2
0

qemu-nbd.c 39 KB

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