qemu-nbd.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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 "system/block-backend.h"
  26. #include "system/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. /* TODO - expose handshake timeout as command line option */
  360. nbd_client_new(cioc, NBD_DEFAULT_HANDSHAKE_MAX_SECS,
  361. tlscreds, tlsauthz, nbd_client_closed, NULL);
  362. }
  363. static void nbd_update_server_watch(void)
  364. {
  365. if (nbd_can_accept()) {
  366. qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
  367. } else {
  368. qio_net_listener_set_client_func(server, NULL, NULL, NULL);
  369. }
  370. }
  371. static SocketAddress *nbd_build_socket_address(const char *sockpath,
  372. const char *bindto,
  373. const char *port)
  374. {
  375. SocketAddress *saddr;
  376. saddr = g_new0(SocketAddress, 1);
  377. if (sockpath) {
  378. saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
  379. saddr->u.q_unix.path = g_strdup(sockpath);
  380. } else {
  381. InetSocketAddress *inet;
  382. saddr->type = SOCKET_ADDRESS_TYPE_INET;
  383. inet = &saddr->u.inet;
  384. inet->host = g_strdup(bindto);
  385. if (port) {
  386. inet->port = g_strdup(port);
  387. } else {
  388. inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
  389. }
  390. }
  391. return saddr;
  392. }
  393. static QemuOptsList file_opts = {
  394. .name = "file",
  395. .implied_opt_name = "file",
  396. .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
  397. .desc = {
  398. /* no elements => accept any params */
  399. { /* end of list */ }
  400. },
  401. };
  402. static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
  403. Error **errp)
  404. {
  405. Object *obj;
  406. QCryptoTLSCreds *creds;
  407. obj = object_resolve_path_component(
  408. object_get_objects_root(), id);
  409. if (!obj) {
  410. error_setg(errp, "No TLS credentials with id '%s'",
  411. id);
  412. return NULL;
  413. }
  414. creds = (QCryptoTLSCreds *)
  415. object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
  416. if (!creds) {
  417. error_setg(errp, "Object with id '%s' is not TLS credentials",
  418. id);
  419. return NULL;
  420. }
  421. if (!qcrypto_tls_creds_check_endpoint(creds,
  422. list
  423. ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
  424. : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
  425. errp)) {
  426. return NULL;
  427. }
  428. object_ref(obj);
  429. return creds;
  430. }
  431. static void setup_address_and_port(const char **address, const char **port)
  432. {
  433. if (*address == NULL) {
  434. *address = "0.0.0.0";
  435. }
  436. if (*port == NULL) {
  437. *port = stringify(NBD_DEFAULT_PORT);
  438. }
  439. }
  440. /*
  441. * Check socket parameters compatibility when socket activation is used.
  442. */
  443. static const char *socket_activation_validate_opts(const char *device,
  444. const char *sockpath,
  445. const char *address,
  446. const char *port,
  447. const char *selinux,
  448. bool list)
  449. {
  450. if (device != NULL) {
  451. return "NBD device can't be set when using socket activation";
  452. }
  453. if (sockpath != NULL) {
  454. return "Unix socket can't be set when using socket activation";
  455. }
  456. if (address != NULL) {
  457. return "The interface can't be set when using socket activation";
  458. }
  459. if (port != NULL) {
  460. return "TCP port number can't be set when using socket activation";
  461. }
  462. if (selinux != NULL) {
  463. return "SELinux label can't be set when using socket activation";
  464. }
  465. if (list) {
  466. return "List mode is incompatible with socket activation";
  467. }
  468. return NULL;
  469. }
  470. static void qemu_nbd_shutdown(void)
  471. {
  472. job_cancel_sync_all();
  473. blk_exp_close_all();
  474. bdrv_close_all();
  475. }
  476. int main(int argc, char **argv)
  477. {
  478. BlockBackend *blk;
  479. BlockDriverState *bs;
  480. uint64_t dev_offset = 0;
  481. bool readonly = false;
  482. bool disconnect = false;
  483. const char *bindto = NULL;
  484. const char *port = NULL;
  485. char *sockpath = NULL;
  486. QemuOpts *sn_opts = NULL;
  487. const char *sn_id_or_name = NULL;
  488. const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
  489. struct option lopt[] = {
  490. { "help", no_argument, NULL, 'h' },
  491. { "version", no_argument, NULL, 'V' },
  492. { "bind", required_argument, NULL, 'b' },
  493. { "port", required_argument, NULL, 'p' },
  494. { "socket", required_argument, NULL, 'k' },
  495. { "offset", required_argument, NULL, 'o' },
  496. { "read-only", no_argument, NULL, 'r' },
  497. { "allocation-depth", no_argument, NULL, 'A' },
  498. { "bitmap", required_argument, NULL, 'B' },
  499. { "connect", required_argument, NULL, 'c' },
  500. { "disconnect", no_argument, NULL, 'd' },
  501. { "list", no_argument, NULL, 'L' },
  502. { "snapshot", no_argument, NULL, 's' },
  503. { "load-snapshot", required_argument, NULL, 'l' },
  504. { "nocache", no_argument, NULL, 'n' },
  505. { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
  506. { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
  507. { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
  508. { "detect-zeroes", required_argument, NULL,
  509. QEMU_NBD_OPT_DETECT_ZEROES },
  510. { "shared", required_argument, NULL, 'e' },
  511. { "format", required_argument, NULL, 'f' },
  512. { "persistent", no_argument, NULL, 't' },
  513. { "verbose", no_argument, NULL, 'v' },
  514. { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
  515. { "export-name", required_argument, NULL, 'x' },
  516. { "description", required_argument, NULL, 'D' },
  517. { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
  518. { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
  519. { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
  520. { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
  521. { "trace", required_argument, NULL, 'T' },
  522. { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
  523. { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
  524. { "selinux-label", required_argument, NULL,
  525. QEMU_NBD_OPT_SELINUX_LABEL },
  526. { NULL, 0, NULL, 0 }
  527. };
  528. int ch;
  529. int opt_ind = 0;
  530. int flags = BDRV_O_RDWR;
  531. int ret = 0;
  532. bool seen_cache = false;
  533. bool seen_discard = false;
  534. bool seen_aio = false;
  535. pthread_t client_thread;
  536. const char *fmt = NULL;
  537. Error *local_err = NULL;
  538. BlockdevDetectZeroesOptions detect_zeroes =
  539. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
  540. QDict *options = NULL;
  541. const char *export_name = NULL; /* defaults to "" later for server mode */
  542. const char *export_description = NULL;
  543. BlockDirtyBitmapOrStrList *bitmaps = NULL;
  544. bool alloc_depth = false;
  545. const char *tlscredsid = NULL;
  546. const char *tlshostname = NULL;
  547. bool imageOpts = false;
  548. bool writethrough = false; /* Client will flush as needed. */
  549. bool list = false;
  550. unsigned socket_activation;
  551. const char *pid_file_name = NULL;
  552. const char *selinux_label = NULL;
  553. BlockExportOptions *export_opts;
  554. struct NbdClientOpts opts = {
  555. .fork_process = false,
  556. .verbose = false,
  557. .device = NULL,
  558. .srcpath = NULL,
  559. .saddr = NULL,
  560. .old_stderr = STDOUT_FILENO,
  561. };
  562. #ifdef CONFIG_POSIX
  563. os_setup_early_signal_handling();
  564. os_setup_signal_handling();
  565. #endif
  566. socket_init();
  567. error_init(argv[0]);
  568. module_call_init(MODULE_INIT_TRACE);
  569. qcrypto_init(&error_fatal);
  570. module_call_init(MODULE_INIT_QOM);
  571. qemu_add_opts(&qemu_trace_opts);
  572. qemu_init_exec_dir(argv[0]);
  573. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  574. switch (ch) {
  575. case 's':
  576. flags |= BDRV_O_SNAPSHOT;
  577. break;
  578. case 'n':
  579. optarg = (char *) "none";
  580. /* fallthrough */
  581. case QEMU_NBD_OPT_CACHE:
  582. if (seen_cache) {
  583. error_report("-n and --cache can only be specified once");
  584. exit(EXIT_FAILURE);
  585. }
  586. seen_cache = true;
  587. if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
  588. error_report("Invalid cache mode `%s'", optarg);
  589. exit(EXIT_FAILURE);
  590. }
  591. break;
  592. case QEMU_NBD_OPT_AIO:
  593. if (seen_aio) {
  594. error_report("--aio can only be specified once");
  595. exit(EXIT_FAILURE);
  596. }
  597. seen_aio = true;
  598. if (bdrv_parse_aio(optarg, &flags) < 0) {
  599. error_report("Invalid aio mode '%s'", optarg);
  600. exit(EXIT_FAILURE);
  601. }
  602. break;
  603. case QEMU_NBD_OPT_DISCARD:
  604. if (seen_discard) {
  605. error_report("--discard can only be specified once");
  606. exit(EXIT_FAILURE);
  607. }
  608. seen_discard = true;
  609. if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
  610. error_report("Invalid discard mode `%s'", optarg);
  611. exit(EXIT_FAILURE);
  612. }
  613. break;
  614. case QEMU_NBD_OPT_DETECT_ZEROES:
  615. detect_zeroes =
  616. qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
  617. optarg,
  618. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
  619. &local_err);
  620. if (local_err) {
  621. error_reportf_err(local_err,
  622. "Failed to parse detect_zeroes mode: ");
  623. exit(EXIT_FAILURE);
  624. }
  625. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  626. !(flags & BDRV_O_UNMAP)) {
  627. error_report("setting detect-zeroes to unmap is not allowed "
  628. "without setting discard operation to unmap");
  629. exit(EXIT_FAILURE);
  630. }
  631. break;
  632. case 'b':
  633. bindto = optarg;
  634. break;
  635. case 'p':
  636. port = optarg;
  637. break;
  638. case 'o':
  639. if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
  640. error_report("Invalid offset '%s'", optarg);
  641. exit(EXIT_FAILURE);
  642. }
  643. break;
  644. case 'l':
  645. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  646. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  647. optarg, false);
  648. if (!sn_opts) {
  649. error_report("Failed in parsing snapshot param `%s'",
  650. optarg);
  651. exit(EXIT_FAILURE);
  652. }
  653. } else {
  654. sn_id_or_name = optarg;
  655. }
  656. /* fall through */
  657. case 'r':
  658. readonly = true;
  659. flags &= ~BDRV_O_RDWR;
  660. break;
  661. case 'A':
  662. alloc_depth = true;
  663. break;
  664. case 'B':
  665. {
  666. BlockDirtyBitmapOrStr *el = g_new(BlockDirtyBitmapOrStr, 1);
  667. *el = (BlockDirtyBitmapOrStr) {
  668. .type = QTYPE_QSTRING,
  669. .u.local = g_strdup(optarg),
  670. };
  671. QAPI_LIST_PREPEND(bitmaps, el);
  672. }
  673. break;
  674. case 'k':
  675. sockpath = optarg;
  676. if (sockpath[0] != '/') {
  677. error_report("socket path must be absolute");
  678. exit(EXIT_FAILURE);
  679. }
  680. break;
  681. case 'd':
  682. disconnect = true;
  683. break;
  684. case 'c':
  685. opts.device = optarg;
  686. break;
  687. case 'e':
  688. if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
  689. shared < 0) {
  690. error_report("Invalid shared device number '%s'", optarg);
  691. exit(EXIT_FAILURE);
  692. }
  693. break;
  694. case 'f':
  695. fmt = optarg;
  696. break;
  697. case 't':
  698. persistent = 1;
  699. break;
  700. case 'x':
  701. export_name = optarg;
  702. if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
  703. error_report("export name '%s' too long", export_name);
  704. exit(EXIT_FAILURE);
  705. }
  706. break;
  707. case 'D':
  708. export_description = optarg;
  709. if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
  710. error_report("export description '%s' too long",
  711. export_description);
  712. exit(EXIT_FAILURE);
  713. }
  714. break;
  715. case 'v':
  716. opts.verbose = true;
  717. break;
  718. case 'V':
  719. version(argv[0]);
  720. exit(0);
  721. break;
  722. case 'h':
  723. usage(argv[0]);
  724. exit(0);
  725. break;
  726. case '?':
  727. error_report("Try `%s --help' for more information.", argv[0]);
  728. exit(EXIT_FAILURE);
  729. case QEMU_NBD_OPT_OBJECT:
  730. user_creatable_process_cmdline(optarg);
  731. break;
  732. case QEMU_NBD_OPT_TLSCREDS:
  733. tlscredsid = optarg;
  734. break;
  735. case QEMU_NBD_OPT_TLSHOSTNAME:
  736. tlshostname = optarg;
  737. break;
  738. case QEMU_NBD_OPT_IMAGE_OPTS:
  739. imageOpts = true;
  740. break;
  741. case 'T':
  742. trace_opt_parse(optarg);
  743. break;
  744. case QEMU_NBD_OPT_TLSAUTHZ:
  745. tlsauthz = optarg;
  746. break;
  747. case QEMU_NBD_OPT_FORK:
  748. opts.fork_process = true;
  749. break;
  750. case 'L':
  751. list = true;
  752. break;
  753. case QEMU_NBD_OPT_PID_FILE:
  754. pid_file_name = optarg;
  755. break;
  756. case QEMU_NBD_OPT_SELINUX_LABEL:
  757. selinux_label = optarg;
  758. break;
  759. }
  760. }
  761. if (list) {
  762. if (argc != optind) {
  763. error_report("List mode is incompatible with a file name");
  764. exit(EXIT_FAILURE);
  765. }
  766. if (export_name || export_description || dev_offset ||
  767. opts.device || disconnect || fmt || sn_id_or_name || bitmaps ||
  768. alloc_depth || seen_aio || seen_discard || seen_cache) {
  769. error_report("List mode is incompatible with per-device settings");
  770. exit(EXIT_FAILURE);
  771. }
  772. if (opts.fork_process) {
  773. error_report("List mode is incompatible with forking");
  774. exit(EXIT_FAILURE);
  775. }
  776. } else if ((argc - optind) != 1) {
  777. error_report("Invalid number of arguments");
  778. error_printf("Try `%s --help' for more information.\n", argv[0]);
  779. exit(EXIT_FAILURE);
  780. } else if (!export_name) {
  781. export_name = "";
  782. }
  783. if (!trace_init_backends()) {
  784. exit(1);
  785. }
  786. trace_init_file();
  787. qemu_set_log(LOG_TRACE, &error_fatal);
  788. socket_activation = check_socket_activation();
  789. if (socket_activation == 0) {
  790. if (!sockpath) {
  791. setup_address_and_port(&bindto, &port);
  792. }
  793. } else {
  794. /* Using socket activation - check user didn't use -p etc. */
  795. const char *err_msg = socket_activation_validate_opts(opts.device,
  796. sockpath,
  797. bindto, port,
  798. selinux_label,
  799. list);
  800. if (err_msg != NULL) {
  801. error_report("%s", err_msg);
  802. exit(EXIT_FAILURE);
  803. }
  804. /* qemu-nbd can only listen on a single socket. */
  805. if (socket_activation > 1) {
  806. error_report("qemu-nbd does not support socket activation with %s > 1",
  807. "LISTEN_FDS");
  808. exit(EXIT_FAILURE);
  809. }
  810. }
  811. if (tlscredsid) {
  812. if (opts.device) {
  813. error_report("TLS is not supported with a host device");
  814. exit(EXIT_FAILURE);
  815. }
  816. if (tlsauthz && list) {
  817. error_report("TLS authorization is incompatible with export list");
  818. exit(EXIT_FAILURE);
  819. }
  820. if (tlshostname && !list) {
  821. error_report("TLS hostname is only supported with export list");
  822. exit(EXIT_FAILURE);
  823. }
  824. tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
  825. if (local_err) {
  826. error_reportf_err(local_err, "Failed to get TLS creds: ");
  827. exit(EXIT_FAILURE);
  828. }
  829. } else {
  830. if (tlsauthz) {
  831. error_report("--tls-authz is not permitted without --tls-creds");
  832. exit(EXIT_FAILURE);
  833. }
  834. if (tlshostname) {
  835. error_report("--tls-hostname is not permitted without --tls-creds");
  836. exit(EXIT_FAILURE);
  837. }
  838. }
  839. if (selinux_label) {
  840. #ifdef CONFIG_SELINUX
  841. if (sockpath == NULL && opts.device == NULL) {
  842. error_report("--selinux-label is not permitted without --socket");
  843. exit(EXIT_FAILURE);
  844. }
  845. #else
  846. error_report("SELinux support not enabled in this binary");
  847. exit(EXIT_FAILURE);
  848. #endif
  849. }
  850. if (list) {
  851. opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
  852. return qemu_nbd_client_list(opts.saddr, tlscreds,
  853. tlshostname ? tlshostname : bindto);
  854. }
  855. #if !HAVE_NBD_DEVICE
  856. if (disconnect || opts.device) {
  857. error_report("Kernel /dev/nbdN support not available");
  858. exit(EXIT_FAILURE);
  859. }
  860. #else /* HAVE_NBD_DEVICE */
  861. if (disconnect) {
  862. int nbdfd = open(argv[optind], O_RDWR);
  863. if (nbdfd < 0) {
  864. error_report("Cannot open %s: %s", argv[optind],
  865. strerror(errno));
  866. exit(EXIT_FAILURE);
  867. }
  868. nbd_disconnect(nbdfd);
  869. close(nbdfd);
  870. printf("%s disconnected\n", argv[optind]);
  871. return 0;
  872. }
  873. #endif
  874. if ((opts.device && !opts.verbose) || opts.fork_process) {
  875. #ifndef WIN32
  876. g_autoptr(GError) err = NULL;
  877. int stderr_fd[2];
  878. pid_t pid;
  879. if (!g_unix_open_pipe(stderr_fd, FD_CLOEXEC, &err)) {
  880. error_report("Error setting up communication pipe: %s",
  881. err->message);
  882. exit(EXIT_FAILURE);
  883. }
  884. /* Now daemonize, but keep a communication channel open to
  885. * print errors and exit with the proper status code.
  886. */
  887. pid = fork();
  888. if (pid < 0) {
  889. error_report("Failed to fork: %s", strerror(errno));
  890. exit(EXIT_FAILURE);
  891. } else if (pid == 0) {
  892. int saved_errno;
  893. close(stderr_fd[0]);
  894. /* Remember parent's stderr if we will be restoring it. */
  895. if (opts.verbose /* fork_process is set */) {
  896. opts.old_stderr = dup(STDERR_FILENO);
  897. if (opts.old_stderr < 0) {
  898. error_report("Could not dup original stderr: %s",
  899. strerror(errno));
  900. exit(EXIT_FAILURE);
  901. }
  902. }
  903. ret = qemu_daemon(1, 0);
  904. saved_errno = errno; /* dup2 will overwrite error below */
  905. /* Temporarily redirect stderr to the parent's pipe... */
  906. if (dup2(stderr_fd[1], STDERR_FILENO) < 0) {
  907. char str[256];
  908. snprintf(str, sizeof(str),
  909. "%s: Failed to link stderr to the pipe: %s\n",
  910. g_get_prgname(), strerror(errno));
  911. /*
  912. * We are unable to use error_report() here as we need to get
  913. * stderr pointed to the parent's pipe. Write to that pipe
  914. * manually.
  915. */
  916. ret = write(stderr_fd[1], str, strlen(str));
  917. exit(EXIT_FAILURE);
  918. }
  919. if (ret < 0) {
  920. error_report("Failed to daemonize: %s", strerror(saved_errno));
  921. exit(EXIT_FAILURE);
  922. }
  923. /* ... close the descriptor we inherited and go on. */
  924. close(stderr_fd[1]);
  925. } else {
  926. bool errors = false;
  927. char *buf;
  928. /* In the parent. Print error messages from the child until
  929. * it closes the pipe.
  930. */
  931. close(stderr_fd[1]);
  932. buf = g_malloc(1024);
  933. while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
  934. errors = true;
  935. ret = qemu_write_full(STDERR_FILENO, buf, ret);
  936. if (ret < 0) {
  937. exit(EXIT_FAILURE);
  938. }
  939. }
  940. if (ret < 0) {
  941. error_report("Cannot read from daemon: %s",
  942. strerror(errno));
  943. exit(EXIT_FAILURE);
  944. }
  945. /* Usually the daemon should not print any message.
  946. * Exit with zero status in that case.
  947. */
  948. exit(errors);
  949. }
  950. #else /* WIN32 */
  951. error_report("Unable to fork into background on Windows hosts");
  952. exit(EXIT_FAILURE);
  953. #endif /* WIN32 */
  954. }
  955. if (opts.device != NULL && sockpath == NULL) {
  956. sockpath = g_malloc(128);
  957. snprintf(sockpath, 128, SOCKET_PATH, basename(opts.device));
  958. }
  959. server = qio_net_listener_new();
  960. if (socket_activation == 0) {
  961. int backlog;
  962. if (persistent || shared == 0) {
  963. backlog = SOMAXCONN;
  964. } else {
  965. backlog = MIN(shared, SOMAXCONN);
  966. }
  967. #ifdef CONFIG_SELINUX
  968. if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
  969. error_report("Cannot set SELinux socket create context to %s: %s",
  970. selinux_label, strerror(errno));
  971. exit(EXIT_FAILURE);
  972. }
  973. #endif
  974. opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
  975. if (qio_net_listener_open_sync(server, opts.saddr, backlog,
  976. &local_err) < 0) {
  977. object_unref(OBJECT(server));
  978. error_report_err(local_err);
  979. exit(EXIT_FAILURE);
  980. }
  981. #ifdef CONFIG_SELINUX
  982. if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
  983. error_report("Cannot clear SELinux socket create context: %s",
  984. strerror(errno));
  985. exit(EXIT_FAILURE);
  986. }
  987. #endif
  988. } else {
  989. size_t i;
  990. /* See comment in check_socket_activation above. */
  991. for (i = 0; i < socket_activation; i++) {
  992. QIOChannelSocket *sioc;
  993. sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
  994. &local_err);
  995. if (sioc == NULL) {
  996. object_unref(OBJECT(server));
  997. error_reportf_err(local_err,
  998. "Failed to use socket activation: ");
  999. exit(EXIT_FAILURE);
  1000. }
  1001. qio_net_listener_add(server, sioc);
  1002. object_unref(OBJECT(sioc));
  1003. }
  1004. }
  1005. qemu_init_main_loop(&error_fatal);
  1006. bdrv_init();
  1007. atexit(qemu_nbd_shutdown);
  1008. opts.srcpath = argv[optind];
  1009. if (imageOpts) {
  1010. QemuOpts *o;
  1011. if (fmt) {
  1012. error_report("--image-opts and -f are mutually exclusive");
  1013. exit(EXIT_FAILURE);
  1014. }
  1015. o = qemu_opts_parse_noisily(&file_opts, opts.srcpath, true);
  1016. if (!o) {
  1017. qemu_opts_reset(&file_opts);
  1018. exit(EXIT_FAILURE);
  1019. }
  1020. options = qemu_opts_to_qdict(o, NULL);
  1021. qemu_opts_reset(&file_opts);
  1022. blk = blk_new_open(NULL, NULL, options, flags, &local_err);
  1023. } else {
  1024. if (fmt) {
  1025. options = qdict_new();
  1026. qdict_put_str(options, "driver", fmt);
  1027. }
  1028. blk = blk_new_open(opts.srcpath, NULL, options, flags, &local_err);
  1029. }
  1030. if (!blk) {
  1031. error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
  1032. argv[optind]);
  1033. exit(EXIT_FAILURE);
  1034. }
  1035. bs = blk_bs(blk);
  1036. if (dev_offset) {
  1037. QDict *raw_opts = qdict_new();
  1038. qdict_put_str(raw_opts, "driver", "raw");
  1039. qdict_put_str(raw_opts, "file", bs->node_name);
  1040. qdict_put_int(raw_opts, "offset", dev_offset);
  1041. bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
  1042. blk_remove_bs(blk);
  1043. blk_insert_bs(blk, bs, &error_fatal);
  1044. bdrv_unref(bs);
  1045. }
  1046. blk_set_enable_write_cache(blk, !writethrough);
  1047. if (sn_opts) {
  1048. ret = bdrv_snapshot_load_tmp(bs,
  1049. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  1050. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  1051. &local_err);
  1052. } else if (sn_id_or_name) {
  1053. ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
  1054. &local_err);
  1055. }
  1056. if (ret < 0) {
  1057. error_reportf_err(local_err, "Failed to load snapshot: ");
  1058. exit(EXIT_FAILURE);
  1059. }
  1060. bs->detect_zeroes = detect_zeroes;
  1061. nbd_server_is_qemu_nbd(shared);
  1062. export_opts = g_new(BlockExportOptions, 1);
  1063. *export_opts = (BlockExportOptions) {
  1064. .type = BLOCK_EXPORT_TYPE_NBD,
  1065. .id = g_strdup("qemu-nbd-export"),
  1066. .node_name = g_strdup(bdrv_get_node_name(bs)),
  1067. .has_writethrough = true,
  1068. .writethrough = writethrough,
  1069. .has_writable = true,
  1070. .writable = !readonly,
  1071. .u.nbd = {
  1072. .name = g_strdup(export_name),
  1073. .description = g_strdup(export_description),
  1074. .has_bitmaps = !!bitmaps,
  1075. .bitmaps = bitmaps,
  1076. .has_allocation_depth = alloc_depth,
  1077. .allocation_depth = alloc_depth,
  1078. },
  1079. };
  1080. blk_exp_add(export_opts, &error_fatal);
  1081. qapi_free_BlockExportOptions(export_opts);
  1082. if (opts.device) {
  1083. #if HAVE_NBD_DEVICE
  1084. ret = pthread_create(&client_thread, NULL, nbd_client_thread, &opts);
  1085. if (ret != 0) {
  1086. error_report("Failed to create client thread: %s", strerror(ret));
  1087. exit(EXIT_FAILURE);
  1088. }
  1089. #endif
  1090. } else {
  1091. /* Shut up GCC warnings. */
  1092. memset(&client_thread, 0, sizeof(client_thread));
  1093. }
  1094. nbd_update_server_watch();
  1095. if (pid_file_name) {
  1096. qemu_write_pidfile(pid_file_name, &error_fatal);
  1097. }
  1098. /* now when the initialization is (almost) complete, chdir("/")
  1099. * to free any busy filesystems */
  1100. if (chdir("/") < 0) {
  1101. error_report("Could not chdir to root directory: %s",
  1102. strerror(errno));
  1103. exit(EXIT_FAILURE);
  1104. }
  1105. if (opts.fork_process) {
  1106. nbd_client_release_pipe(opts.old_stderr);
  1107. }
  1108. state = RUNNING;
  1109. do {
  1110. main_loop_wait(false);
  1111. if (state == TERMINATE) {
  1112. blk_exp_close_all();
  1113. state = TERMINATED;
  1114. }
  1115. } while (state != TERMINATED);
  1116. blk_unref(blk);
  1117. if (sockpath) {
  1118. unlink(sockpath);
  1119. }
  1120. qemu_opts_del(sn_opts);
  1121. if (opts.device) {
  1122. void *result;
  1123. pthread_join(client_thread, &result);
  1124. ret = (intptr_t)result;
  1125. exit(ret);
  1126. } else {
  1127. exit(EXIT_SUCCESS);
  1128. }
  1129. }