qemu-nbd.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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 "qemu/help-texts.h"
  23. #include "qapi/error.h"
  24. #include "qemu/cutils.h"
  25. #include "sysemu/block-backend.h"
  26. #include "sysemu/runstate.h" /* for qemu_system_killed() prototype */
  27. #include "block/block_int.h"
  28. #include "block/nbd.h"
  29. #include "qemu/main-loop.h"
  30. #include "qemu/module.h"
  31. #include "qemu/option.h"
  32. #include "qemu/error-report.h"
  33. #include "qemu/config-file.h"
  34. #include "qemu/bswap.h"
  35. #include "qemu/log.h"
  36. #include "qemu/systemd.h"
  37. #include "block/snapshot.h"
  38. #include "qapi/qmp/qdict.h"
  39. #include "qapi/qmp/qstring.h"
  40. #include "qom/object_interfaces.h"
  41. #include "io/channel-socket.h"
  42. #include "io/net-listener.h"
  43. #include "crypto/init.h"
  44. #include "crypto/tlscreds.h"
  45. #include "trace/control.h"
  46. #include "qemu-version.h"
  47. #ifdef CONFIG_SELINUX
  48. #include <selinux/selinux.h>
  49. #endif
  50. #ifdef __linux__
  51. #define HAVE_NBD_DEVICE 1
  52. #else
  53. #define HAVE_NBD_DEVICE 0
  54. #endif
  55. #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
  56. #define QEMU_NBD_OPT_CACHE 256
  57. #define QEMU_NBD_OPT_AIO 257
  58. #define QEMU_NBD_OPT_DISCARD 258
  59. #define QEMU_NBD_OPT_DETECT_ZEROES 259
  60. #define QEMU_NBD_OPT_OBJECT 260
  61. #define QEMU_NBD_OPT_TLSCREDS 261
  62. #define QEMU_NBD_OPT_IMAGE_OPTS 262
  63. #define QEMU_NBD_OPT_FORK 263
  64. #define QEMU_NBD_OPT_TLSAUTHZ 264
  65. #define QEMU_NBD_OPT_PID_FILE 265
  66. #define QEMU_NBD_OPT_SELINUX_LABEL 266
  67. #define QEMU_NBD_OPT_TLSHOSTNAME 267
  68. #define MBR_SIZE 512
  69. static int persistent = 0;
  70. static enum { RUNNING, TERMINATE, TERMINATED } state;
  71. static int shared = 1;
  72. static int nb_fds;
  73. static QIONetListener *server;
  74. static QCryptoTLSCreds *tlscreds;
  75. static const char *tlsauthz;
  76. static void usage(const char *name)
  77. {
  78. (printf) (
  79. "Usage: %s [OPTIONS] FILE\n"
  80. " or: %s -L [OPTIONS]\n"
  81. "QEMU Disk Network Block Device Utility\n"
  82. "\n"
  83. " -h, --help display this help and exit\n"
  84. " -V, --version output version information and exit\n"
  85. "\n"
  86. "Connection properties:\n"
  87. " -p, --port=PORT port to listen on (default `%d')\n"
  88. " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
  89. " -k, --socket=PATH path to the unix socket\n"
  90. " (default '"SOCKET_PATH"')\n"
  91. " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
  92. " -t, --persistent don't exit on the last connection\n"
  93. " -v, --verbose display extra debugging information\n"
  94. " -x, --export-name=NAME expose export by name (default is empty string)\n"
  95. " -D, --description=TEXT export a human-readable description\n"
  96. "\n"
  97. "Exposing part of the image:\n"
  98. " -o, --offset=OFFSET offset into the image\n"
  99. " -A, --allocation-depth expose the allocation depth\n"
  100. " -B, --bitmap=NAME expose a persistent dirty bitmap\n"
  101. "\n"
  102. "General purpose options:\n"
  103. " -L, --list list exports available from another NBD server\n"
  104. " --object type,id=ID,... define an object such as 'secret' for providing\n"
  105. " passwords and/or encryption keys\n"
  106. " --tls-creds=ID use id of an earlier --object to provide TLS\n"
  107. " --tls-authz=ID use id of an earlier --object to provide\n"
  108. " authorization\n"
  109. " --tls-hostname=HOSTNAME override hostname used to check x509 certificate\n"
  110. " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
  111. " specify tracing options\n"
  112. " --fork fork off the server process and exit the parent\n"
  113. " once the server is running\n"
  114. " --pid-file=PATH store the server's process ID in the given file\n"
  115. #ifdef CONFIG_SELINUX
  116. " --selinux-label=LABEL set SELinux process label on listening socket\n"
  117. #endif
  118. #if HAVE_NBD_DEVICE
  119. "\n"
  120. "Kernel NBD client support:\n"
  121. " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
  122. " -d, --disconnect disconnect the specified device\n"
  123. #endif
  124. "\n"
  125. "Block device options:\n"
  126. " -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
  127. " -r, --read-only export read-only\n"
  128. " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
  129. " file with backing_file=FILE, redirect the write to\n"
  130. " the temporary one\n"
  131. " -l, --load-snapshot=SNAPSHOT_PARAM\n"
  132. " load an internal snapshot inside FILE and export it\n"
  133. " as an read-only device, SNAPSHOT_PARAM format is\n"
  134. " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
  135. " '[ID_OR_NAME]'\n"
  136. " -n, --nocache disable host cache\n"
  137. " --cache=MODE set cache mode used to access the disk image, the\n"
  138. " valid options are: 'none', 'writeback' (default),\n"
  139. " 'writethrough', 'directsync' and 'unsafe'\n"
  140. " --aio=MODE set AIO mode (native, io_uring or threads)\n"
  141. " --discard=MODE set discard mode (ignore, unmap)\n"
  142. " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
  143. " --image-opts treat FILE as a full set of image options\n"
  144. "\n"
  145. QEMU_HELP_BOTTOM "\n"
  146. , name, name, NBD_DEFAULT_PORT, "DEVICE");
  147. }
  148. static void version(const char *name)
  149. {
  150. printf(
  151. "%s " QEMU_FULL_VERSION "\n"
  152. "Written by Anthony Liguori.\n"
  153. "\n"
  154. QEMU_COPYRIGHT "\n"
  155. "This is free software; see the source for copying conditions. There is NO\n"
  156. "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
  157. , name);
  158. }
  159. #ifdef CONFIG_POSIX
  160. /*
  161. * The client thread uses SIGTERM to interrupt the server. A signal
  162. * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
  163. */
  164. void qemu_system_killed(int signum, pid_t pid)
  165. {
  166. qatomic_cmpxchg(&state, RUNNING, TERMINATE);
  167. qemu_notify_event();
  168. }
  169. #endif /* CONFIG_POSIX */
  170. static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
  171. const char *hostname)
  172. {
  173. int ret = EXIT_FAILURE;
  174. int rc;
  175. Error *err = NULL;
  176. QIOChannelSocket *sioc;
  177. NBDExportInfo *list;
  178. int i, j;
  179. sioc = qio_channel_socket_new();
  180. if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
  181. error_report_err(err);
  182. goto out;
  183. }
  184. rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
  185. &err);
  186. if (rc < 0) {
  187. if (err) {
  188. error_report_err(err);
  189. }
  190. goto out;
  191. }
  192. printf("exports available: %d\n", rc);
  193. for (i = 0; i < rc; i++) {
  194. printf(" export: '%s'\n", list[i].name);
  195. if (list[i].description && *list[i].description) {
  196. printf(" description: %s\n", list[i].description);
  197. }
  198. if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
  199. static const char *const flag_names[] = {
  200. [NBD_FLAG_READ_ONLY_BIT] = "readonly",
  201. [NBD_FLAG_SEND_FLUSH_BIT] = "flush",
  202. [NBD_FLAG_SEND_FUA_BIT] = "fua",
  203. [NBD_FLAG_ROTATIONAL_BIT] = "rotational",
  204. [NBD_FLAG_SEND_TRIM_BIT] = "trim",
  205. [NBD_FLAG_SEND_WRITE_ZEROES_BIT] = "zeroes",
  206. [NBD_FLAG_SEND_DF_BIT] = "df",
  207. [NBD_FLAG_CAN_MULTI_CONN_BIT] = "multi",
  208. [NBD_FLAG_SEND_RESIZE_BIT] = "resize",
  209. [NBD_FLAG_SEND_CACHE_BIT] = "cache",
  210. [NBD_FLAG_SEND_FAST_ZERO_BIT] = "fast-zero",
  211. [NBD_FLAG_BLOCK_STAT_PAYLOAD_BIT] = "block-status-payload",
  212. };
  213. printf(" size: %" PRIu64 "\n", list[i].size);
  214. printf(" flags: 0x%x (", list[i].flags);
  215. for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
  216. if (flag_names[bit] && (list[i].flags & (1 << bit))) {
  217. printf(" %s", flag_names[bit]);
  218. }
  219. }
  220. printf(" )\n");
  221. }
  222. if (list[i].min_block) {
  223. printf(" min block: %u\n", list[i].min_block);
  224. printf(" opt block: %u\n", list[i].opt_block);
  225. printf(" max block: %u\n", list[i].max_block);
  226. }
  227. printf(" transaction size: %s\n",
  228. list[i].mode >= NBD_MODE_EXTENDED ?
  229. "64-bit" : "32-bit");
  230. if (list[i].n_contexts) {
  231. printf(" available meta contexts: %d\n", list[i].n_contexts);
  232. for (j = 0; j < list[i].n_contexts; j++) {
  233. printf(" %s\n", list[i].contexts[j]);
  234. }
  235. }
  236. }
  237. nbd_free_export_list(list, rc);
  238. ret = EXIT_SUCCESS;
  239. out:
  240. object_unref(OBJECT(sioc));
  241. return ret;
  242. }
  243. struct NbdClientOpts {
  244. char *device;
  245. char *srcpath;
  246. SocketAddress *saddr;
  247. int old_stderr;
  248. bool fork_process;
  249. bool verbose;
  250. };
  251. static void nbd_client_release_pipe(int old_stderr)
  252. {
  253. /* Close stderr so that the qemu-nbd process exits. */
  254. if (dup2(old_stderr, STDERR_FILENO) < 0) {
  255. error_report("Could not release pipe to parent: %s",
  256. strerror(errno));
  257. exit(EXIT_FAILURE);
  258. }
  259. if (old_stderr != STDOUT_FILENO && close(old_stderr) < 0) {
  260. error_report("Could not release qemu-nbd: %s", strerror(errno));
  261. exit(EXIT_FAILURE);
  262. }
  263. }
  264. #if HAVE_NBD_DEVICE
  265. static void *show_parts(void *arg)
  266. {
  267. char *device = arg;
  268. int nbd;
  269. /* linux just needs an open() to trigger
  270. * the partition table update
  271. * but remember to load the module with max_part != 0 :
  272. * modprobe nbd max_part=63
  273. */
  274. nbd = open(device, O_RDWR);
  275. if (nbd >= 0) {
  276. close(nbd);
  277. }
  278. return NULL;
  279. }
  280. static void *nbd_client_thread(void *arg)
  281. {
  282. struct NbdClientOpts *opts = arg;
  283. /* TODO: Revisit this if nbd.ko ever gains support for structured reply */
  284. NBDExportInfo info = { .request_sizes = false, .name = g_strdup(""),
  285. .mode = NBD_MODE_SIMPLE };
  286. QIOChannelSocket *sioc;
  287. int fd = -1;
  288. int ret = EXIT_FAILURE;
  289. pthread_t show_parts_thread;
  290. Error *local_error = NULL;
  291. sioc = qio_channel_socket_new();
  292. if (qio_channel_socket_connect_sync(sioc,
  293. opts->saddr,
  294. &local_error) < 0) {
  295. error_report_err(local_error);
  296. goto out;
  297. }
  298. if (nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, NULL, NULL,
  299. &info, &local_error) < 0) {
  300. if (local_error) {
  301. error_report_err(local_error);
  302. }
  303. goto out;
  304. }
  305. fd = open(opts->device, O_RDWR);
  306. if (fd < 0) {
  307. /* Linux-only, we can use %m in printf. */
  308. error_report("Failed to open %s: %m", opts->device);
  309. goto out;
  310. }
  311. if (nbd_init(fd, sioc, &info, &local_error) < 0) {
  312. error_report_err(local_error);
  313. goto out;
  314. }
  315. /* update partition table */
  316. pthread_create(&show_parts_thread, NULL, show_parts, opts->device);
  317. if (opts->verbose && !opts->fork_process) {
  318. fprintf(stderr, "NBD device %s is now connected to %s\n",
  319. opts->device, opts->srcpath);
  320. } else {
  321. nbd_client_release_pipe(opts->old_stderr);
  322. }
  323. if (nbd_client(fd) < 0) {
  324. goto out;
  325. }
  326. ret = EXIT_SUCCESS;
  327. out:
  328. if (fd >= 0) {
  329. close(fd);
  330. }
  331. object_unref(OBJECT(sioc));
  332. g_free(info.name);
  333. kill(getpid(), SIGTERM);
  334. return (void *) (intptr_t) ret;
  335. }
  336. #endif /* HAVE_NBD_DEVICE */
  337. static int nbd_can_accept(void)
  338. {
  339. return state == RUNNING && (shared == 0 || nb_fds < shared);
  340. }
  341. static void nbd_update_server_watch(void);
  342. static void nbd_client_closed(NBDClient *client, bool negotiated)
  343. {
  344. nb_fds--;
  345. if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
  346. state = TERMINATE;
  347. }
  348. nbd_update_server_watch();
  349. nbd_client_put(client);
  350. }
  351. static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
  352. gpointer opaque)
  353. {
  354. if (state >= TERMINATE) {
  355. return;
  356. }
  357. nb_fds++;
  358. nbd_update_server_watch();
  359. nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
  360. }
  361. static void nbd_update_server_watch(void)
  362. {
  363. if (nbd_can_accept()) {
  364. qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
  365. } else {
  366. qio_net_listener_set_client_func(server, NULL, NULL, NULL);
  367. }
  368. }
  369. static SocketAddress *nbd_build_socket_address(const char *sockpath,
  370. const char *bindto,
  371. const char *port)
  372. {
  373. SocketAddress *saddr;
  374. saddr = g_new0(SocketAddress, 1);
  375. if (sockpath) {
  376. saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
  377. saddr->u.q_unix.path = g_strdup(sockpath);
  378. } else {
  379. InetSocketAddress *inet;
  380. saddr->type = SOCKET_ADDRESS_TYPE_INET;
  381. inet = &saddr->u.inet;
  382. inet->host = g_strdup(bindto);
  383. if (port) {
  384. inet->port = g_strdup(port);
  385. } else {
  386. inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
  387. }
  388. }
  389. return saddr;
  390. }
  391. static QemuOptsList file_opts = {
  392. .name = "file",
  393. .implied_opt_name = "file",
  394. .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
  395. .desc = {
  396. /* no elements => accept any params */
  397. { /* end of list */ }
  398. },
  399. };
  400. static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
  401. Error **errp)
  402. {
  403. Object *obj;
  404. QCryptoTLSCreds *creds;
  405. obj = object_resolve_path_component(
  406. object_get_objects_root(), id);
  407. if (!obj) {
  408. error_setg(errp, "No TLS credentials with id '%s'",
  409. id);
  410. return NULL;
  411. }
  412. creds = (QCryptoTLSCreds *)
  413. object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
  414. if (!creds) {
  415. error_setg(errp, "Object with id '%s' is not TLS credentials",
  416. id);
  417. return NULL;
  418. }
  419. if (!qcrypto_tls_creds_check_endpoint(creds,
  420. list
  421. ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
  422. : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
  423. errp)) {
  424. return NULL;
  425. }
  426. object_ref(obj);
  427. return creds;
  428. }
  429. static void setup_address_and_port(const char **address, const char **port)
  430. {
  431. if (*address == NULL) {
  432. *address = "0.0.0.0";
  433. }
  434. if (*port == NULL) {
  435. *port = stringify(NBD_DEFAULT_PORT);
  436. }
  437. }
  438. /*
  439. * Check socket parameters compatibility when socket activation is used.
  440. */
  441. static const char *socket_activation_validate_opts(const char *device,
  442. const char *sockpath,
  443. const char *address,
  444. const char *port,
  445. const char *selinux,
  446. bool list)
  447. {
  448. if (device != NULL) {
  449. return "NBD device can't be set when using socket activation";
  450. }
  451. if (sockpath != NULL) {
  452. return "Unix socket can't be set when using socket activation";
  453. }
  454. if (address != NULL) {
  455. return "The interface can't be set when using socket activation";
  456. }
  457. if (port != NULL) {
  458. return "TCP port number can't be set when using socket activation";
  459. }
  460. if (selinux != NULL) {
  461. return "SELinux label can't be set when using socket activation";
  462. }
  463. if (list) {
  464. return "List mode is incompatible with socket activation";
  465. }
  466. return NULL;
  467. }
  468. static void qemu_nbd_shutdown(void)
  469. {
  470. job_cancel_sync_all();
  471. blk_exp_close_all();
  472. bdrv_close_all();
  473. }
  474. int main(int argc, char **argv)
  475. {
  476. BlockBackend *blk;
  477. BlockDriverState *bs;
  478. uint64_t dev_offset = 0;
  479. bool readonly = false;
  480. bool disconnect = false;
  481. const char *bindto = NULL;
  482. const char *port = NULL;
  483. char *sockpath = NULL;
  484. QemuOpts *sn_opts = NULL;
  485. const char *sn_id_or_name = NULL;
  486. const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
  487. struct option lopt[] = {
  488. { "help", no_argument, NULL, 'h' },
  489. { "version", no_argument, NULL, 'V' },
  490. { "bind", required_argument, NULL, 'b' },
  491. { "port", required_argument, NULL, 'p' },
  492. { "socket", required_argument, NULL, 'k' },
  493. { "offset", required_argument, NULL, 'o' },
  494. { "read-only", no_argument, NULL, 'r' },
  495. { "allocation-depth", no_argument, NULL, 'A' },
  496. { "bitmap", required_argument, NULL, 'B' },
  497. { "connect", required_argument, NULL, 'c' },
  498. { "disconnect", no_argument, NULL, 'd' },
  499. { "list", no_argument, NULL, 'L' },
  500. { "snapshot", no_argument, NULL, 's' },
  501. { "load-snapshot", required_argument, NULL, 'l' },
  502. { "nocache", no_argument, NULL, 'n' },
  503. { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
  504. { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
  505. { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
  506. { "detect-zeroes", required_argument, NULL,
  507. QEMU_NBD_OPT_DETECT_ZEROES },
  508. { "shared", required_argument, NULL, 'e' },
  509. { "format", required_argument, NULL, 'f' },
  510. { "persistent", no_argument, NULL, 't' },
  511. { "verbose", no_argument, NULL, 'v' },
  512. { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
  513. { "export-name", required_argument, NULL, 'x' },
  514. { "description", required_argument, NULL, 'D' },
  515. { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
  516. { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
  517. { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
  518. { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
  519. { "trace", required_argument, NULL, 'T' },
  520. { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
  521. { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
  522. { "selinux-label", required_argument, NULL,
  523. QEMU_NBD_OPT_SELINUX_LABEL },
  524. { NULL, 0, NULL, 0 }
  525. };
  526. int ch;
  527. int opt_ind = 0;
  528. int flags = BDRV_O_RDWR;
  529. int ret = 0;
  530. bool seen_cache = false;
  531. bool seen_discard = false;
  532. bool seen_aio = false;
  533. pthread_t client_thread;
  534. const char *fmt = NULL;
  535. Error *local_err = NULL;
  536. BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
  537. QDict *options = NULL;
  538. const char *export_name = NULL; /* defaults to "" later for server mode */
  539. const char *export_description = NULL;
  540. BlockDirtyBitmapOrStrList *bitmaps = NULL;
  541. bool alloc_depth = false;
  542. const char *tlscredsid = NULL;
  543. const char *tlshostname = NULL;
  544. bool imageOpts = false;
  545. bool writethrough = false; /* Client will flush as needed. */
  546. bool list = false;
  547. unsigned socket_activation;
  548. const char *pid_file_name = NULL;
  549. const char *selinux_label = NULL;
  550. BlockExportOptions *export_opts;
  551. struct NbdClientOpts opts = {
  552. .fork_process = false,
  553. .verbose = false,
  554. .device = NULL,
  555. .srcpath = NULL,
  556. .saddr = NULL,
  557. .old_stderr = STDOUT_FILENO,
  558. };
  559. #ifdef CONFIG_POSIX
  560. os_setup_early_signal_handling();
  561. os_setup_signal_handling();
  562. #endif
  563. socket_init();
  564. error_init(argv[0]);
  565. module_call_init(MODULE_INIT_TRACE);
  566. qcrypto_init(&error_fatal);
  567. module_call_init(MODULE_INIT_QOM);
  568. qemu_add_opts(&qemu_trace_opts);
  569. qemu_init_exec_dir(argv[0]);
  570. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  571. switch (ch) {
  572. case 's':
  573. flags |= BDRV_O_SNAPSHOT;
  574. break;
  575. case 'n':
  576. optarg = (char *) "none";
  577. /* fallthrough */
  578. case QEMU_NBD_OPT_CACHE:
  579. if (seen_cache) {
  580. error_report("-n and --cache can only be specified once");
  581. exit(EXIT_FAILURE);
  582. }
  583. seen_cache = true;
  584. if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
  585. error_report("Invalid cache mode `%s'", optarg);
  586. exit(EXIT_FAILURE);
  587. }
  588. break;
  589. case QEMU_NBD_OPT_AIO:
  590. if (seen_aio) {
  591. error_report("--aio can only be specified once");
  592. exit(EXIT_FAILURE);
  593. }
  594. seen_aio = true;
  595. if (bdrv_parse_aio(optarg, &flags) < 0) {
  596. error_report("Invalid aio mode '%s'", optarg);
  597. exit(EXIT_FAILURE);
  598. }
  599. break;
  600. case QEMU_NBD_OPT_DISCARD:
  601. if (seen_discard) {
  602. error_report("--discard can only be specified once");
  603. exit(EXIT_FAILURE);
  604. }
  605. seen_discard = true;
  606. if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
  607. error_report("Invalid discard mode `%s'", optarg);
  608. exit(EXIT_FAILURE);
  609. }
  610. break;
  611. case QEMU_NBD_OPT_DETECT_ZEROES:
  612. detect_zeroes =
  613. qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
  614. optarg,
  615. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
  616. &local_err);
  617. if (local_err) {
  618. error_reportf_err(local_err,
  619. "Failed to parse detect_zeroes mode: ");
  620. exit(EXIT_FAILURE);
  621. }
  622. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  623. !(flags & BDRV_O_UNMAP)) {
  624. error_report("setting detect-zeroes to unmap is not allowed "
  625. "without setting discard operation to unmap");
  626. exit(EXIT_FAILURE);
  627. }
  628. break;
  629. case 'b':
  630. bindto = optarg;
  631. break;
  632. case 'p':
  633. port = optarg;
  634. break;
  635. case 'o':
  636. if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
  637. error_report("Invalid offset '%s'", optarg);
  638. exit(EXIT_FAILURE);
  639. }
  640. break;
  641. case 'l':
  642. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  643. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  644. optarg, false);
  645. if (!sn_opts) {
  646. error_report("Failed in parsing snapshot param `%s'",
  647. optarg);
  648. exit(EXIT_FAILURE);
  649. }
  650. } else {
  651. sn_id_or_name = optarg;
  652. }
  653. /* fall through */
  654. case 'r':
  655. readonly = true;
  656. flags &= ~BDRV_O_RDWR;
  657. break;
  658. case 'A':
  659. alloc_depth = true;
  660. break;
  661. case 'B':
  662. {
  663. BlockDirtyBitmapOrStr *el = g_new(BlockDirtyBitmapOrStr, 1);
  664. *el = (BlockDirtyBitmapOrStr) {
  665. .type = QTYPE_QSTRING,
  666. .u.local = g_strdup(optarg),
  667. };
  668. QAPI_LIST_PREPEND(bitmaps, el);
  669. }
  670. break;
  671. case 'k':
  672. sockpath = optarg;
  673. if (sockpath[0] != '/') {
  674. error_report("socket path must be absolute");
  675. exit(EXIT_FAILURE);
  676. }
  677. break;
  678. case 'd':
  679. disconnect = true;
  680. break;
  681. case 'c':
  682. opts.device = optarg;
  683. break;
  684. case 'e':
  685. if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
  686. shared < 0) {
  687. error_report("Invalid shared device number '%s'", optarg);
  688. exit(EXIT_FAILURE);
  689. }
  690. break;
  691. case 'f':
  692. fmt = optarg;
  693. break;
  694. case 't':
  695. persistent = 1;
  696. break;
  697. case 'x':
  698. export_name = optarg;
  699. if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
  700. error_report("export name '%s' too long", export_name);
  701. exit(EXIT_FAILURE);
  702. }
  703. break;
  704. case 'D':
  705. export_description = optarg;
  706. if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
  707. error_report("export description '%s' too long",
  708. export_description);
  709. exit(EXIT_FAILURE);
  710. }
  711. break;
  712. case 'v':
  713. opts.verbose = true;
  714. break;
  715. case 'V':
  716. version(argv[0]);
  717. exit(0);
  718. break;
  719. case 'h':
  720. usage(argv[0]);
  721. exit(0);
  722. break;
  723. case '?':
  724. error_report("Try `%s --help' for more information.", argv[0]);
  725. exit(EXIT_FAILURE);
  726. case QEMU_NBD_OPT_OBJECT:
  727. user_creatable_process_cmdline(optarg);
  728. break;
  729. case QEMU_NBD_OPT_TLSCREDS:
  730. tlscredsid = optarg;
  731. break;
  732. case QEMU_NBD_OPT_TLSHOSTNAME:
  733. tlshostname = optarg;
  734. break;
  735. case QEMU_NBD_OPT_IMAGE_OPTS:
  736. imageOpts = true;
  737. break;
  738. case 'T':
  739. trace_opt_parse(optarg);
  740. break;
  741. case QEMU_NBD_OPT_TLSAUTHZ:
  742. tlsauthz = optarg;
  743. break;
  744. case QEMU_NBD_OPT_FORK:
  745. opts.fork_process = true;
  746. break;
  747. case 'L':
  748. list = true;
  749. break;
  750. case QEMU_NBD_OPT_PID_FILE:
  751. pid_file_name = optarg;
  752. break;
  753. case QEMU_NBD_OPT_SELINUX_LABEL:
  754. selinux_label = optarg;
  755. break;
  756. }
  757. }
  758. if (list) {
  759. if (argc != optind) {
  760. error_report("List mode is incompatible with a file name");
  761. exit(EXIT_FAILURE);
  762. }
  763. if (export_name || export_description || dev_offset ||
  764. opts.device || disconnect || fmt || sn_id_or_name || bitmaps ||
  765. alloc_depth || seen_aio || seen_discard || seen_cache) {
  766. error_report("List mode is incompatible with per-device settings");
  767. exit(EXIT_FAILURE);
  768. }
  769. if (opts.fork_process) {
  770. error_report("List mode is incompatible with forking");
  771. exit(EXIT_FAILURE);
  772. }
  773. } else if ((argc - optind) != 1) {
  774. error_report("Invalid number of arguments");
  775. error_printf("Try `%s --help' for more information.\n", argv[0]);
  776. exit(EXIT_FAILURE);
  777. } else if (!export_name) {
  778. export_name = "";
  779. }
  780. if (!trace_init_backends()) {
  781. exit(1);
  782. }
  783. trace_init_file();
  784. qemu_set_log(LOG_TRACE, &error_fatal);
  785. socket_activation = check_socket_activation();
  786. if (socket_activation == 0) {
  787. if (!sockpath) {
  788. setup_address_and_port(&bindto, &port);
  789. }
  790. } else {
  791. /* Using socket activation - check user didn't use -p etc. */
  792. const char *err_msg = socket_activation_validate_opts(opts.device,
  793. sockpath,
  794. bindto, port,
  795. selinux_label,
  796. list);
  797. if (err_msg != NULL) {
  798. error_report("%s", err_msg);
  799. exit(EXIT_FAILURE);
  800. }
  801. /* qemu-nbd can only listen on a single socket. */
  802. if (socket_activation > 1) {
  803. error_report("qemu-nbd does not support socket activation with %s > 1",
  804. "LISTEN_FDS");
  805. exit(EXIT_FAILURE);
  806. }
  807. }
  808. if (tlscredsid) {
  809. if (opts.device) {
  810. error_report("TLS is not supported with a host device");
  811. exit(EXIT_FAILURE);
  812. }
  813. if (tlsauthz && list) {
  814. error_report("TLS authorization is incompatible with export list");
  815. exit(EXIT_FAILURE);
  816. }
  817. if (tlshostname && !list) {
  818. error_report("TLS hostname is only supported with export list");
  819. exit(EXIT_FAILURE);
  820. }
  821. tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
  822. if (local_err) {
  823. error_reportf_err(local_err, "Failed to get TLS creds: ");
  824. exit(EXIT_FAILURE);
  825. }
  826. } else {
  827. if (tlsauthz) {
  828. error_report("--tls-authz is not permitted without --tls-creds");
  829. exit(EXIT_FAILURE);
  830. }
  831. if (tlshostname) {
  832. error_report("--tls-hostname is not permitted without --tls-creds");
  833. exit(EXIT_FAILURE);
  834. }
  835. }
  836. if (selinux_label) {
  837. #ifdef CONFIG_SELINUX
  838. if (sockpath == NULL && opts.device == NULL) {
  839. error_report("--selinux-label is not permitted without --socket");
  840. exit(EXIT_FAILURE);
  841. }
  842. #else
  843. error_report("SELinux support not enabled in this binary");
  844. exit(EXIT_FAILURE);
  845. #endif
  846. }
  847. if (list) {
  848. opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
  849. return qemu_nbd_client_list(opts.saddr, tlscreds,
  850. tlshostname ? tlshostname : bindto);
  851. }
  852. #if !HAVE_NBD_DEVICE
  853. if (disconnect || opts.device) {
  854. error_report("Kernel /dev/nbdN support not available");
  855. exit(EXIT_FAILURE);
  856. }
  857. #else /* HAVE_NBD_DEVICE */
  858. if (disconnect) {
  859. int nbdfd = open(argv[optind], O_RDWR);
  860. if (nbdfd < 0) {
  861. error_report("Cannot open %s: %s", argv[optind],
  862. strerror(errno));
  863. exit(EXIT_FAILURE);
  864. }
  865. nbd_disconnect(nbdfd);
  866. close(nbdfd);
  867. printf("%s disconnected\n", argv[optind]);
  868. return 0;
  869. }
  870. #endif
  871. if ((opts.device && !opts.verbose) || opts.fork_process) {
  872. #ifndef WIN32
  873. g_autoptr(GError) err = NULL;
  874. int stderr_fd[2];
  875. pid_t pid;
  876. if (!g_unix_open_pipe(stderr_fd, FD_CLOEXEC, &err)) {
  877. error_report("Error setting up communication pipe: %s",
  878. err->message);
  879. exit(EXIT_FAILURE);
  880. }
  881. /* Now daemonize, but keep a communication channel open to
  882. * print errors and exit with the proper status code.
  883. */
  884. pid = fork();
  885. if (pid < 0) {
  886. error_report("Failed to fork: %s", strerror(errno));
  887. exit(EXIT_FAILURE);
  888. } else if (pid == 0) {
  889. int saved_errno;
  890. close(stderr_fd[0]);
  891. /* Remember parent's stderr if we will be restoring it. */
  892. if (opts.verbose /* fork_process is set */) {
  893. opts.old_stderr = dup(STDERR_FILENO);
  894. if (opts.old_stderr < 0) {
  895. error_report("Could not dup original stderr: %s",
  896. strerror(errno));
  897. exit(EXIT_FAILURE);
  898. }
  899. }
  900. ret = qemu_daemon(1, 0);
  901. saved_errno = errno; /* dup2 will overwrite error below */
  902. /* Temporarily redirect stderr to the parent's pipe... */
  903. if (dup2(stderr_fd[1], STDERR_FILENO) < 0) {
  904. char str[256];
  905. snprintf(str, sizeof(str),
  906. "%s: Failed to link stderr to the pipe: %s\n",
  907. g_get_prgname(), strerror(errno));
  908. /*
  909. * We are unable to use error_report() here as we need to get
  910. * stderr pointed to the parent's pipe. Write to that pipe
  911. * manually.
  912. */
  913. ret = write(stderr_fd[1], str, strlen(str));
  914. exit(EXIT_FAILURE);
  915. }
  916. if (ret < 0) {
  917. error_report("Failed to daemonize: %s", strerror(saved_errno));
  918. exit(EXIT_FAILURE);
  919. }
  920. /* ... close the descriptor we inherited and go on. */
  921. close(stderr_fd[1]);
  922. } else {
  923. bool errors = false;
  924. char *buf;
  925. /* In the parent. Print error messages from the child until
  926. * it closes the pipe.
  927. */
  928. close(stderr_fd[1]);
  929. buf = g_malloc(1024);
  930. while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
  931. errors = true;
  932. ret = qemu_write_full(STDERR_FILENO, buf, ret);
  933. if (ret < 0) {
  934. exit(EXIT_FAILURE);
  935. }
  936. }
  937. if (ret < 0) {
  938. error_report("Cannot read from daemon: %s",
  939. strerror(errno));
  940. exit(EXIT_FAILURE);
  941. }
  942. /* Usually the daemon should not print any message.
  943. * Exit with zero status in that case.
  944. */
  945. exit(errors);
  946. }
  947. #else /* WIN32 */
  948. error_report("Unable to fork into background on Windows hosts");
  949. exit(EXIT_FAILURE);
  950. #endif /* WIN32 */
  951. }
  952. if (opts.device != NULL && sockpath == NULL) {
  953. sockpath = g_malloc(128);
  954. snprintf(sockpath, 128, SOCKET_PATH, basename(opts.device));
  955. }
  956. server = qio_net_listener_new();
  957. if (socket_activation == 0) {
  958. int backlog;
  959. if (persistent || shared == 0) {
  960. backlog = SOMAXCONN;
  961. } else {
  962. backlog = MIN(shared, SOMAXCONN);
  963. }
  964. #ifdef CONFIG_SELINUX
  965. if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
  966. error_report("Cannot set SELinux socket create context to %s: %s",
  967. selinux_label, strerror(errno));
  968. exit(EXIT_FAILURE);
  969. }
  970. #endif
  971. opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
  972. if (qio_net_listener_open_sync(server, opts.saddr, backlog,
  973. &local_err) < 0) {
  974. object_unref(OBJECT(server));
  975. error_report_err(local_err);
  976. exit(EXIT_FAILURE);
  977. }
  978. #ifdef CONFIG_SELINUX
  979. if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
  980. error_report("Cannot clear SELinux socket create context: %s",
  981. strerror(errno));
  982. exit(EXIT_FAILURE);
  983. }
  984. #endif
  985. } else {
  986. size_t i;
  987. /* See comment in check_socket_activation above. */
  988. for (i = 0; i < socket_activation; i++) {
  989. QIOChannelSocket *sioc;
  990. sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
  991. &local_err);
  992. if (sioc == NULL) {
  993. object_unref(OBJECT(server));
  994. error_reportf_err(local_err,
  995. "Failed to use socket activation: ");
  996. exit(EXIT_FAILURE);
  997. }
  998. qio_net_listener_add(server, sioc);
  999. object_unref(OBJECT(sioc));
  1000. }
  1001. }
  1002. qemu_init_main_loop(&error_fatal);
  1003. bdrv_init();
  1004. atexit(qemu_nbd_shutdown);
  1005. opts.srcpath = argv[optind];
  1006. if (imageOpts) {
  1007. QemuOpts *o;
  1008. if (fmt) {
  1009. error_report("--image-opts and -f are mutually exclusive");
  1010. exit(EXIT_FAILURE);
  1011. }
  1012. o = qemu_opts_parse_noisily(&file_opts, opts.srcpath, true);
  1013. if (!o) {
  1014. qemu_opts_reset(&file_opts);
  1015. exit(EXIT_FAILURE);
  1016. }
  1017. options = qemu_opts_to_qdict(o, NULL);
  1018. qemu_opts_reset(&file_opts);
  1019. blk = blk_new_open(NULL, NULL, options, flags, &local_err);
  1020. } else {
  1021. if (fmt) {
  1022. options = qdict_new();
  1023. qdict_put_str(options, "driver", fmt);
  1024. }
  1025. blk = blk_new_open(opts.srcpath, NULL, options, flags, &local_err);
  1026. }
  1027. if (!blk) {
  1028. error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
  1029. argv[optind]);
  1030. exit(EXIT_FAILURE);
  1031. }
  1032. bs = blk_bs(blk);
  1033. if (dev_offset) {
  1034. QDict *raw_opts = qdict_new();
  1035. qdict_put_str(raw_opts, "driver", "raw");
  1036. qdict_put_str(raw_opts, "file", bs->node_name);
  1037. qdict_put_int(raw_opts, "offset", dev_offset);
  1038. bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
  1039. blk_remove_bs(blk);
  1040. blk_insert_bs(blk, bs, &error_fatal);
  1041. bdrv_unref(bs);
  1042. }
  1043. blk_set_enable_write_cache(blk, !writethrough);
  1044. if (sn_opts) {
  1045. ret = bdrv_snapshot_load_tmp(bs,
  1046. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  1047. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  1048. &local_err);
  1049. } else if (sn_id_or_name) {
  1050. ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
  1051. &local_err);
  1052. }
  1053. if (ret < 0) {
  1054. error_reportf_err(local_err, "Failed to load snapshot: ");
  1055. exit(EXIT_FAILURE);
  1056. }
  1057. bs->detect_zeroes = detect_zeroes;
  1058. nbd_server_is_qemu_nbd(shared);
  1059. export_opts = g_new(BlockExportOptions, 1);
  1060. *export_opts = (BlockExportOptions) {
  1061. .type = BLOCK_EXPORT_TYPE_NBD,
  1062. .id = g_strdup("qemu-nbd-export"),
  1063. .node_name = g_strdup(bdrv_get_node_name(bs)),
  1064. .has_writethrough = true,
  1065. .writethrough = writethrough,
  1066. .has_writable = true,
  1067. .writable = !readonly,
  1068. .u.nbd = {
  1069. .name = g_strdup(export_name),
  1070. .description = g_strdup(export_description),
  1071. .has_bitmaps = !!bitmaps,
  1072. .bitmaps = bitmaps,
  1073. .has_allocation_depth = alloc_depth,
  1074. .allocation_depth = alloc_depth,
  1075. },
  1076. };
  1077. blk_exp_add(export_opts, &error_fatal);
  1078. qapi_free_BlockExportOptions(export_opts);
  1079. if (opts.device) {
  1080. #if HAVE_NBD_DEVICE
  1081. ret = pthread_create(&client_thread, NULL, nbd_client_thread, &opts);
  1082. if (ret != 0) {
  1083. error_report("Failed to create client thread: %s", strerror(ret));
  1084. exit(EXIT_FAILURE);
  1085. }
  1086. #endif
  1087. } else {
  1088. /* Shut up GCC warnings. */
  1089. memset(&client_thread, 0, sizeof(client_thread));
  1090. }
  1091. nbd_update_server_watch();
  1092. if (pid_file_name) {
  1093. qemu_write_pidfile(pid_file_name, &error_fatal);
  1094. }
  1095. /* now when the initialization is (almost) complete, chdir("/")
  1096. * to free any busy filesystems */
  1097. if (chdir("/") < 0) {
  1098. error_report("Could not chdir to root directory: %s",
  1099. strerror(errno));
  1100. exit(EXIT_FAILURE);
  1101. }
  1102. if (opts.fork_process) {
  1103. nbd_client_release_pipe(opts.old_stderr);
  1104. }
  1105. state = RUNNING;
  1106. do {
  1107. main_loop_wait(false);
  1108. if (state == TERMINATE) {
  1109. blk_exp_close_all();
  1110. state = TERMINATED;
  1111. }
  1112. } while (state != TERMINATED);
  1113. blk_unref(blk);
  1114. if (sockpath) {
  1115. unlink(sockpath);
  1116. }
  1117. qemu_opts_del(sn_opts);
  1118. if (opts.device) {
  1119. void *result;
  1120. pthread_join(client_thread, &result);
  1121. ret = (intptr_t)result;
  1122. exit(ret);
  1123. } else {
  1124. exit(EXIT_SUCCESS);
  1125. }
  1126. }