nslookup.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. /* vi: set sw=4 ts=4: */
  2. //config:config NSLOOKUP
  3. //config: bool "nslookup (4.5 kb)"
  4. //config: default y
  5. //config: help
  6. //config: nslookup is a tool to query Internet name servers.
  7. //config:
  8. //config:config FEATURE_NSLOOKUP_BIG
  9. //config: bool "Use internal resolver code instead of libc"
  10. //config: depends on NSLOOKUP
  11. //config: default y
  12. //config:
  13. //config:config FEATURE_NSLOOKUP_LONG_OPTIONS
  14. //config: bool "Enable long options"
  15. //config: default y
  16. //config: depends on FEATURE_NSLOOKUP_BIG && LONG_OPTS
  17. //applet:IF_NSLOOKUP(APPLET(nslookup, BB_DIR_USR_BIN, BB_SUID_DROP))
  18. //kbuild:lib-$(CONFIG_NSLOOKUP) += nslookup.o
  19. //usage:#define nslookup_trivial_usage
  20. //usage: IF_FEATURE_NSLOOKUP_BIG("[-type=QUERY_TYPE] [-debug] ") "HOST [DNS_SERVER]"
  21. //usage:#define nslookup_full_usage "\n\n"
  22. //usage: "Query DNS about HOST"
  23. //usage: IF_FEATURE_NSLOOKUP_BIG("\n")
  24. //usage: IF_FEATURE_NSLOOKUP_BIG("\nQUERY_TYPE: soa,ns,a,"IF_FEATURE_IPV6("aaaa,")"cname,mx,txt,ptr,any")
  25. //usage:#define nslookup_example_usage
  26. //usage: "$ nslookup localhost\n"
  27. //usage: "Server: default\n"
  28. //usage: "Address: default\n"
  29. //usage: "\n"
  30. //usage: "Name: debian\n"
  31. //usage: "Address: 127.0.0.1\n"
  32. #include <resolv.h>
  33. #include <net/if.h> /* for IFNAMSIZ */
  34. //#include <arpa/inet.h>
  35. //#include <netdb.h>
  36. #include "libbb.h"
  37. #include "common_bufsiz.h"
  38. #if !ENABLE_FEATURE_NSLOOKUP_BIG
  39. /*
  40. * Mini nslookup implementation for busybox
  41. *
  42. * Copyright (C) 1999,2000 by Lineo, inc. and John Beppu
  43. * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
  44. *
  45. * Correct default name server display and explicit name server option
  46. * added by Ben Zeckel <bzeckel@hmc.edu> June 2001
  47. *
  48. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  49. */
  50. /*
  51. * I'm only implementing non-interactive mode;
  52. * I totally forgot nslookup even had an interactive mode.
  53. *
  54. * This applet is the only user of res_init(). Without it,
  55. * you may avoid pulling in _res global from libc.
  56. */
  57. /* Examples of 'standard' nslookup output
  58. * $ nslookup yahoo.com
  59. * Server: 128.193.0.10
  60. * Address: 128.193.0.10#53
  61. *
  62. * Non-authoritative answer:
  63. * Name: yahoo.com
  64. * Address: 216.109.112.135
  65. * Name: yahoo.com
  66. * Address: 66.94.234.13
  67. *
  68. * $ nslookup 204.152.191.37
  69. * Server: 128.193.4.20
  70. * Address: 128.193.4.20#53
  71. *
  72. * Non-authoritative answer:
  73. * 37.191.152.204.in-addr.arpa canonical name = 37.32-27.191.152.204.in-addr.arpa.
  74. * 37.32-27.191.152.204.in-addr.arpa name = zeus-pub2.kernel.org.
  75. *
  76. * Authoritative answers can be found from:
  77. * 32-27.191.152.204.in-addr.arpa nameserver = ns1.kernel.org.
  78. * 32-27.191.152.204.in-addr.arpa nameserver = ns2.kernel.org.
  79. * 32-27.191.152.204.in-addr.arpa nameserver = ns3.kernel.org.
  80. * ns1.kernel.org internet address = 140.211.167.34
  81. * ns2.kernel.org internet address = 204.152.191.4
  82. * ns3.kernel.org internet address = 204.152.191.36
  83. */
  84. static int print_host(const char *hostname, const char *header)
  85. {
  86. /* We can't use xhost2sockaddr() - we want to get ALL addresses,
  87. * not just one */
  88. struct addrinfo *result = NULL;
  89. int rc;
  90. struct addrinfo hint;
  91. memset(&hint, 0 , sizeof(hint));
  92. /* hint.ai_family = AF_UNSPEC; - zero anyway */
  93. /* Needed. Or else we will get each address thrice (or more)
  94. * for each possible socket type (tcp,udp,raw...): */
  95. hint.ai_socktype = SOCK_STREAM;
  96. // hint.ai_flags = AI_CANONNAME;
  97. rc = getaddrinfo(hostname, NULL /*service*/, &hint, &result);
  98. if (rc == 0) {
  99. struct addrinfo *cur = result;
  100. unsigned cnt = 0;
  101. printf("%-10s %s\n", header, hostname);
  102. // puts(cur->ai_canonname); ?
  103. while (cur) {
  104. char *dotted, *revhost;
  105. dotted = xmalloc_sockaddr2dotted_noport(cur->ai_addr);
  106. revhost = xmalloc_sockaddr2hostonly_noport(cur->ai_addr);
  107. printf("Address %u: %s%c", ++cnt, dotted, revhost ? ' ' : '\n');
  108. if (revhost) {
  109. puts(revhost);
  110. if (ENABLE_FEATURE_CLEAN_UP)
  111. free(revhost);
  112. }
  113. if (ENABLE_FEATURE_CLEAN_UP)
  114. free(dotted);
  115. cur = cur->ai_next;
  116. }
  117. } else {
  118. #if ENABLE_VERBOSE_RESOLUTION_ERRORS
  119. bb_error_msg("can't resolve '%s': %s", hostname, gai_strerror(rc));
  120. #else
  121. bb_error_msg("can't resolve '%s'", hostname);
  122. #endif
  123. }
  124. if (ENABLE_FEATURE_CLEAN_UP && result)
  125. freeaddrinfo(result);
  126. return (rc != 0);
  127. }
  128. /* lookup the default nameserver and display it */
  129. static void server_print(void)
  130. {
  131. char *server;
  132. struct sockaddr *sa;
  133. #if ENABLE_FEATURE_IPV6
  134. sa = (struct sockaddr*)_res._u._ext.nsaddrs[0];
  135. if (!sa)
  136. #endif
  137. sa = (struct sockaddr*)&_res.nsaddr_list[0];
  138. server = xmalloc_sockaddr2dotted_noport(sa);
  139. print_host(server, "Server:");
  140. if (ENABLE_FEATURE_CLEAN_UP)
  141. free(server);
  142. bb_putchar('\n');
  143. }
  144. /* alter the global _res nameserver structure to use
  145. an explicit dns server instead of what is in /etc/resolv.conf */
  146. static void set_default_dns(const char *server)
  147. {
  148. len_and_sockaddr *lsa;
  149. if (!server)
  150. return;
  151. /* NB: this works even with, say, "[::1]:5353"! :) */
  152. lsa = xhost2sockaddr(server, 53);
  153. if (lsa->u.sa.sa_family == AF_INET) {
  154. _res.nscount = 1;
  155. /* struct copy */
  156. _res.nsaddr_list[0] = lsa->u.sin;
  157. }
  158. #if ENABLE_FEATURE_IPV6
  159. /* Hoped libc can cope with IPv4 address there too.
  160. * No such luck, glibc 2.4 segfaults even with IPv6,
  161. * maybe I misunderstand how to make glibc use IPv6 addr?
  162. * (uclibc 0.9.31+ should work) */
  163. if (lsa->u.sa.sa_family == AF_INET6) {
  164. // glibc neither SEGVs nor sends any dgrams with this
  165. // (strace shows no socket ops):
  166. //_res.nscount = 0;
  167. _res._u._ext.nscount = 1;
  168. /* store a pointer to part of malloc'ed lsa */
  169. _res._u._ext.nsaddrs[0] = &lsa->u.sin6;
  170. /* must not free(lsa)! */
  171. }
  172. #endif
  173. }
  174. int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  175. int nslookup_main(int argc, char **argv)
  176. {
  177. /* We allow 1 or 2 arguments.
  178. * The first is the name to be looked up and the second is an
  179. * optional DNS server with which to do the lookup.
  180. * More than 3 arguments is an error to follow the pattern of the
  181. * standard nslookup */
  182. if (!argv[1] || argv[1][0] == '-' || argc > 3)
  183. bb_show_usage();
  184. /* initialize DNS structure _res used in printing the default
  185. * name server and in the explicit name server option feature. */
  186. res_init();
  187. /* rfc2133 says this enables IPv6 lookups */
  188. /* (but it also says "may be enabled in /etc/resolv.conf") */
  189. /*_res.options |= RES_USE_INET6;*/
  190. set_default_dns(argv[2]);
  191. server_print();
  192. /* getaddrinfo and friends are free to request a resolver
  193. * reinitialization. Just in case, set_default_dns() again
  194. * after getaddrinfo (in server_print). This reportedly helps
  195. * with bug 675 "nslookup does not properly use second argument"
  196. * at least on Debian Wheezy and Openwrt AA (eglibc based).
  197. */
  198. set_default_dns(argv[2]);
  199. return print_host(argv[1], "Name:");
  200. }
  201. #else /****** A version from LEDE / OpenWRT ******/
  202. /*
  203. * musl compatible nslookup
  204. *
  205. * Copyright (C) 2017 Jo-Philipp Wich <jo@mein.io>
  206. *
  207. * Permission to use, copy, modify, and/or distribute this software for any
  208. * purpose with or without fee is hereby granted, provided that the above
  209. * copyright notice and this permission notice appear in all copies.
  210. *
  211. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  212. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  213. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  214. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  215. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  216. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  217. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  218. */
  219. #if 0
  220. # define dbg(...) fprintf(stderr, __VA_ARGS__)
  221. #else
  222. # define dbg(...) ((void)0)
  223. #endif
  224. struct ns {
  225. const char *name;
  226. len_and_sockaddr *lsa;
  227. int failures;
  228. int replies;
  229. };
  230. struct query {
  231. const char *name;
  232. unsigned qlen;
  233. // unsigned latency;
  234. // uint8_t rcode;
  235. unsigned char query[512];
  236. // unsigned char reply[512];
  237. };
  238. static const struct {
  239. unsigned char type;
  240. char name[7];
  241. } qtypes[] = {
  242. { ns_t_soa, "SOA" },
  243. { ns_t_ns, "NS" },
  244. { ns_t_a, "A" },
  245. #if ENABLE_FEATURE_IPV6
  246. { ns_t_aaaa, "AAAA" },
  247. #endif
  248. { ns_t_cname, "CNAME" },
  249. { ns_t_mx, "MX" },
  250. { ns_t_txt, "TXT" },
  251. { ns_t_ptr, "PTR" },
  252. { ns_t_any, "ANY" },
  253. };
  254. static const char *const rcodes[] = {
  255. "NOERROR", // 0
  256. "FORMERR", // 1
  257. "SERVFAIL", // 2
  258. "NXDOMAIN", // 3
  259. "NOTIMP", // 4
  260. "REFUSED", // 5
  261. "YXDOMAIN", // 6
  262. "YXRRSET", // 7
  263. "NXRRSET", // 8
  264. "NOTAUTH", // 9
  265. "NOTZONE", // 10
  266. "11", // 11 not assigned
  267. "12", // 12 not assigned
  268. "13", // 13 not assigned
  269. "14", // 14 not assigned
  270. "15", // 15 not assigned
  271. };
  272. #if ENABLE_FEATURE_IPV6
  273. static const char v4_mapped[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xff,0xff };
  274. #endif
  275. struct globals {
  276. unsigned default_port;
  277. unsigned default_retry;
  278. unsigned default_timeout;
  279. unsigned query_count;
  280. unsigned serv_count;
  281. struct ns *server;
  282. struct query *query;
  283. } FIX_ALIASING;
  284. #define G (*(struct globals*)bb_common_bufsiz1)
  285. #define INIT_G() do { \
  286. setup_common_bufsiz(); \
  287. G.default_port = 53; \
  288. G.default_retry = 2; \
  289. G.default_timeout = 5; \
  290. } while (0)
  291. enum {
  292. OPT_debug = (1 << 0),
  293. };
  294. static int parse_reply(const unsigned char *msg, size_t len)
  295. {
  296. HEADER *header;
  297. ns_msg handle;
  298. ns_rr rr;
  299. int i, n, rdlen;
  300. const char *format = NULL;
  301. char astr[INET6_ADDRSTRLEN], dname[MAXDNAME];
  302. const unsigned char *cp;
  303. header = (HEADER *)msg;
  304. if (!header->aa)
  305. printf("Non-authoritative answer:\n");
  306. if (ns_initparse(msg, len, &handle) != 0) {
  307. //printf("Unable to parse reply: %s\n", strerror(errno));
  308. return -1;
  309. }
  310. for (i = 0; i < ns_msg_count(handle, ns_s_an); i++) {
  311. if (ns_parserr(&handle, ns_s_an, i, &rr) != 0) {
  312. //printf("Unable to parse resource record: %s\n", strerror(errno));
  313. return -1;
  314. }
  315. rdlen = ns_rr_rdlen(rr);
  316. switch (ns_rr_type(rr))
  317. {
  318. case ns_t_a:
  319. if (rdlen != 4) {
  320. dbg("unexpected A record length %d\n", rdlen);
  321. return -1;
  322. }
  323. inet_ntop(AF_INET, ns_rr_rdata(rr), astr, sizeof(astr));
  324. printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
  325. break;
  326. #if ENABLE_FEATURE_IPV6
  327. case ns_t_aaaa:
  328. if (rdlen != 16) {
  329. dbg("unexpected AAAA record length %d\n", rdlen);
  330. return -1;
  331. }
  332. inet_ntop(AF_INET6, ns_rr_rdata(rr), astr, sizeof(astr));
  333. /* bind-utils-9.11.3 uses the same format for A and AAAA answers */
  334. printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
  335. break;
  336. #endif
  337. case ns_t_ns:
  338. if (!format)
  339. format = "%s\tnameserver = %s\n";
  340. /* fall through */
  341. case ns_t_cname:
  342. if (!format)
  343. format = "%s\tcanonical name = %s\n";
  344. /* fall through */
  345. case ns_t_ptr:
  346. if (!format)
  347. format = "%s\tname = %s\n";
  348. if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  349. ns_rr_rdata(rr), dname, sizeof(dname)) < 0
  350. ) {
  351. //printf("Unable to uncompress domain: %s\n", strerror(errno));
  352. return -1;
  353. }
  354. printf(format, ns_rr_name(rr), dname);
  355. break;
  356. case ns_t_mx:
  357. if (rdlen < 2) {
  358. printf("MX record too short\n");
  359. return -1;
  360. }
  361. n = ns_get16(ns_rr_rdata(rr));
  362. if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  363. ns_rr_rdata(rr) + 2, dname, sizeof(dname)) < 0
  364. ) {
  365. //printf("Cannot uncompress MX domain: %s\n", strerror(errno));
  366. return -1;
  367. }
  368. printf("%s\tmail exchanger = %d %s\n", ns_rr_name(rr), n, dname);
  369. break;
  370. case ns_t_txt:
  371. if (rdlen < 1) {
  372. //printf("TXT record too short\n");
  373. return -1;
  374. }
  375. n = *(unsigned char *)ns_rr_rdata(rr);
  376. if (n > 0) {
  377. memset(dname, 0, sizeof(dname));
  378. memcpy(dname, ns_rr_rdata(rr) + 1, n);
  379. printf("%s\ttext = \"%s\"\n", ns_rr_name(rr), dname);
  380. }
  381. break;
  382. case ns_t_soa:
  383. if (rdlen < 20) {
  384. dbg("SOA record too short:%d\n", rdlen);
  385. return -1;
  386. }
  387. printf("%s\n", ns_rr_name(rr));
  388. cp = ns_rr_rdata(rr);
  389. n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  390. cp, dname, sizeof(dname));
  391. if (n < 0) {
  392. //printf("Unable to uncompress domain: %s\n", strerror(errno));
  393. return -1;
  394. }
  395. printf("\torigin = %s\n", dname);
  396. cp += n;
  397. n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  398. cp, dname, sizeof(dname));
  399. if (n < 0) {
  400. //printf("Unable to uncompress domain: %s\n", strerror(errno));
  401. return -1;
  402. }
  403. printf("\tmail addr = %s\n", dname);
  404. cp += n;
  405. printf("\tserial = %lu\n", ns_get32(cp));
  406. cp += 4;
  407. printf("\trefresh = %lu\n", ns_get32(cp));
  408. cp += 4;
  409. printf("\tretry = %lu\n", ns_get32(cp));
  410. cp += 4;
  411. printf("\texpire = %lu\n", ns_get32(cp));
  412. cp += 4;
  413. printf("\tminimum = %lu\n", ns_get32(cp));
  414. break;
  415. default:
  416. break;
  417. }
  418. }
  419. return i;
  420. }
  421. /*
  422. * Function logic borrowed & modified from musl libc, res_msend.c
  423. * G.query_count is always > 0.
  424. */
  425. static int send_queries(struct ns *ns)
  426. {
  427. unsigned char reply[512];
  428. uint8_t rcode;
  429. len_and_sockaddr *local_lsa;
  430. struct pollfd pfd;
  431. int servfail_retry = 0;
  432. int n_replies = 0;
  433. // int save_idx = 0;
  434. unsigned retry_interval;
  435. unsigned timeout = G.default_timeout * 1000;
  436. unsigned tstart, tsent, tcur;
  437. pfd.events = POLLIN;
  438. pfd.fd = xsocket_type(&local_lsa, ns->lsa->u.sa.sa_family, SOCK_DGRAM);
  439. /*
  440. * local_lsa has "null" address and port 0 now.
  441. * bind() ensures we have a *particular port* selected by kernel
  442. * and remembered in fd, thus later recv(fd)
  443. * receives only packets sent to this port.
  444. */
  445. xbind(pfd.fd, &local_lsa->u.sa, local_lsa->len);
  446. free(local_lsa);
  447. /* Make read/writes know the destination */
  448. xconnect(pfd.fd, &ns->lsa->u.sa, ns->lsa->len);
  449. ndelay_on(pfd.fd);
  450. retry_interval = timeout / G.default_retry;
  451. tstart = tcur = monotonic_ms();
  452. goto send;
  453. while (tcur - tstart < timeout) {
  454. int qn;
  455. int recvlen;
  456. if (tcur - tsent >= retry_interval) {
  457. send:
  458. for (qn = 0; qn < G.query_count; qn++) {
  459. if (G.query[qn].qlen == 0)
  460. continue; /* this one was replied already */
  461. if (write(pfd.fd, G.query[qn].query, G.query[qn].qlen) < 0) {
  462. bb_perror_msg("write to '%s'", ns->name);
  463. n_replies = -1; /* "no go, try next server" */
  464. goto ret;
  465. }
  466. dbg("query %u sent\n", qn);
  467. }
  468. tsent = tcur;
  469. servfail_retry = 2 * G.query_count;
  470. }
  471. /* Wait for a response, or until time to retry */
  472. if (poll(&pfd, 1, retry_interval - (tcur - tsent)) <= 0)
  473. goto next;
  474. recvlen = read(pfd.fd, reply, sizeof(reply));
  475. if (recvlen < 0) {
  476. bb_perror_msg("read");
  477. next:
  478. tcur = monotonic_ms();
  479. continue;
  480. }
  481. if (ns->replies++ == 0) {
  482. printf("Server:\t\t%s\n", ns->name);
  483. printf("Address:\t%s\n\n",
  484. auto_string(xmalloc_sockaddr2dotted(&ns->lsa->u.sa))
  485. );
  486. /* In "Address", bind-utils-9.11.3 show port after a hash: "1.2.3.4#53" */
  487. /* Should we do the same? */
  488. }
  489. /* Non-identifiable packet */
  490. if (recvlen < 4) {
  491. dbg("read is too short:%d\n", recvlen);
  492. goto next;
  493. }
  494. /* Find which query this answer goes with, if any */
  495. // qn = save_idx;
  496. qn = 0;
  497. for (;;) {
  498. if (memcmp(reply, G.query[qn].query, 2) == 0) {
  499. dbg("response matches query %u\n", qn);
  500. break;
  501. }
  502. if (++qn >= G.query_count) {
  503. dbg("response does not match any query\n");
  504. goto next;
  505. }
  506. }
  507. if (G.query[qn].qlen == 0) {
  508. dbg("dropped duplicate response to query %u\n", qn);
  509. goto next;
  510. }
  511. rcode = reply[3] & 0x0f;
  512. dbg("query %u rcode:%s\n", qn, rcodes[rcode]);
  513. /* Retry immediately on SERVFAIL */
  514. if (rcode == 2) {
  515. ns->failures++;
  516. if (servfail_retry) {
  517. servfail_retry--;
  518. write(pfd.fd, G.query[qn].query, G.query[qn].qlen);
  519. dbg("query %u resent\n", qn);
  520. goto next;
  521. }
  522. }
  523. /* Process reply */
  524. G.query[qn].qlen = 0; /* flag: "reply received" */
  525. tcur = monotonic_ms();
  526. #if 1
  527. if (option_mask32 & OPT_debug) {
  528. printf("Query #%d completed in %ums:\n", qn, tcur - tstart);
  529. }
  530. if (rcode != 0) {
  531. printf("** server can't find %s: %s\n",
  532. G.query[qn].name, rcodes[rcode]);
  533. } else {
  534. if (parse_reply(reply, recvlen) < 0)
  535. printf("*** Can't find %s: Parse error\n", G.query[qn].name);
  536. }
  537. bb_putchar('\n');
  538. n_replies++;
  539. if (n_replies >= G.query_count)
  540. goto ret;
  541. #else
  542. //used to store replies and process them later
  543. G.query[qn].latency = tcur - tstart;
  544. n_replies++;
  545. if (qn != save_idx) {
  546. /* "wrong" receive buffer, move to correct one */
  547. memcpy(G.query[qn].reply, G.query[save_idx].reply, recvlen);
  548. continue;
  549. }
  550. /* G.query[0..save_idx] have replies, move to next one, if exists */
  551. for (;;) {
  552. save_idx++;
  553. if (save_idx >= G.query_count)
  554. goto ret; /* all are full: we have all results */
  555. if (!G.query[save_idx].rlen)
  556. break; /* this one is empty */
  557. }
  558. #endif
  559. } /* while() */
  560. ret:
  561. close(pfd.fd);
  562. return n_replies;
  563. }
  564. static void add_ns(const char *addr)
  565. {
  566. struct ns *ns;
  567. unsigned count;
  568. dbg("%s: addr:'%s'\n", __func__, addr);
  569. count = G.serv_count++;
  570. G.server = xrealloc_vector(G.server, /*8=2^3:*/ 3, count);
  571. ns = &G.server[count];
  572. ns->name = addr;
  573. ns->lsa = xhost2sockaddr(addr, G.default_port);
  574. /*ns->replies = 0; - already is */
  575. /*ns->failures = 0; - already is */
  576. }
  577. static void parse_resolvconf(void)
  578. {
  579. FILE *resolv;
  580. resolv = fopen("/etc/resolv.conf", "r");
  581. if (resolv) {
  582. char line[128], *p;
  583. while (fgets(line, sizeof(line), resolv)) {
  584. p = strtok(line, " \t\n");
  585. if (!p || strcmp(p, "nameserver") != 0)
  586. continue;
  587. p = strtok(NULL, " \t\n");
  588. if (!p)
  589. continue;
  590. add_ns(xstrdup(p));
  591. }
  592. fclose(resolv);
  593. }
  594. }
  595. static void add_query(int type, const char *dname)
  596. {
  597. struct query *new_q;
  598. unsigned count;
  599. ssize_t qlen;
  600. count = G.query_count++;
  601. G.query = xrealloc_vector(G.query, /*2=2^1:*/ 1, count);
  602. new_q = &G.query[count];
  603. dbg("new query#%u type %u for '%s'\n", count, type, dname);
  604. new_q->name = dname;
  605. qlen = res_mkquery(QUERY, dname, C_IN, type,
  606. /*data:*/ NULL, /*datalen:*/ 0,
  607. /*newrr:*/ NULL,
  608. new_q->query, sizeof(new_q->query)
  609. );
  610. new_q->qlen = qlen;
  611. }
  612. static char *make_ptr(const char *addrstr)
  613. {
  614. unsigned char addr[16];
  615. #if ENABLE_FEATURE_IPV6
  616. if (inet_pton(AF_INET6, addrstr, addr)) {
  617. if (memcmp(addr, v4_mapped, 12) != 0) {
  618. int i;
  619. char resbuf[80];
  620. char *ptr = resbuf;
  621. for (i = 0; i < 16; i++) {
  622. *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] & 0xf];
  623. *ptr++ = '.';
  624. *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] >> 4];
  625. *ptr++ = '.';
  626. }
  627. strcpy(ptr, "ip6.arpa");
  628. return xstrdup(resbuf);
  629. }
  630. return xasprintf("%u.%u.%u.%u.in-addr.arpa",
  631. addr[15], addr[14], addr[13], addr[12]);
  632. }
  633. #endif
  634. if (inet_pton(AF_INET, addrstr, addr)) {
  635. return xasprintf("%u.%u.%u.%u.in-addr.arpa",
  636. addr[3], addr[2], addr[1], addr[0]);
  637. }
  638. return NULL;
  639. }
  640. int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  641. int nslookup_main(int argc UNUSED_PARAM, char **argv)
  642. {
  643. unsigned types;
  644. int rc;
  645. int err;
  646. INIT_G();
  647. /* manpage: "Options can also be specified on the command line
  648. * if they precede the arguments and are prefixed with a hyphen."
  649. */
  650. types = 0;
  651. argv++;
  652. for (;;) {
  653. const char *options =
  654. // bind-utils-9.11.3 accept these:
  655. // class= cl=
  656. // type= ty= querytype= query= qu= q=
  657. // domain= do=
  658. // port= po=
  659. // timeout= t=
  660. // retry= ret=
  661. // ndots=
  662. // recurse
  663. // norecurse
  664. // defname
  665. // nodefname
  666. // vc
  667. // novc
  668. // debug
  669. // nodebug
  670. // d2
  671. // nod2
  672. // search
  673. // nosearch
  674. // sil
  675. // fail
  676. // nofail
  677. // ver (prints version and exits)
  678. "type\0" /* 0 */
  679. "querytype\0" /* 1 */
  680. "port\0" /* 2 */
  681. "retry\0" /* 3 */
  682. "debug\0" /* 4 */
  683. "t\0" /* disambiguate with "type": else -t=2 fails */
  684. "timeout\0" /* 6 */
  685. "";
  686. int i;
  687. char *arg;
  688. char *val;
  689. if (!*argv)
  690. bb_show_usage();
  691. if (argv[0][0] != '-')
  692. break;
  693. /* Separate out "=val" part */
  694. arg = (*argv++) + 1;
  695. val = strchrnul(arg, '=');
  696. if (*val)
  697. *val++ = '\0';
  698. i = index_in_substrings(options, arg);
  699. //bb_error_msg("i:%d arg:'%s' val:'%s'", i, arg, val);
  700. if (i < 0)
  701. bb_show_usage();
  702. if (i <= 1) {
  703. for (i = 0;; i++) {
  704. if (i == ARRAY_SIZE(qtypes))
  705. bb_error_msg_and_die("invalid query type \"%s\"", val);
  706. if (strcasecmp(qtypes[i].name, val) == 0)
  707. break;
  708. }
  709. types |= (1 << i);
  710. continue;
  711. }
  712. if (i == 2) {
  713. G.default_port = xatou_range(val, 1, 0xffff);
  714. }
  715. if (i == 3) {
  716. G.default_retry = xatou_range(val, 1, INT_MAX);
  717. }
  718. if (i == 4) {
  719. option_mask32 |= OPT_debug;
  720. }
  721. if (i > 4) {
  722. G.default_timeout = xatou_range(val, 1, INT_MAX / 1000);
  723. }
  724. }
  725. if (types == 0) {
  726. /* No explicit type given, guess query type.
  727. * If we can convert the domain argument into a ptr (means that
  728. * inet_pton() could read it) we assume a PTR request, else
  729. * we issue A+AAAA queries and switch to an output format
  730. * mimicking the one of the traditional nslookup applet.
  731. */
  732. char *ptr;
  733. ptr = make_ptr(argv[0]);
  734. if (ptr) {
  735. add_query(T_PTR, ptr);
  736. } else {
  737. add_query(T_A, argv[0]);
  738. #if ENABLE_FEATURE_IPV6
  739. add_query(T_AAAA, argv[0]);
  740. #endif
  741. }
  742. } else {
  743. int c;
  744. for (c = 0; c < ARRAY_SIZE(qtypes); c++) {
  745. if (types & (1 << c))
  746. add_query(qtypes[c].type, argv[0]);
  747. }
  748. }
  749. /* Use given DNS server if present */
  750. if (argv[1]) {
  751. if (argv[2])
  752. bb_show_usage();
  753. add_ns(argv[1]);
  754. } else {
  755. parse_resolvconf();
  756. /* Fall back to localhost if we could not find NS in resolv.conf */
  757. if (G.serv_count == 0)
  758. add_ns("127.0.0.1");
  759. }
  760. for (rc = 0; rc < G.serv_count;) {
  761. int c;
  762. c = send_queries(&G.server[rc]);
  763. if (c > 0) {
  764. /* more than zero replies received */
  765. #if 0 /* which version does this? */
  766. if (option_mask32 & OPT_debug) {
  767. printf("Replies:\t%d\n", G.server[rc].replies);
  768. printf("Failures:\t%d\n\n", G.server[rc].failures);
  769. }
  770. #endif
  771. break;
  772. //FIXME: we "break" even though some queries may still be not answered, and other servers may know them?
  773. }
  774. /* c = 0: timed out waiting for replies */
  775. /* c < 0: error (message already printed) */
  776. rc++;
  777. if (rc >= G.serv_count) {
  778. //
  779. // NB: bind-utils-9.11.3 behavior (all to stdout, not stderr):
  780. //
  781. // $ nslookup gmail.com 8.8.8.8
  782. // ;; connection timed out; no servers could be reached
  783. //
  784. // Using TCP mode:
  785. // $ nslookup -vc gmail.com 8.8.8.8; echo EXITCODE:$?
  786. // <~10 sec>
  787. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  788. // <~10 sec>
  789. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  790. // <~10 sec>
  791. // ;; connection timed out; no servers could be reached
  792. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  793. // <empty line>
  794. // EXITCODE:1
  795. // $ _
  796. printf(";; connection timed out; no servers could be reached\n\n");
  797. return EXIT_FAILURE;
  798. }
  799. }
  800. err = 0;
  801. for (rc = 0; rc < G.query_count; rc++) {
  802. if (G.query[rc].qlen) {
  803. printf("*** Can't find %s: No answer\n", G.query[rc].name);
  804. err = 1;
  805. }
  806. }
  807. if (err) /* should this affect exicode too? */
  808. bb_putchar('\n');
  809. if (ENABLE_FEATURE_CLEAN_UP) {
  810. free(G.server);
  811. free(G.query);
  812. }
  813. return EXIT_SUCCESS;
  814. }
  815. #endif