2
0

qemu-nbd.c 36 KB

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