You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

qemu-nbd.c 38KB

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