qemu-nbd.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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 NBDExport *export;
  63. static int verbose;
  64. static char *srcpath;
  65. static SocketAddress *saddr;
  66. static int persistent = 0;
  67. static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
  68. static int shared = 1;
  69. static int nb_fds;
  70. static QIONetListener *server;
  71. static QCryptoTLSCreds *tlscreds;
  72. static const char *tlsauthz;
  73. static void usage(const char *name)
  74. {
  75. (printf) (
  76. "Usage: %s [OPTIONS] FILE\n"
  77. " or: %s -L [OPTIONS]\n"
  78. "QEMU Disk Network Block Device Utility\n"
  79. "\n"
  80. " -h, --help display this help and exit\n"
  81. " -V, --version output version information and exit\n"
  82. "\n"
  83. "Connection properties:\n"
  84. " -p, --port=PORT port to listen on (default `%d')\n"
  85. " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
  86. " -k, --socket=PATH path to the unix socket\n"
  87. " (default '"SOCKET_PATH"')\n"
  88. " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
  89. " -t, --persistent don't exit on the last connection\n"
  90. " -v, --verbose display extra debugging information\n"
  91. " -x, --export-name=NAME expose export by name (default is empty string)\n"
  92. " -D, --description=TEXT export a human-readable description\n"
  93. "\n"
  94. "Exposing part of the image:\n"
  95. " -o, --offset=OFFSET offset into the image\n"
  96. " -B, --bitmap=NAME expose a persistent dirty bitmap\n"
  97. "\n"
  98. "General purpose options:\n"
  99. " -L, --list list exports available from another NBD server\n"
  100. " --object type,id=ID,... define an object such as 'secret' for providing\n"
  101. " passwords and/or encryption keys\n"
  102. " --tls-creds=ID use id of an earlier --object to provide TLS\n"
  103. " --tls-authz=ID use id of an earlier --object to provide\n"
  104. " authorization\n"
  105. " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
  106. " specify tracing options\n"
  107. " --fork fork off the server process and exit the parent\n"
  108. " once the server is running\n"
  109. " --pid-file=PATH store the server's process ID in the given file\n"
  110. #if HAVE_NBD_DEVICE
  111. "\n"
  112. "Kernel NBD client support:\n"
  113. " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
  114. " -d, --disconnect disconnect the specified device\n"
  115. #endif
  116. "\n"
  117. "Block device options:\n"
  118. " -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
  119. " -r, --read-only export read-only\n"
  120. " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
  121. " file with backing_file=FILE, redirect the write to\n"
  122. " the temporary one\n"
  123. " -l, --load-snapshot=SNAPSHOT_PARAM\n"
  124. " load an internal snapshot inside FILE and export it\n"
  125. " as an read-only device, SNAPSHOT_PARAM format is\n"
  126. " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
  127. " '[ID_OR_NAME]'\n"
  128. " -n, --nocache disable host cache\n"
  129. " --cache=MODE set cache mode (none, writeback, ...)\n"
  130. " --aio=MODE set AIO mode (native, io_uring or threads)\n"
  131. " --discard=MODE set discard mode (ignore, unmap)\n"
  132. " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
  133. " --image-opts treat FILE as a full set of image options\n"
  134. "\n"
  135. QEMU_HELP_BOTTOM "\n"
  136. , name, name, NBD_DEFAULT_PORT, "DEVICE");
  137. }
  138. static void version(const char *name)
  139. {
  140. printf(
  141. "%s " QEMU_FULL_VERSION "\n"
  142. "Written by Anthony Liguori.\n"
  143. "\n"
  144. QEMU_COPYRIGHT "\n"
  145. "This is free software; see the source for copying conditions. There is NO\n"
  146. "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
  147. , name);
  148. }
  149. static void termsig_handler(int signum)
  150. {
  151. atomic_cmpxchg(&state, RUNNING, TERMINATE);
  152. qemu_notify_event();
  153. }
  154. static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
  155. const char *hostname)
  156. {
  157. int ret = EXIT_FAILURE;
  158. int rc;
  159. Error *err = NULL;
  160. QIOChannelSocket *sioc;
  161. NBDExportInfo *list;
  162. int i, j;
  163. sioc = qio_channel_socket_new();
  164. if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
  165. error_report_err(err);
  166. return EXIT_FAILURE;
  167. }
  168. rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
  169. &err);
  170. if (rc < 0) {
  171. if (err) {
  172. error_report_err(err);
  173. }
  174. goto out;
  175. }
  176. printf("exports available: %d\n", rc);
  177. for (i = 0; i < rc; i++) {
  178. printf(" export: '%s'\n", list[i].name);
  179. if (list[i].description && *list[i].description) {
  180. printf(" description: %s\n", list[i].description);
  181. }
  182. if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
  183. static const char *const flag_names[] = {
  184. [NBD_FLAG_READ_ONLY_BIT] = "readonly",
  185. [NBD_FLAG_SEND_FLUSH_BIT] = "flush",
  186. [NBD_FLAG_SEND_FUA_BIT] = "fua",
  187. [NBD_FLAG_ROTATIONAL_BIT] = "rotational",
  188. [NBD_FLAG_SEND_TRIM_BIT] = "trim",
  189. [NBD_FLAG_SEND_WRITE_ZEROES_BIT] = "zeroes",
  190. [NBD_FLAG_SEND_DF_BIT] = "df",
  191. [NBD_FLAG_CAN_MULTI_CONN_BIT] = "multi",
  192. [NBD_FLAG_SEND_RESIZE_BIT] = "resize",
  193. [NBD_FLAG_SEND_CACHE_BIT] = "cache",
  194. [NBD_FLAG_SEND_FAST_ZERO_BIT] = "fast-zero",
  195. };
  196. printf(" size: %" PRIu64 "\n", list[i].size);
  197. printf(" flags: 0x%x (", list[i].flags);
  198. for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
  199. if (flag_names[bit] && (list[i].flags & (1 << bit))) {
  200. printf(" %s", flag_names[bit]);
  201. }
  202. }
  203. printf(" )\n");
  204. }
  205. if (list[i].min_block) {
  206. printf(" min block: %u\n", list[i].min_block);
  207. printf(" opt block: %u\n", list[i].opt_block);
  208. printf(" max block: %u\n", list[i].max_block);
  209. }
  210. if (list[i].n_contexts) {
  211. printf(" available meta contexts: %d\n", list[i].n_contexts);
  212. for (j = 0; j < list[i].n_contexts; j++) {
  213. printf(" %s\n", list[i].contexts[j]);
  214. }
  215. }
  216. }
  217. nbd_free_export_list(list, rc);
  218. ret = EXIT_SUCCESS;
  219. out:
  220. object_unref(OBJECT(sioc));
  221. return ret;
  222. }
  223. #if HAVE_NBD_DEVICE
  224. static void *show_parts(void *arg)
  225. {
  226. char *device = arg;
  227. int nbd;
  228. /* linux just needs an open() to trigger
  229. * the partition table update
  230. * but remember to load the module with max_part != 0 :
  231. * modprobe nbd max_part=63
  232. */
  233. nbd = open(device, O_RDWR);
  234. if (nbd >= 0) {
  235. close(nbd);
  236. }
  237. return NULL;
  238. }
  239. static void *nbd_client_thread(void *arg)
  240. {
  241. char *device = arg;
  242. NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
  243. QIOChannelSocket *sioc;
  244. int fd;
  245. int ret;
  246. pthread_t show_parts_thread;
  247. Error *local_error = NULL;
  248. sioc = qio_channel_socket_new();
  249. if (qio_channel_socket_connect_sync(sioc,
  250. saddr,
  251. &local_error) < 0) {
  252. error_report_err(local_error);
  253. goto out;
  254. }
  255. ret = nbd_receive_negotiate(NULL, QIO_CHANNEL(sioc),
  256. NULL, NULL, NULL, &info, &local_error);
  257. if (ret < 0) {
  258. if (local_error) {
  259. error_report_err(local_error);
  260. }
  261. goto out_socket;
  262. }
  263. fd = open(device, O_RDWR);
  264. if (fd < 0) {
  265. /* Linux-only, we can use %m in printf. */
  266. error_report("Failed to open %s: %m", device);
  267. goto out_socket;
  268. }
  269. ret = nbd_init(fd, sioc, &info, &local_error);
  270. if (ret < 0) {
  271. error_report_err(local_error);
  272. goto out_fd;
  273. }
  274. /* update partition table */
  275. pthread_create(&show_parts_thread, NULL, show_parts, device);
  276. if (verbose) {
  277. fprintf(stderr, "NBD device %s is now connected to %s\n",
  278. device, srcpath);
  279. } else {
  280. /* Close stderr so that the qemu-nbd process exits. */
  281. dup2(STDOUT_FILENO, STDERR_FILENO);
  282. }
  283. ret = nbd_client(fd);
  284. if (ret) {
  285. goto out_fd;
  286. }
  287. close(fd);
  288. object_unref(OBJECT(sioc));
  289. g_free(info.name);
  290. kill(getpid(), SIGTERM);
  291. return (void *) EXIT_SUCCESS;
  292. out_fd:
  293. close(fd);
  294. out_socket:
  295. object_unref(OBJECT(sioc));
  296. out:
  297. g_free(info.name);
  298. kill(getpid(), SIGTERM);
  299. return (void *) EXIT_FAILURE;
  300. }
  301. #endif /* HAVE_NBD_DEVICE */
  302. static int nbd_can_accept(void)
  303. {
  304. return state == RUNNING && nb_fds < shared;
  305. }
  306. static void nbd_export_closed(NBDExport *export)
  307. {
  308. assert(state == TERMINATING);
  309. state = TERMINATED;
  310. }
  311. static void nbd_update_server_watch(void);
  312. static void nbd_client_closed(NBDClient *client, bool negotiated)
  313. {
  314. nb_fds--;
  315. if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
  316. state = TERMINATE;
  317. }
  318. nbd_update_server_watch();
  319. nbd_client_put(client);
  320. }
  321. static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
  322. gpointer opaque)
  323. {
  324. if (state >= TERMINATE) {
  325. return;
  326. }
  327. nb_fds++;
  328. nbd_update_server_watch();
  329. nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
  330. }
  331. static void nbd_update_server_watch(void)
  332. {
  333. if (nbd_can_accept()) {
  334. qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
  335. } else {
  336. qio_net_listener_set_client_func(server, NULL, NULL, NULL);
  337. }
  338. }
  339. static SocketAddress *nbd_build_socket_address(const char *sockpath,
  340. const char *bindto,
  341. const char *port)
  342. {
  343. SocketAddress *saddr;
  344. saddr = g_new0(SocketAddress, 1);
  345. if (sockpath) {
  346. saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
  347. saddr->u.q_unix.path = g_strdup(sockpath);
  348. } else {
  349. InetSocketAddress *inet;
  350. saddr->type = SOCKET_ADDRESS_TYPE_INET;
  351. inet = &saddr->u.inet;
  352. inet->host = g_strdup(bindto);
  353. if (port) {
  354. inet->port = g_strdup(port);
  355. } else {
  356. inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
  357. }
  358. }
  359. return saddr;
  360. }
  361. static QemuOptsList file_opts = {
  362. .name = "file",
  363. .implied_opt_name = "file",
  364. .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
  365. .desc = {
  366. /* no elements => accept any params */
  367. { /* end of list */ }
  368. },
  369. };
  370. static QemuOptsList qemu_object_opts = {
  371. .name = "object",
  372. .implied_opt_name = "qom-type",
  373. .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
  374. .desc = {
  375. { }
  376. },
  377. };
  378. static bool qemu_nbd_object_print_help(const char *type, QemuOpts *opts)
  379. {
  380. if (user_creatable_print_help(type, opts)) {
  381. exit(0);
  382. }
  383. return true;
  384. }
  385. static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
  386. Error **errp)
  387. {
  388. Object *obj;
  389. QCryptoTLSCreds *creds;
  390. obj = object_resolve_path_component(
  391. object_get_objects_root(), id);
  392. if (!obj) {
  393. error_setg(errp, "No TLS credentials with id '%s'",
  394. id);
  395. return NULL;
  396. }
  397. creds = (QCryptoTLSCreds *)
  398. object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
  399. if (!creds) {
  400. error_setg(errp, "Object with id '%s' is not TLS credentials",
  401. id);
  402. return NULL;
  403. }
  404. if (list) {
  405. if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
  406. error_setg(errp,
  407. "Expecting TLS credentials with a client endpoint");
  408. return NULL;
  409. }
  410. } else {
  411. if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
  412. error_setg(errp,
  413. "Expecting TLS credentials with a server endpoint");
  414. return NULL;
  415. }
  416. }
  417. object_ref(obj);
  418. return creds;
  419. }
  420. static void setup_address_and_port(const char **address, const char **port)
  421. {
  422. if (*address == NULL) {
  423. *address = "0.0.0.0";
  424. }
  425. if (*port == NULL) {
  426. *port = stringify(NBD_DEFAULT_PORT);
  427. }
  428. }
  429. /*
  430. * Check socket parameters compatibility when socket activation is used.
  431. */
  432. static const char *socket_activation_validate_opts(const char *device,
  433. const char *sockpath,
  434. const char *address,
  435. const char *port,
  436. bool list)
  437. {
  438. if (device != NULL) {
  439. return "NBD device can't be set when using socket activation";
  440. }
  441. if (sockpath != NULL) {
  442. return "Unix socket can't be set when using socket activation";
  443. }
  444. if (address != NULL) {
  445. return "The interface can't be set when using socket activation";
  446. }
  447. if (port != NULL) {
  448. return "TCP port number can't be set when using socket activation";
  449. }
  450. if (list) {
  451. return "List mode is incompatible with socket activation";
  452. }
  453. return NULL;
  454. }
  455. static void qemu_nbd_shutdown(void)
  456. {
  457. job_cancel_sync_all();
  458. bdrv_close_all();
  459. }
  460. int main(int argc, char **argv)
  461. {
  462. BlockBackend *blk;
  463. BlockDriverState *bs;
  464. uint64_t dev_offset = 0;
  465. bool readonly = false;
  466. bool disconnect = false;
  467. const char *bindto = NULL;
  468. const char *port = NULL;
  469. char *sockpath = NULL;
  470. char *device = NULL;
  471. int64_t fd_size;
  472. QemuOpts *sn_opts = NULL;
  473. const char *sn_id_or_name = NULL;
  474. const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:B:L";
  475. struct option lopt[] = {
  476. { "help", no_argument, NULL, 'h' },
  477. { "version", no_argument, NULL, 'V' },
  478. { "bind", required_argument, NULL, 'b' },
  479. { "port", required_argument, NULL, 'p' },
  480. { "socket", required_argument, NULL, 'k' },
  481. { "offset", required_argument, NULL, 'o' },
  482. { "read-only", no_argument, NULL, 'r' },
  483. { "bitmap", required_argument, NULL, 'B' },
  484. { "connect", required_argument, NULL, 'c' },
  485. { "disconnect", no_argument, NULL, 'd' },
  486. { "list", no_argument, NULL, 'L' },
  487. { "snapshot", no_argument, NULL, 's' },
  488. { "load-snapshot", required_argument, NULL, 'l' },
  489. { "nocache", no_argument, NULL, 'n' },
  490. { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
  491. { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
  492. { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
  493. { "detect-zeroes", required_argument, NULL,
  494. QEMU_NBD_OPT_DETECT_ZEROES },
  495. { "shared", required_argument, NULL, 'e' },
  496. { "format", required_argument, NULL, 'f' },
  497. { "persistent", no_argument, NULL, 't' },
  498. { "verbose", no_argument, NULL, 'v' },
  499. { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
  500. { "export-name", required_argument, NULL, 'x' },
  501. { "description", required_argument, NULL, 'D' },
  502. { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
  503. { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
  504. { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
  505. { "trace", required_argument, NULL, 'T' },
  506. { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
  507. { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
  508. { NULL, 0, NULL, 0 }
  509. };
  510. int ch;
  511. int opt_ind = 0;
  512. int flags = BDRV_O_RDWR;
  513. int ret = 0;
  514. bool seen_cache = false;
  515. bool seen_discard = false;
  516. bool seen_aio = false;
  517. pthread_t client_thread;
  518. const char *fmt = NULL;
  519. Error *local_err = NULL;
  520. BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
  521. QDict *options = NULL;
  522. const char *export_name = NULL; /* defaults to "" later for server mode */
  523. const char *export_description = NULL;
  524. const char *bitmap = NULL;
  525. const char *tlscredsid = NULL;
  526. bool imageOpts = false;
  527. bool writethrough = true;
  528. char *trace_file = NULL;
  529. bool fork_process = false;
  530. bool list = false;
  531. int old_stderr = -1;
  532. unsigned socket_activation;
  533. const char *pid_file_name = NULL;
  534. /* The client thread uses SIGTERM to interrupt the server. A signal
  535. * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
  536. */
  537. struct sigaction sa_sigterm;
  538. memset(&sa_sigterm, 0, sizeof(sa_sigterm));
  539. sa_sigterm.sa_handler = termsig_handler;
  540. sigaction(SIGTERM, &sa_sigterm, NULL);
  541. #ifdef CONFIG_POSIX
  542. signal(SIGPIPE, SIG_IGN);
  543. #endif
  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. int stderr_fd[2];
  827. pid_t pid;
  828. int ret;
  829. if (qemu_pipe(stderr_fd) < 0) {
  830. error_report("Error setting up communication pipe: %s",
  831. strerror(errno));
  832. exit(EXIT_FAILURE);
  833. }
  834. /* Now daemonize, but keep a communication channel open to
  835. * print errors and exit with the proper status code.
  836. */
  837. pid = fork();
  838. if (pid < 0) {
  839. error_report("Failed to fork: %s", strerror(errno));
  840. exit(EXIT_FAILURE);
  841. } else if (pid == 0) {
  842. close(stderr_fd[0]);
  843. /* Remember parent's stderr if we will be restoring it. */
  844. if (fork_process) {
  845. old_stderr = dup(STDERR_FILENO);
  846. }
  847. ret = qemu_daemon(1, 0);
  848. /* Temporarily redirect stderr to the parent's pipe... */
  849. dup2(stderr_fd[1], STDERR_FILENO);
  850. if (ret < 0) {
  851. error_report("Failed to daemonize: %s", strerror(errno));
  852. exit(EXIT_FAILURE);
  853. }
  854. /* ... close the descriptor we inherited and go on. */
  855. close(stderr_fd[1]);
  856. } else {
  857. bool errors = false;
  858. char *buf;
  859. /* In the parent. Print error messages from the child until
  860. * it closes the pipe.
  861. */
  862. close(stderr_fd[1]);
  863. buf = g_malloc(1024);
  864. while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
  865. errors = true;
  866. ret = qemu_write_full(STDERR_FILENO, buf, ret);
  867. if (ret < 0) {
  868. exit(EXIT_FAILURE);
  869. }
  870. }
  871. if (ret < 0) {
  872. error_report("Cannot read from daemon: %s",
  873. strerror(errno));
  874. exit(EXIT_FAILURE);
  875. }
  876. /* Usually the daemon should not print any message.
  877. * Exit with zero status in that case.
  878. */
  879. exit(errors);
  880. }
  881. }
  882. if (device != NULL && sockpath == NULL) {
  883. sockpath = g_malloc(128);
  884. snprintf(sockpath, 128, SOCKET_PATH, basename(device));
  885. }
  886. server = qio_net_listener_new();
  887. if (socket_activation == 0) {
  888. saddr = nbd_build_socket_address(sockpath, bindto, port);
  889. if (qio_net_listener_open_sync(server, saddr, 1, &local_err) < 0) {
  890. object_unref(OBJECT(server));
  891. error_report_err(local_err);
  892. exit(EXIT_FAILURE);
  893. }
  894. } else {
  895. size_t i;
  896. /* See comment in check_socket_activation above. */
  897. for (i = 0; i < socket_activation; i++) {
  898. QIOChannelSocket *sioc;
  899. sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
  900. &local_err);
  901. if (sioc == NULL) {
  902. object_unref(OBJECT(server));
  903. error_reportf_err(local_err,
  904. "Failed to use socket activation: ");
  905. exit(EXIT_FAILURE);
  906. }
  907. qio_net_listener_add(server, sioc);
  908. object_unref(OBJECT(sioc));
  909. }
  910. }
  911. if (qemu_init_main_loop(&local_err)) {
  912. error_report_err(local_err);
  913. exit(EXIT_FAILURE);
  914. }
  915. bdrv_init();
  916. atexit(qemu_nbd_shutdown);
  917. srcpath = argv[optind];
  918. if (imageOpts) {
  919. QemuOpts *opts;
  920. if (fmt) {
  921. error_report("--image-opts and -f are mutually exclusive");
  922. exit(EXIT_FAILURE);
  923. }
  924. opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
  925. if (!opts) {
  926. qemu_opts_reset(&file_opts);
  927. exit(EXIT_FAILURE);
  928. }
  929. options = qemu_opts_to_qdict(opts, NULL);
  930. qemu_opts_reset(&file_opts);
  931. blk = blk_new_open(NULL, NULL, options, flags, &local_err);
  932. } else {
  933. if (fmt) {
  934. options = qdict_new();
  935. qdict_put_str(options, "driver", fmt);
  936. }
  937. blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
  938. }
  939. if (!blk) {
  940. error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
  941. argv[optind]);
  942. exit(EXIT_FAILURE);
  943. }
  944. bs = blk_bs(blk);
  945. blk_set_enable_write_cache(blk, !writethrough);
  946. if (sn_opts) {
  947. ret = bdrv_snapshot_load_tmp(bs,
  948. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  949. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  950. &local_err);
  951. } else if (sn_id_or_name) {
  952. ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
  953. &local_err);
  954. }
  955. if (ret < 0) {
  956. error_reportf_err(local_err, "Failed to load snapshot: ");
  957. exit(EXIT_FAILURE);
  958. }
  959. bs->detect_zeroes = detect_zeroes;
  960. fd_size = blk_getlength(blk);
  961. if (fd_size < 0) {
  962. error_report("Failed to determine the image length: %s",
  963. strerror(-fd_size));
  964. exit(EXIT_FAILURE);
  965. }
  966. if (dev_offset >= fd_size) {
  967. error_report("Offset (%" PRIu64 ") has to be smaller than the image "
  968. "size (%" PRId64 ")", dev_offset, fd_size);
  969. exit(EXIT_FAILURE);
  970. }
  971. fd_size -= dev_offset;
  972. export = nbd_export_new(bs, dev_offset, fd_size, export_name,
  973. export_description, bitmap, readonly, shared > 1,
  974. nbd_export_closed, writethrough, NULL,
  975. &error_fatal);
  976. if (device) {
  977. #if HAVE_NBD_DEVICE
  978. int ret;
  979. ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
  980. if (ret != 0) {
  981. error_report("Failed to create client thread: %s", strerror(ret));
  982. exit(EXIT_FAILURE);
  983. }
  984. #endif
  985. } else {
  986. /* Shut up GCC warnings. */
  987. memset(&client_thread, 0, sizeof(client_thread));
  988. }
  989. nbd_update_server_watch();
  990. if (pid_file_name) {
  991. qemu_write_pidfile(pid_file_name, &error_fatal);
  992. }
  993. /* now when the initialization is (almost) complete, chdir("/")
  994. * to free any busy filesystems */
  995. if (chdir("/") < 0) {
  996. error_report("Could not chdir to root directory: %s",
  997. strerror(errno));
  998. exit(EXIT_FAILURE);
  999. }
  1000. if (fork_process) {
  1001. dup2(old_stderr, STDERR_FILENO);
  1002. close(old_stderr);
  1003. }
  1004. state = RUNNING;
  1005. do {
  1006. main_loop_wait(false);
  1007. if (state == TERMINATE) {
  1008. state = TERMINATING;
  1009. nbd_export_close(export);
  1010. nbd_export_put(export);
  1011. export = NULL;
  1012. }
  1013. } while (state != TERMINATED);
  1014. blk_unref(blk);
  1015. if (sockpath) {
  1016. unlink(sockpath);
  1017. }
  1018. qemu_opts_del(sn_opts);
  1019. if (device) {
  1020. void *ret;
  1021. pthread_join(client_thread, &ret);
  1022. exit(ret != NULL);
  1023. } else {
  1024. exit(EXIT_SUCCESS);
  1025. }
  1026. }