2
0

qemu-nbd.c 38 KB

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