qemu-nbd.c 41 KB

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