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 39KB

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