nslookup.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. /* vi: set sw=4 ts=4: */
  2. //config:config NSLOOKUP
  3. //config: bool "nslookup (9.7 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. //UNUSED: 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_srv, "SRV" },
  252. { ns_t_ptr, "PTR" },
  253. { ns_t_any, "ANY" },
  254. };
  255. static const char *const rcodes[] = {
  256. "NOERROR", // 0
  257. "FORMERR", // 1
  258. "SERVFAIL", // 2
  259. "NXDOMAIN", // 3
  260. "NOTIMP", // 4
  261. "REFUSED", // 5
  262. "YXDOMAIN", // 6
  263. "YXRRSET", // 7
  264. "NXRRSET", // 8
  265. "NOTAUTH", // 9
  266. "NOTZONE", // 10
  267. "11", // 11 not assigned
  268. "12", // 12 not assigned
  269. "13", // 13 not assigned
  270. "14", // 14 not assigned
  271. "15", // 15 not assigned
  272. };
  273. #if ENABLE_FEATURE_IPV6
  274. static const char v4_mapped[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xff,0xff };
  275. #endif
  276. struct globals {
  277. unsigned default_port;
  278. unsigned default_retry;
  279. unsigned default_timeout;
  280. unsigned query_count;
  281. unsigned serv_count;
  282. struct ns *server;
  283. struct query *query;
  284. char *search;
  285. smalluint have_search_directive;
  286. smalluint exitcode;
  287. } FIX_ALIASING;
  288. #define G (*(struct globals*)bb_common_bufsiz1)
  289. #define INIT_G() do { \
  290. setup_common_bufsiz(); \
  291. G.default_port = 53; \
  292. G.default_retry = 2; \
  293. G.default_timeout = 5; \
  294. } while (0)
  295. enum {
  296. OPT_debug = (1 << 0),
  297. };
  298. static int parse_reply(const unsigned char *msg, size_t len)
  299. {
  300. HEADER *header;
  301. ns_msg handle;
  302. ns_rr rr;
  303. int i, n, rdlen;
  304. const char *format = NULL;
  305. char astr[INET6_ADDRSTRLEN], dname[MAXDNAME];
  306. const unsigned char *cp;
  307. header = (HEADER *)msg;
  308. if (!header->aa)
  309. printf("Non-authoritative answer:\n");
  310. if (ns_initparse(msg, len, &handle) != 0) {
  311. //printf("Unable to parse reply: %s\n", strerror(errno));
  312. return -1;
  313. }
  314. for (i = 0; i < ns_msg_count(handle, ns_s_an); i++) {
  315. if (ns_parserr(&handle, ns_s_an, i, &rr) != 0) {
  316. //printf("Unable to parse resource record: %s\n", strerror(errno));
  317. return -1;
  318. }
  319. rdlen = ns_rr_rdlen(rr);
  320. switch (ns_rr_type(rr))
  321. {
  322. case ns_t_a:
  323. if (rdlen != 4) {
  324. dbg("unexpected A record length %d\n", rdlen);
  325. return -1;
  326. }
  327. inet_ntop(AF_INET, ns_rr_rdata(rr), astr, sizeof(astr));
  328. printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
  329. break;
  330. #if ENABLE_FEATURE_IPV6
  331. case ns_t_aaaa:
  332. if (rdlen != 16) {
  333. dbg("unexpected AAAA record length %d\n", rdlen);
  334. return -1;
  335. }
  336. inet_ntop(AF_INET6, ns_rr_rdata(rr), astr, sizeof(astr));
  337. /* bind-utils-9.11.3 uses the same format for A and AAAA answers */
  338. printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
  339. break;
  340. #endif
  341. case ns_t_ns:
  342. if (!format)
  343. format = "%s\tnameserver = %s\n";
  344. /* fall through */
  345. case ns_t_cname:
  346. if (!format)
  347. format = "%s\tcanonical name = %s\n";
  348. /* fall through */
  349. case ns_t_ptr:
  350. if (!format)
  351. format = "%s\tname = %s\n";
  352. if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  353. ns_rr_rdata(rr), dname, sizeof(dname)) < 0
  354. ) {
  355. //printf("Unable to uncompress domain: %s\n", strerror(errno));
  356. return -1;
  357. }
  358. printf(format, ns_rr_name(rr), dname);
  359. break;
  360. case ns_t_mx:
  361. if (rdlen < 2) {
  362. printf("MX record too short\n");
  363. return -1;
  364. }
  365. n = ns_get16(ns_rr_rdata(rr));
  366. if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  367. ns_rr_rdata(rr) + 2, dname, sizeof(dname)) < 0
  368. ) {
  369. //printf("Cannot uncompress MX domain: %s\n", strerror(errno));
  370. return -1;
  371. }
  372. printf("%s\tmail exchanger = %d %s\n", ns_rr_name(rr), n, dname);
  373. break;
  374. case ns_t_txt:
  375. if (rdlen < 1) {
  376. //printf("TXT record too short\n");
  377. return -1;
  378. }
  379. n = *(unsigned char *)ns_rr_rdata(rr);
  380. if (n > 0) {
  381. memset(dname, 0, sizeof(dname));
  382. memcpy(dname, ns_rr_rdata(rr) + 1, n);
  383. printf("%s\ttext = \"%s\"\n", ns_rr_name(rr), dname);
  384. }
  385. break;
  386. case ns_t_srv:
  387. if (rdlen < 6) {
  388. //printf("SRV record too short\n");
  389. return -1;
  390. }
  391. cp = ns_rr_rdata(rr);
  392. n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  393. cp + 6, dname, sizeof(dname));
  394. if (n < 0) {
  395. //printf("Unable to uncompress domain: %s\n", strerror(errno));
  396. return -1;
  397. }
  398. printf("%s\tservice = %u %u %u %s\n", ns_rr_name(rr),
  399. ns_get16(cp), ns_get16(cp + 2), ns_get16(cp + 4), dname);
  400. break;
  401. case ns_t_soa:
  402. if (rdlen < 20) {
  403. dbg("SOA record too short:%d\n", rdlen);
  404. return -1;
  405. }
  406. printf("%s\n", ns_rr_name(rr));
  407. cp = ns_rr_rdata(rr);
  408. n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  409. cp, dname, sizeof(dname));
  410. if (n < 0) {
  411. //printf("Unable to uncompress domain: %s\n", strerror(errno));
  412. return -1;
  413. }
  414. printf("\torigin = %s\n", dname);
  415. cp += n;
  416. n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
  417. cp, dname, sizeof(dname));
  418. if (n < 0) {
  419. //printf("Unable to uncompress domain: %s\n", strerror(errno));
  420. return -1;
  421. }
  422. printf("\tmail addr = %s\n", dname);
  423. cp += n;
  424. printf("\tserial = %lu\n", ns_get32(cp));
  425. cp += 4;
  426. printf("\trefresh = %lu\n", ns_get32(cp));
  427. cp += 4;
  428. printf("\tretry = %lu\n", ns_get32(cp));
  429. cp += 4;
  430. printf("\texpire = %lu\n", ns_get32(cp));
  431. cp += 4;
  432. printf("\tminimum = %lu\n", ns_get32(cp));
  433. break;
  434. default:
  435. break;
  436. }
  437. }
  438. return i;
  439. }
  440. /*
  441. * Function logic borrowed & modified from musl libc, res_msend.c
  442. * G.query_count is always > 0.
  443. */
  444. static int send_queries(struct ns *ns)
  445. {
  446. unsigned char reply[512];
  447. uint8_t rcode;
  448. len_and_sockaddr *local_lsa;
  449. struct pollfd pfd;
  450. int servfail_retry = 0;
  451. int n_replies = 0;
  452. // int save_idx = 0;
  453. unsigned retry_interval;
  454. unsigned timeout = G.default_timeout * 1000;
  455. unsigned tstart, tsent, tcur;
  456. pfd.events = POLLIN;
  457. pfd.fd = xsocket_type(&local_lsa, ns->lsa->u.sa.sa_family, SOCK_DGRAM);
  458. /*
  459. * local_lsa has "null" address and port 0 now.
  460. * bind() ensures we have a *particular port* selected by kernel
  461. * and remembered in fd, thus later recv(fd)
  462. * receives only packets sent to this port.
  463. */
  464. xbind(pfd.fd, &local_lsa->u.sa, local_lsa->len);
  465. free(local_lsa);
  466. /* Make read/writes know the destination */
  467. xconnect(pfd.fd, &ns->lsa->u.sa, ns->lsa->len);
  468. ndelay_on(pfd.fd);
  469. retry_interval = timeout / G.default_retry;
  470. tstart = tcur = monotonic_ms();
  471. goto send;
  472. while (tcur - tstart < timeout) {
  473. int qn;
  474. int recvlen;
  475. if (tcur - tsent >= retry_interval) {
  476. send:
  477. for (qn = 0; qn < G.query_count; qn++) {
  478. if (G.query[qn].qlen == 0)
  479. continue; /* this one was replied already */
  480. if (write(pfd.fd, G.query[qn].query, G.query[qn].qlen) < 0) {
  481. bb_perror_msg("write to '%s'", ns->name);
  482. n_replies = -1; /* "no go, try next server" */
  483. goto ret;
  484. }
  485. dbg("query %u sent\n", qn);
  486. }
  487. tsent = tcur;
  488. servfail_retry = 2 * G.query_count;
  489. }
  490. /* Wait for a response, or until time to retry */
  491. if (poll(&pfd, 1, retry_interval - (tcur - tsent)) <= 0)
  492. goto next;
  493. recvlen = read(pfd.fd, reply, sizeof(reply));
  494. if (recvlen < 0) {
  495. bb_simple_perror_msg("read");
  496. next:
  497. tcur = monotonic_ms();
  498. continue;
  499. }
  500. if (ns->replies++ == 0) {
  501. printf("Server:\t\t%s\n", ns->name);
  502. printf("Address:\t%s\n\n",
  503. auto_string(xmalloc_sockaddr2dotted(&ns->lsa->u.sa))
  504. );
  505. /* In "Address", bind-utils-9.11.3 show port after a hash: "1.2.3.4#53" */
  506. /* Should we do the same? */
  507. }
  508. /* Non-identifiable packet */
  509. if (recvlen < 4) {
  510. dbg("read is too short:%d\n", recvlen);
  511. goto next;
  512. }
  513. /* Find which query this answer goes with, if any */
  514. // qn = save_idx;
  515. qn = 0;
  516. for (;;) {
  517. if (memcmp(reply, G.query[qn].query, 2) == 0) {
  518. dbg("response matches query %u\n", qn);
  519. break;
  520. }
  521. if (++qn >= G.query_count) {
  522. dbg("response does not match any query\n");
  523. goto next;
  524. }
  525. }
  526. if (G.query[qn].qlen == 0) {
  527. dbg("dropped duplicate response to query %u\n", qn);
  528. goto next;
  529. }
  530. rcode = reply[3] & 0x0f;
  531. dbg("query %u rcode:%s\n", qn, rcodes[rcode]);
  532. /* Retry immediately on SERVFAIL */
  533. if (rcode == 2) {
  534. //UNUSED: ns->failures++;
  535. if (servfail_retry) {
  536. servfail_retry--;
  537. write(pfd.fd, G.query[qn].query, G.query[qn].qlen);
  538. dbg("query %u resent\n", qn);
  539. goto next;
  540. }
  541. }
  542. /* Process reply */
  543. G.query[qn].qlen = 0; /* flag: "reply received" */
  544. tcur = monotonic_ms();
  545. #if 1
  546. if (option_mask32 & OPT_debug) {
  547. printf("Query #%d completed in %ums:\n", qn, tcur - tstart);
  548. }
  549. if (rcode != 0) {
  550. printf("** server can't find %s: %s\n",
  551. G.query[qn].name, rcodes[rcode]);
  552. G.exitcode = EXIT_FAILURE;
  553. } else {
  554. switch (parse_reply(reply, recvlen)) {
  555. case -1:
  556. printf("*** Can't find %s: Parse error\n", G.query[qn].name);
  557. G.exitcode = EXIT_FAILURE;
  558. break;
  559. case 0:
  560. printf("*** Can't find %s: No answer\n", G.query[qn].name);
  561. break;
  562. }
  563. }
  564. bb_putchar('\n');
  565. n_replies++;
  566. if (n_replies >= G.query_count)
  567. goto ret;
  568. #else
  569. //used to store replies and process them later
  570. G.query[qn].latency = tcur - tstart;
  571. n_replies++;
  572. if (qn != save_idx) {
  573. /* "wrong" receive buffer, move to correct one */
  574. memcpy(G.query[qn].reply, G.query[save_idx].reply, recvlen);
  575. continue;
  576. }
  577. /* G.query[0..save_idx] have replies, move to next one, if exists */
  578. for (;;) {
  579. save_idx++;
  580. if (save_idx >= G.query_count)
  581. goto ret; /* all are full: we have all results */
  582. if (!G.query[save_idx].rlen)
  583. break; /* this one is empty */
  584. }
  585. #endif
  586. } /* while() */
  587. ret:
  588. close(pfd.fd);
  589. return n_replies;
  590. }
  591. static void add_ns(const char *addr)
  592. {
  593. struct ns *ns;
  594. unsigned count;
  595. dbg("%s: addr:'%s'\n", __func__, addr);
  596. count = G.serv_count++;
  597. G.server = xrealloc_vector(G.server, /*8=2^3:*/ 3, count);
  598. ns = &G.server[count];
  599. ns->name = addr;
  600. ns->lsa = xhost2sockaddr(addr, G.default_port);
  601. /*ns->replies = 0; - already is */
  602. /*ns->failures = 0; - already is */
  603. }
  604. static void parse_resolvconf(void)
  605. {
  606. FILE *resolv;
  607. resolv = fopen("/etc/resolv.conf", "r");
  608. if (resolv) {
  609. char line[512]; /* "search" is defined to be up to 256 chars */
  610. while (fgets(line, sizeof(line), resolv)) {
  611. char *p, *arg;
  612. p = strtok(line, " \t\n");
  613. if (!p)
  614. continue;
  615. dbg("resolv_key:'%s'\n", p);
  616. arg = strtok(NULL, "\n");
  617. dbg("resolv_arg:'%s'\n", arg);
  618. if (!arg)
  619. continue;
  620. if (strcmp(p, "domain") == 0) {
  621. /* domain DOM */
  622. if (!G.have_search_directive)
  623. goto set_search;
  624. continue;
  625. }
  626. if (strcmp(p, "search") == 0) {
  627. /* search DOM1 DOM2... */
  628. G.have_search_directive = 1;
  629. set_search:
  630. free(G.search);
  631. G.search = xstrdup(arg);
  632. dbg("search='%s'\n", G.search);
  633. continue;
  634. }
  635. if (strcmp(p, "nameserver") != 0)
  636. continue;
  637. /* nameserver DNS */
  638. add_ns(xstrdup(arg));
  639. }
  640. fclose(resolv);
  641. }
  642. if (!G.search) {
  643. /* default search domain is domain part of hostname */
  644. char *h = safe_gethostname();
  645. char *d = strchr(h, '.');
  646. if (d) {
  647. G.search = d + 1;
  648. dbg("search='%s' (from hostname)\n", G.search);
  649. }
  650. /* else free(h); */
  651. }
  652. /* Cater for case of "domain ." in resolv.conf */
  653. if (G.search && LONE_CHAR(G.search, '.'))
  654. G.search = NULL;
  655. }
  656. static void add_query(int type, const char *dname)
  657. {
  658. struct query *new_q;
  659. unsigned count;
  660. ssize_t qlen;
  661. count = G.query_count++;
  662. G.query = xrealloc_vector(G.query, /*4=2^2:*/ 2, count);
  663. new_q = &G.query[count];
  664. dbg("new query#%u type %u for '%s'\n", count, type, dname);
  665. new_q->name = dname;
  666. qlen = res_mkquery(QUERY, dname, C_IN, type,
  667. /*data:*/ NULL, /*datalen:*/ 0,
  668. /*newrr:*/ NULL,
  669. new_q->query, sizeof(new_q->query)
  670. );
  671. new_q->qlen = qlen;
  672. }
  673. static void add_query_with_search(int type, const char *dname)
  674. {
  675. char *s;
  676. if (type == T_PTR || !G.search || strchr(dname, '.')) {
  677. add_query(type, dname);
  678. return;
  679. }
  680. s = G.search;
  681. for (;;) {
  682. char *fullname, *e;
  683. e = skip_non_whitespace(s);
  684. fullname = xasprintf("%s.%.*s", dname, (int)(e - s), s);
  685. add_query(type, fullname);
  686. s = skip_whitespace(e);
  687. if (!*s)
  688. break;
  689. }
  690. }
  691. static char *make_ptr(const char *addrstr)
  692. {
  693. unsigned char addr[16];
  694. #if ENABLE_FEATURE_IPV6
  695. if (inet_pton(AF_INET6, addrstr, addr)) {
  696. if (memcmp(addr, v4_mapped, 12) != 0) {
  697. int i;
  698. char resbuf[80];
  699. char *ptr = resbuf;
  700. for (i = 0; i < 16; i++) {
  701. *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] & 0xf];
  702. *ptr++ = '.';
  703. *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] >> 4];
  704. *ptr++ = '.';
  705. }
  706. strcpy(ptr, "ip6.arpa");
  707. return xstrdup(resbuf);
  708. }
  709. return xasprintf("%u.%u.%u.%u.in-addr.arpa",
  710. addr[15], addr[14], addr[13], addr[12]);
  711. }
  712. #endif
  713. if (inet_pton(AF_INET, addrstr, addr)) {
  714. return xasprintf("%u.%u.%u.%u.in-addr.arpa",
  715. addr[3], addr[2], addr[1], addr[0]);
  716. }
  717. return NULL;
  718. }
  719. int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  720. int nslookup_main(int argc UNUSED_PARAM, char **argv)
  721. {
  722. unsigned types;
  723. int rc;
  724. int err;
  725. INIT_G();
  726. /* manpage: "Options can also be specified on the command line
  727. * if they precede the arguments and are prefixed with a hyphen."
  728. */
  729. types = 0;
  730. argv++;
  731. for (;;) {
  732. const char *options =
  733. // bind-utils-9.11.3 accept these:
  734. // class= cl=
  735. // type= ty= querytype= query= qu= q=
  736. // domain= do=
  737. // port= po=
  738. // timeout= t=
  739. // retry= ret=
  740. // ndots=
  741. // recurse
  742. // norecurse
  743. // defname
  744. // nodefname
  745. // vc
  746. // novc
  747. // debug
  748. // nodebug
  749. // d2
  750. // nod2
  751. // search
  752. // nosearch
  753. // sil
  754. // fail
  755. // nofail
  756. // ver (prints version and exits)
  757. "type\0" /* 0 */
  758. "querytype\0" /* 1 */
  759. "port\0" /* 2 */
  760. "retry\0" /* 3 */
  761. "debug\0" /* 4 */
  762. "t\0" /* disambiguate with "type": else -t=2 fails */
  763. "timeout\0" /* 6 */
  764. "";
  765. int i;
  766. char *arg;
  767. char *val;
  768. if (!*argv)
  769. bb_show_usage();
  770. if (argv[0][0] != '-')
  771. break;
  772. /* Separate out "=val" part */
  773. arg = (*argv++) + 1;
  774. val = strchrnul(arg, '=');
  775. if (*val)
  776. *val++ = '\0';
  777. i = index_in_substrings(options, arg);
  778. //bb_error_msg("i:%d arg:'%s' val:'%s'", i, arg, val);
  779. if (i < 0)
  780. bb_show_usage();
  781. if (i <= 1) {
  782. for (i = 0;; i++) {
  783. if (i == ARRAY_SIZE(qtypes))
  784. bb_error_msg_and_die("invalid query type \"%s\"", val);
  785. if (strcasecmp(qtypes[i].name, val) == 0)
  786. break;
  787. }
  788. types |= (1 << i);
  789. continue;
  790. }
  791. if (i == 2) {
  792. G.default_port = xatou_range(val, 1, 0xffff);
  793. }
  794. if (i == 3) {
  795. G.default_retry = xatou_range(val, 1, INT_MAX);
  796. }
  797. if (i == 4) {
  798. option_mask32 |= OPT_debug;
  799. }
  800. if (i > 4) {
  801. G.default_timeout = xatou_range(val, 1, INT_MAX / 1000);
  802. }
  803. }
  804. /* Use given DNS server if present */
  805. if (argv[1]) {
  806. if (argv[2])
  807. bb_show_usage();
  808. add_ns(argv[1]);
  809. } else {
  810. parse_resolvconf();
  811. /* Fall back to localhost if we could not find NS in resolv.conf */
  812. if (G.serv_count == 0)
  813. add_ns("127.0.0.1");
  814. }
  815. if (types == 0) {
  816. /* No explicit type given, guess query type.
  817. * If we can convert the domain argument into a ptr (means that
  818. * inet_pton() could read it) we assume a PTR request, else
  819. * we issue A+AAAA queries and switch to an output format
  820. * mimicking the one of the traditional nslookup applet.
  821. */
  822. char *ptr;
  823. ptr = make_ptr(argv[0]);
  824. if (ptr) {
  825. add_query(T_PTR, ptr);
  826. } else {
  827. add_query_with_search(T_A, argv[0]);
  828. #if ENABLE_FEATURE_IPV6
  829. add_query_with_search(T_AAAA, argv[0]);
  830. #endif
  831. }
  832. } else {
  833. int c;
  834. for (c = 0; c < ARRAY_SIZE(qtypes); c++) {
  835. if (types & (1 << c))
  836. add_query_with_search(qtypes[c].type, argv[0]);
  837. }
  838. }
  839. for (rc = 0; rc < G.serv_count;) {
  840. int c;
  841. c = send_queries(&G.server[rc]);
  842. if (c > 0) {
  843. /* more than zero replies received */
  844. #if 0 /* which version does this? */
  845. if (option_mask32 & OPT_debug) {
  846. printf("Replies:\t%d\n", G.server[rc].replies);
  847. printf("Failures:\t%d\n\n", G.server[rc].failures);
  848. }
  849. #endif
  850. break;
  851. //FIXME: we "break" even though some queries may still be not answered, and other servers may know them?
  852. }
  853. /* c = 0: timed out waiting for replies */
  854. /* c < 0: error (message already printed) */
  855. rc++;
  856. if (rc >= G.serv_count) {
  857. //
  858. // NB: bind-utils-9.11.3 behavior (all to stdout, not stderr):
  859. //
  860. // $ nslookup gmail.com 8.8.8.8
  861. // ;; connection timed out; no servers could be reached
  862. //
  863. // Using TCP mode:
  864. // $ nslookup -vc gmail.com 8.8.8.8; echo EXITCODE:$?
  865. // <~10 sec>
  866. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  867. // <~10 sec>
  868. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  869. // <~10 sec>
  870. // ;; connection timed out; no servers could be reached
  871. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  872. // <empty line>
  873. // EXITCODE:1
  874. // $ _
  875. printf(";; connection timed out; no servers could be reached\n\n");
  876. return EXIT_FAILURE;
  877. }
  878. }
  879. err = 0;
  880. for (rc = 0; rc < G.query_count; rc++) {
  881. if (G.query[rc].qlen) {
  882. printf("*** Can't find %s: No answer\n", G.query[rc].name);
  883. err = 1;
  884. }
  885. }
  886. if (err) /* should this affect exicode too? */
  887. bb_putchar('\n');
  888. if (ENABLE_FEATURE_CLEAN_UP) {
  889. free(G.server);
  890. free(G.query);
  891. }
  892. return G.exitcode;
  893. }
  894. #endif