qemu-nbd.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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-common.h"
  24. #include "qemu/cutils.h"
  25. #include "sysemu/block-backend.h"
  26. #include "block/block_int.h"
  27. #include "block/nbd.h"
  28. #include "qemu/main-loop.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/qstring.h"
  36. #include "qom/object_interfaces.h"
  37. #include "io/channel-socket.h"
  38. #include "crypto/init.h"
  39. #include "trace/control.h"
  40. #include "qemu-version.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. QEMU_HELP_BOTTOM "\n"
  120. , name, NBD_DEFAULT_PORT, "DEVICE");
  121. }
  122. static void version(const char *name)
  123. {
  124. printf(
  125. "%s " QEMU_VERSION QEMU_PKGVERSION "\n"
  126. "Written by Anthony Liguori.\n"
  127. "\n"
  128. QEMU_COPYRIGHT "\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. NBDExportInfo info = { .request_sizes = false, };
  234. QIOChannelSocket *sioc;
  235. int fd;
  236. int ret;
  237. pthread_t show_parts_thread;
  238. Error *local_error = NULL;
  239. sioc = qio_channel_socket_new();
  240. if (qio_channel_socket_connect_sync(sioc,
  241. saddr,
  242. &local_error) < 0) {
  243. error_report_err(local_error);
  244. goto out;
  245. }
  246. ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL,
  247. NULL, NULL, NULL, &info, &local_error);
  248. if (ret < 0) {
  249. if (local_error) {
  250. error_report_err(local_error);
  251. }
  252. goto out_socket;
  253. }
  254. fd = open(device, O_RDWR);
  255. if (fd < 0) {
  256. /* Linux-only, we can use %m in printf. */
  257. error_report("Failed to open %s: %m", device);
  258. goto out_socket;
  259. }
  260. ret = nbd_init(fd, sioc, &info, &local_error);
  261. if (ret < 0) {
  262. error_report_err(local_error);
  263. goto out_fd;
  264. }
  265. /* update partition table */
  266. pthread_create(&show_parts_thread, NULL, show_parts, device);
  267. if (verbose) {
  268. fprintf(stderr, "NBD device %s is now connected to %s\n",
  269. device, srcpath);
  270. } else {
  271. /* Close stderr so that the qemu-nbd process exits. */
  272. dup2(STDOUT_FILENO, STDERR_FILENO);
  273. }
  274. ret = nbd_client(fd);
  275. if (ret) {
  276. goto out_fd;
  277. }
  278. close(fd);
  279. object_unref(OBJECT(sioc));
  280. kill(getpid(), SIGTERM);
  281. return (void *) EXIT_SUCCESS;
  282. out_fd:
  283. close(fd);
  284. out_socket:
  285. object_unref(OBJECT(sioc));
  286. out:
  287. kill(getpid(), SIGTERM);
  288. return (void *) EXIT_FAILURE;
  289. }
  290. static int nbd_can_accept(void)
  291. {
  292. return state == RUNNING && nb_fds < shared;
  293. }
  294. static void nbd_export_closed(NBDExport *exp)
  295. {
  296. assert(state == TERMINATING);
  297. state = TERMINATED;
  298. }
  299. static void nbd_update_server_watch(void);
  300. static void nbd_client_closed(NBDClient *client, bool negotiated)
  301. {
  302. nb_fds--;
  303. if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
  304. state = TERMINATE;
  305. }
  306. nbd_update_server_watch();
  307. nbd_client_put(client);
  308. }
  309. static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
  310. {
  311. QIOChannelSocket *cioc;
  312. cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
  313. NULL);
  314. if (!cioc) {
  315. return TRUE;
  316. }
  317. if (state >= TERMINATE) {
  318. object_unref(OBJECT(cioc));
  319. return TRUE;
  320. }
  321. nb_fds++;
  322. nbd_update_server_watch();
  323. nbd_client_new(newproto ? NULL : exp, cioc,
  324. tlscreds, NULL, nbd_client_closed);
  325. object_unref(OBJECT(cioc));
  326. return TRUE;
  327. }
  328. static void nbd_update_server_watch(void)
  329. {
  330. if (nbd_can_accept()) {
  331. if (server_watch == -1) {
  332. server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
  333. G_IO_IN,
  334. nbd_accept,
  335. NULL, NULL);
  336. }
  337. } else {
  338. if (server_watch != -1) {
  339. g_source_remove(server_watch);
  340. server_watch = -1;
  341. }
  342. }
  343. }
  344. static SocketAddress *nbd_build_socket_address(const char *sockpath,
  345. const char *bindto,
  346. const char *port)
  347. {
  348. SocketAddress *saddr;
  349. saddr = g_new0(SocketAddress, 1);
  350. if (sockpath) {
  351. saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
  352. saddr->u.q_unix.path = g_strdup(sockpath);
  353. } else {
  354. InetSocketAddress *inet;
  355. saddr->type = SOCKET_ADDRESS_TYPE_INET;
  356. inet = &saddr->u.inet;
  357. inet->host = g_strdup(bindto);
  358. if (port) {
  359. inet->port = g_strdup(port);
  360. } else {
  361. inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
  362. }
  363. }
  364. return saddr;
  365. }
  366. static QemuOptsList file_opts = {
  367. .name = "file",
  368. .implied_opt_name = "file",
  369. .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
  370. .desc = {
  371. /* no elements => accept any params */
  372. { /* end of list */ }
  373. },
  374. };
  375. static QemuOptsList qemu_object_opts = {
  376. .name = "object",
  377. .implied_opt_name = "qom-type",
  378. .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
  379. .desc = {
  380. { }
  381. },
  382. };
  383. static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
  384. {
  385. Object *obj;
  386. QCryptoTLSCreds *creds;
  387. obj = object_resolve_path_component(
  388. object_get_objects_root(), id);
  389. if (!obj) {
  390. error_setg(errp, "No TLS credentials with id '%s'",
  391. id);
  392. return NULL;
  393. }
  394. creds = (QCryptoTLSCreds *)
  395. object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
  396. if (!creds) {
  397. error_setg(errp, "Object with id '%s' is not TLS credentials",
  398. id);
  399. return NULL;
  400. }
  401. if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
  402. error_setg(errp,
  403. "Expecting TLS credentials with a server endpoint");
  404. return NULL;
  405. }
  406. object_ref(obj);
  407. return creds;
  408. }
  409. static void setup_address_and_port(const char **address, const char **port)
  410. {
  411. if (*address == NULL) {
  412. *address = "0.0.0.0";
  413. }
  414. if (*port == NULL) {
  415. *port = stringify(NBD_DEFAULT_PORT);
  416. }
  417. }
  418. /*
  419. * Check socket parameters compatibility when socket activation is used.
  420. */
  421. static const char *socket_activation_validate_opts(const char *device,
  422. const char *sockpath,
  423. const char *address,
  424. const char *port)
  425. {
  426. if (device != NULL) {
  427. return "NBD device can't be set when using socket activation";
  428. }
  429. if (sockpath != NULL) {
  430. return "Unix socket can't be set when using socket activation";
  431. }
  432. if (address != NULL) {
  433. return "The interface can't be set when using socket activation";
  434. }
  435. if (port != NULL) {
  436. return "TCP port number can't be set when using socket activation";
  437. }
  438. return NULL;
  439. }
  440. int main(int argc, char **argv)
  441. {
  442. BlockBackend *blk;
  443. BlockDriverState *bs;
  444. off_t dev_offset = 0;
  445. uint16_t nbdflags = 0;
  446. bool disconnect = false;
  447. const char *bindto = NULL;
  448. const char *port = NULL;
  449. char *sockpath = NULL;
  450. char *device = NULL;
  451. off_t fd_size;
  452. QemuOpts *sn_opts = NULL;
  453. const char *sn_id_or_name = NULL;
  454. const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:T:D:";
  455. struct option lopt[] = {
  456. { "help", no_argument, NULL, 'h' },
  457. { "version", no_argument, NULL, 'V' },
  458. { "bind", required_argument, NULL, 'b' },
  459. { "port", required_argument, NULL, 'p' },
  460. { "socket", required_argument, NULL, 'k' },
  461. { "offset", required_argument, NULL, 'o' },
  462. { "read-only", no_argument, NULL, 'r' },
  463. { "partition", required_argument, NULL, 'P' },
  464. { "connect", required_argument, NULL, 'c' },
  465. { "disconnect", no_argument, NULL, 'd' },
  466. { "snapshot", no_argument, NULL, 's' },
  467. { "load-snapshot", required_argument, NULL, 'l' },
  468. { "nocache", no_argument, NULL, 'n' },
  469. { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
  470. { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
  471. { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
  472. { "detect-zeroes", required_argument, NULL,
  473. QEMU_NBD_OPT_DETECT_ZEROES },
  474. { "shared", required_argument, NULL, 'e' },
  475. { "format", required_argument, NULL, 'f' },
  476. { "persistent", no_argument, NULL, 't' },
  477. { "verbose", no_argument, NULL, 'v' },
  478. { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
  479. { "export-name", required_argument, NULL, 'x' },
  480. { "description", required_argument, NULL, 'D' },
  481. { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
  482. { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
  483. { "trace", required_argument, NULL, 'T' },
  484. { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
  485. { NULL, 0, NULL, 0 }
  486. };
  487. int ch;
  488. int opt_ind = 0;
  489. char *end;
  490. int flags = BDRV_O_RDWR;
  491. int partition = -1;
  492. int ret = 0;
  493. bool seen_cache = false;
  494. bool seen_discard = false;
  495. bool seen_aio = false;
  496. pthread_t client_thread;
  497. const char *fmt = NULL;
  498. Error *local_err = NULL;
  499. BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
  500. QDict *options = NULL;
  501. const char *export_name = NULL;
  502. const char *export_description = NULL;
  503. const char *tlscredsid = NULL;
  504. bool imageOpts = false;
  505. bool writethrough = true;
  506. char *trace_file = NULL;
  507. bool fork_process = false;
  508. int old_stderr = -1;
  509. unsigned socket_activation;
  510. /* The client thread uses SIGTERM to interrupt the server. A signal
  511. * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
  512. */
  513. struct sigaction sa_sigterm;
  514. memset(&sa_sigterm, 0, sizeof(sa_sigterm));
  515. sa_sigterm.sa_handler = termsig_handler;
  516. sigaction(SIGTERM, &sa_sigterm, NULL);
  517. #ifdef CONFIG_POSIX
  518. signal(SIGPIPE, SIG_IGN);
  519. #endif
  520. module_call_init(MODULE_INIT_TRACE);
  521. qcrypto_init(&error_fatal);
  522. module_call_init(MODULE_INIT_QOM);
  523. qemu_add_opts(&qemu_object_opts);
  524. qemu_add_opts(&qemu_trace_opts);
  525. qemu_init_exec_dir(argv[0]);
  526. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  527. switch (ch) {
  528. case 's':
  529. flags |= BDRV_O_SNAPSHOT;
  530. break;
  531. case 'n':
  532. optarg = (char *) "none";
  533. /* fallthrough */
  534. case QEMU_NBD_OPT_CACHE:
  535. if (seen_cache) {
  536. error_report("-n and --cache can only be specified once");
  537. exit(EXIT_FAILURE);
  538. }
  539. seen_cache = true;
  540. if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
  541. error_report("Invalid cache mode `%s'", optarg);
  542. exit(EXIT_FAILURE);
  543. }
  544. break;
  545. case QEMU_NBD_OPT_AIO:
  546. if (seen_aio) {
  547. error_report("--aio can only be specified once");
  548. exit(EXIT_FAILURE);
  549. }
  550. seen_aio = true;
  551. if (!strcmp(optarg, "native")) {
  552. flags |= BDRV_O_NATIVE_AIO;
  553. } else if (!strcmp(optarg, "threads")) {
  554. /* this is the default */
  555. } else {
  556. error_report("invalid aio mode `%s'", optarg);
  557. exit(EXIT_FAILURE);
  558. }
  559. break;
  560. case QEMU_NBD_OPT_DISCARD:
  561. if (seen_discard) {
  562. error_report("--discard can only be specified once");
  563. exit(EXIT_FAILURE);
  564. }
  565. seen_discard = true;
  566. if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
  567. error_report("Invalid discard mode `%s'", optarg);
  568. exit(EXIT_FAILURE);
  569. }
  570. break;
  571. case QEMU_NBD_OPT_DETECT_ZEROES:
  572. detect_zeroes =
  573. qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
  574. optarg,
  575. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
  576. &local_err);
  577. if (local_err) {
  578. error_reportf_err(local_err,
  579. "Failed to parse detect_zeroes mode: ");
  580. exit(EXIT_FAILURE);
  581. }
  582. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  583. !(flags & BDRV_O_UNMAP)) {
  584. error_report("setting detect-zeroes to unmap is not allowed "
  585. "without setting discard operation to unmap");
  586. exit(EXIT_FAILURE);
  587. }
  588. break;
  589. case 'b':
  590. bindto = optarg;
  591. break;
  592. case 'p':
  593. port = optarg;
  594. break;
  595. case 'o':
  596. dev_offset = strtoll (optarg, &end, 0);
  597. if (*end) {
  598. error_report("Invalid offset `%s'", optarg);
  599. exit(EXIT_FAILURE);
  600. }
  601. if (dev_offset < 0) {
  602. error_report("Offset must be positive `%s'", optarg);
  603. exit(EXIT_FAILURE);
  604. }
  605. break;
  606. case 'l':
  607. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  608. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  609. optarg, false);
  610. if (!sn_opts) {
  611. error_report("Failed in parsing snapshot param `%s'",
  612. optarg);
  613. exit(EXIT_FAILURE);
  614. }
  615. } else {
  616. sn_id_or_name = optarg;
  617. }
  618. /* fall through */
  619. case 'r':
  620. nbdflags |= NBD_FLAG_READ_ONLY;
  621. flags &= ~BDRV_O_RDWR;
  622. break;
  623. case 'P':
  624. partition = strtol(optarg, &end, 0);
  625. if (*end) {
  626. error_report("Invalid partition `%s'", optarg);
  627. exit(EXIT_FAILURE);
  628. }
  629. if (partition < 1 || partition > 8) {
  630. error_report("Invalid partition %d", partition);
  631. exit(EXIT_FAILURE);
  632. }
  633. break;
  634. case 'k':
  635. sockpath = optarg;
  636. if (sockpath[0] != '/') {
  637. error_report("socket path must be absolute");
  638. exit(EXIT_FAILURE);
  639. }
  640. break;
  641. case 'd':
  642. disconnect = true;
  643. break;
  644. case 'c':
  645. device = optarg;
  646. break;
  647. case 'e':
  648. shared = strtol(optarg, &end, 0);
  649. if (*end) {
  650. error_report("Invalid shared device number '%s'", optarg);
  651. exit(EXIT_FAILURE);
  652. }
  653. if (shared < 1) {
  654. error_report("Shared device number must be greater than 0");
  655. exit(EXIT_FAILURE);
  656. }
  657. break;
  658. case 'f':
  659. fmt = optarg;
  660. break;
  661. case 't':
  662. persistent = 1;
  663. break;
  664. case 'x':
  665. export_name = optarg;
  666. break;
  667. case 'D':
  668. export_description = optarg;
  669. break;
  670. case 'v':
  671. verbose = 1;
  672. break;
  673. case 'V':
  674. version(argv[0]);
  675. exit(0);
  676. break;
  677. case 'h':
  678. usage(argv[0]);
  679. exit(0);
  680. break;
  681. case '?':
  682. error_report("Try `%s --help' for more information.", argv[0]);
  683. exit(EXIT_FAILURE);
  684. case QEMU_NBD_OPT_OBJECT: {
  685. QemuOpts *opts;
  686. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  687. optarg, true);
  688. if (!opts) {
  689. exit(EXIT_FAILURE);
  690. }
  691. } break;
  692. case QEMU_NBD_OPT_TLSCREDS:
  693. tlscredsid = optarg;
  694. break;
  695. case QEMU_NBD_OPT_IMAGE_OPTS:
  696. imageOpts = true;
  697. break;
  698. case 'T':
  699. g_free(trace_file);
  700. trace_file = trace_opt_parse(optarg);
  701. break;
  702. case QEMU_NBD_OPT_FORK:
  703. fork_process = true;
  704. break;
  705. }
  706. }
  707. if ((argc - optind) != 1) {
  708. error_report("Invalid number of arguments");
  709. error_printf("Try `%s --help' for more information.\n", argv[0]);
  710. exit(EXIT_FAILURE);
  711. }
  712. if (qemu_opts_foreach(&qemu_object_opts,
  713. user_creatable_add_opts_foreach,
  714. NULL, NULL)) {
  715. exit(EXIT_FAILURE);
  716. }
  717. if (!trace_init_backends()) {
  718. exit(1);
  719. }
  720. trace_init_file(trace_file);
  721. qemu_set_log(LOG_TRACE);
  722. socket_activation = check_socket_activation();
  723. if (socket_activation == 0) {
  724. setup_address_and_port(&bindto, &port);
  725. } else {
  726. /* Using socket activation - check user didn't use -p etc. */
  727. const char *err_msg = socket_activation_validate_opts(device, sockpath,
  728. bindto, port);
  729. if (err_msg != NULL) {
  730. error_report("%s", err_msg);
  731. exit(EXIT_FAILURE);
  732. }
  733. /* qemu-nbd can only listen on a single socket. */
  734. if (socket_activation > 1) {
  735. error_report("qemu-nbd does not support socket activation with %s > 1",
  736. "LISTEN_FDS");
  737. exit(EXIT_FAILURE);
  738. }
  739. }
  740. if (tlscredsid) {
  741. if (sockpath) {
  742. error_report("TLS is only supported with IPv4/IPv6");
  743. exit(EXIT_FAILURE);
  744. }
  745. if (device) {
  746. error_report("TLS is not supported with a host device");
  747. exit(EXIT_FAILURE);
  748. }
  749. if (!export_name) {
  750. /* Set the default NBD protocol export name, since
  751. * we *must* use new style protocol for TLS */
  752. export_name = "";
  753. }
  754. tlscreds = nbd_get_tls_creds(tlscredsid, &local_err);
  755. if (local_err) {
  756. error_report("Failed to get TLS creds %s",
  757. error_get_pretty(local_err));
  758. exit(EXIT_FAILURE);
  759. }
  760. }
  761. if (disconnect) {
  762. int nbdfd = open(argv[optind], O_RDWR);
  763. if (nbdfd < 0) {
  764. error_report("Cannot open %s: %s", argv[optind],
  765. strerror(errno));
  766. exit(EXIT_FAILURE);
  767. }
  768. nbd_disconnect(nbdfd);
  769. close(nbdfd);
  770. printf("%s disconnected\n", argv[optind]);
  771. return 0;
  772. }
  773. if ((device && !verbose) || fork_process) {
  774. int stderr_fd[2];
  775. pid_t pid;
  776. int ret;
  777. if (qemu_pipe(stderr_fd) < 0) {
  778. error_report("Error setting up communication pipe: %s",
  779. strerror(errno));
  780. exit(EXIT_FAILURE);
  781. }
  782. /* Now daemonize, but keep a communication channel open to
  783. * print errors and exit with the proper status code.
  784. */
  785. pid = fork();
  786. if (pid < 0) {
  787. error_report("Failed to fork: %s", strerror(errno));
  788. exit(EXIT_FAILURE);
  789. } else if (pid == 0) {
  790. close(stderr_fd[0]);
  791. ret = qemu_daemon(1, 0);
  792. /* Temporarily redirect stderr to the parent's pipe... */
  793. old_stderr = dup(STDERR_FILENO);
  794. dup2(stderr_fd[1], STDERR_FILENO);
  795. if (ret < 0) {
  796. error_report("Failed to daemonize: %s", strerror(errno));
  797. exit(EXIT_FAILURE);
  798. }
  799. /* ... close the descriptor we inherited and go on. */
  800. close(stderr_fd[1]);
  801. } else {
  802. bool errors = false;
  803. char *buf;
  804. /* In the parent. Print error messages from the child until
  805. * it closes the pipe.
  806. */
  807. close(stderr_fd[1]);
  808. buf = g_malloc(1024);
  809. while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
  810. errors = true;
  811. ret = qemu_write_full(STDERR_FILENO, buf, ret);
  812. if (ret < 0) {
  813. exit(EXIT_FAILURE);
  814. }
  815. }
  816. if (ret < 0) {
  817. error_report("Cannot read from daemon: %s",
  818. strerror(errno));
  819. exit(EXIT_FAILURE);
  820. }
  821. /* Usually the daemon should not print any message.
  822. * Exit with zero status in that case.
  823. */
  824. exit(errors);
  825. }
  826. }
  827. if (device != NULL && sockpath == NULL) {
  828. sockpath = g_malloc(128);
  829. snprintf(sockpath, 128, SOCKET_PATH, basename(device));
  830. }
  831. if (socket_activation == 0) {
  832. server_ioc = qio_channel_socket_new();
  833. saddr = nbd_build_socket_address(sockpath, bindto, port);
  834. if (qio_channel_socket_listen_sync(server_ioc, saddr, &local_err) < 0) {
  835. object_unref(OBJECT(server_ioc));
  836. error_report_err(local_err);
  837. return 1;
  838. }
  839. } else {
  840. /* See comment in check_socket_activation above. */
  841. assert(socket_activation == 1);
  842. server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD,
  843. &local_err);
  844. if (server_ioc == NULL) {
  845. error_report("Failed to use socket activation: %s",
  846. error_get_pretty(local_err));
  847. exit(EXIT_FAILURE);
  848. }
  849. }
  850. if (qemu_init_main_loop(&local_err)) {
  851. error_report_err(local_err);
  852. exit(EXIT_FAILURE);
  853. }
  854. bdrv_init();
  855. atexit(bdrv_close_all);
  856. srcpath = argv[optind];
  857. if (imageOpts) {
  858. QemuOpts *opts;
  859. if (fmt) {
  860. error_report("--image-opts and -f are mutually exclusive");
  861. exit(EXIT_FAILURE);
  862. }
  863. opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
  864. if (!opts) {
  865. qemu_opts_reset(&file_opts);
  866. exit(EXIT_FAILURE);
  867. }
  868. options = qemu_opts_to_qdict(opts, NULL);
  869. qemu_opts_reset(&file_opts);
  870. blk = blk_new_open(NULL, NULL, options, flags, &local_err);
  871. } else {
  872. if (fmt) {
  873. options = qdict_new();
  874. qdict_put_str(options, "driver", fmt);
  875. }
  876. blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
  877. }
  878. if (!blk) {
  879. error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
  880. argv[optind]);
  881. exit(EXIT_FAILURE);
  882. }
  883. bs = blk_bs(blk);
  884. blk_set_enable_write_cache(blk, !writethrough);
  885. if (sn_opts) {
  886. ret = bdrv_snapshot_load_tmp(bs,
  887. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  888. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  889. &local_err);
  890. } else if (sn_id_or_name) {
  891. ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
  892. &local_err);
  893. }
  894. if (ret < 0) {
  895. error_reportf_err(local_err, "Failed to load snapshot: ");
  896. exit(EXIT_FAILURE);
  897. }
  898. bs->detect_zeroes = detect_zeroes;
  899. fd_size = blk_getlength(blk);
  900. if (fd_size < 0) {
  901. error_report("Failed to determine the image length: %s",
  902. strerror(-fd_size));
  903. exit(EXIT_FAILURE);
  904. }
  905. if (dev_offset >= fd_size) {
  906. error_report("Offset (%lld) has to be smaller than the image size "
  907. "(%lld)",
  908. (long long int)dev_offset, (long long int)fd_size);
  909. exit(EXIT_FAILURE);
  910. }
  911. fd_size -= dev_offset;
  912. if (partition != -1) {
  913. ret = find_partition(blk, partition, &dev_offset, &fd_size);
  914. if (ret < 0) {
  915. error_report("Could not find partition %d: %s", partition,
  916. strerror(-ret));
  917. exit(EXIT_FAILURE);
  918. }
  919. }
  920. exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags, nbd_export_closed,
  921. writethrough, NULL, &local_err);
  922. if (!exp) {
  923. error_report_err(local_err);
  924. exit(EXIT_FAILURE);
  925. }
  926. if (export_name) {
  927. nbd_export_set_name(exp, export_name);
  928. nbd_export_set_description(exp, export_description);
  929. newproto = true;
  930. } else if (export_description) {
  931. error_report("Export description requires an export name");
  932. exit(EXIT_FAILURE);
  933. }
  934. if (device) {
  935. int ret;
  936. ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
  937. if (ret != 0) {
  938. error_report("Failed to create client thread: %s", strerror(ret));
  939. exit(EXIT_FAILURE);
  940. }
  941. } else {
  942. /* Shut up GCC warnings. */
  943. memset(&client_thread, 0, sizeof(client_thread));
  944. }
  945. nbd_update_server_watch();
  946. /* now when the initialization is (almost) complete, chdir("/")
  947. * to free any busy filesystems */
  948. if (chdir("/") < 0) {
  949. error_report("Could not chdir to root directory: %s",
  950. strerror(errno));
  951. exit(EXIT_FAILURE);
  952. }
  953. if (fork_process) {
  954. dup2(old_stderr, STDERR_FILENO);
  955. close(old_stderr);
  956. }
  957. state = RUNNING;
  958. do {
  959. main_loop_wait(false);
  960. if (state == TERMINATE) {
  961. state = TERMINATING;
  962. nbd_export_close(exp);
  963. nbd_export_put(exp);
  964. exp = NULL;
  965. }
  966. } while (state != TERMINATED);
  967. blk_unref(blk);
  968. if (sockpath) {
  969. unlink(sockpath);
  970. }
  971. qemu_opts_del(sn_opts);
  972. if (device) {
  973. void *ret;
  974. pthread_join(client_thread, &ret);
  975. exit(ret != NULL);
  976. } else {
  977. exit(EXIT_SUCCESS);
  978. }
  979. }