nslookup.c 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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[] ALIGN1 = {
  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[] ALIGN_PTR = {
  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_for_read("/etc/resolv.conf");
  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. char *tokstate;
  613. p = strtok_r(line, " \t\n", &tokstate);
  614. if (!p)
  615. continue;
  616. dbg("resolv_key:'%s'\n", p);
  617. arg = strtok_r(NULL, "\n", &tokstate);
  618. dbg("resolv_arg:'%s'\n", arg);
  619. if (!arg)
  620. continue;
  621. if (strcmp(p, "domain") == 0) {
  622. /* domain DOM */
  623. if (!G.have_search_directive)
  624. goto set_search;
  625. continue;
  626. }
  627. if (strcmp(p, "search") == 0) {
  628. /* search DOM1 DOM2... */
  629. G.have_search_directive = 1;
  630. set_search:
  631. free(G.search);
  632. G.search = xstrdup(arg);
  633. dbg("search='%s'\n", G.search);
  634. continue;
  635. }
  636. if (strcmp(p, "nameserver") != 0)
  637. continue;
  638. /* nameserver DNS */
  639. add_ns(xstrdup(arg));
  640. }
  641. fclose(resolv);
  642. }
  643. if (!G.search) {
  644. /* default search domain is domain part of hostname */
  645. char *h = safe_gethostname();
  646. char *d = strchr(h, '.');
  647. if (d) {
  648. G.search = d + 1;
  649. dbg("search='%s' (from hostname)\n", G.search);
  650. }
  651. /* else free(h); */
  652. }
  653. /* Cater for case of "domain ." in resolv.conf */
  654. if (G.search && LONE_CHAR(G.search, '.'))
  655. G.search = NULL;
  656. }
  657. static void add_query(int type, const char *dname)
  658. {
  659. struct query *new_q;
  660. unsigned count;
  661. ssize_t qlen;
  662. count = G.query_count++;
  663. G.query = xrealloc_vector(G.query, /*4=2^2:*/ 2, count);
  664. new_q = &G.query[count];
  665. dbg("new query#%u type %u for '%s'\n", count, type, dname);
  666. new_q->name = dname;
  667. qlen = res_mkquery(QUERY, dname, C_IN, type,
  668. /*data:*/ NULL, /*datalen:*/ 0,
  669. /*newrr:*/ NULL,
  670. new_q->query, sizeof(new_q->query)
  671. );
  672. new_q->qlen = qlen;
  673. }
  674. static void add_query_with_search(int type, const char *dname)
  675. {
  676. char *s;
  677. if (type == T_PTR || !G.search || strchr(dname, '.')) {
  678. add_query(type, dname);
  679. return;
  680. }
  681. s = G.search;
  682. for (;;) {
  683. char *fullname, *e;
  684. e = skip_non_whitespace(s);
  685. fullname = xasprintf("%s.%.*s", dname, (int)(e - s), s);
  686. add_query(type, fullname);
  687. s = skip_whitespace(e);
  688. if (!*s)
  689. break;
  690. }
  691. }
  692. static char *make_ptr(const char *addrstr)
  693. {
  694. unsigned char addr[16];
  695. #if ENABLE_FEATURE_IPV6
  696. if (inet_pton(AF_INET6, addrstr, addr)) {
  697. if (memcmp(addr, v4_mapped, 12) != 0) {
  698. int i;
  699. char resbuf[80];
  700. char *ptr = resbuf;
  701. for (i = 0; i < 16; i++) {
  702. *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] & 0xf];
  703. *ptr++ = '.';
  704. *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] >> 4];
  705. *ptr++ = '.';
  706. }
  707. strcpy(ptr, "ip6.arpa");
  708. return xstrdup(resbuf);
  709. }
  710. return xasprintf("%u.%u.%u.%u.in-addr.arpa",
  711. addr[15], addr[14], addr[13], addr[12]);
  712. }
  713. #endif
  714. if (inet_pton(AF_INET, addrstr, addr)) {
  715. return xasprintf("%u.%u.%u.%u.in-addr.arpa",
  716. addr[3], addr[2], addr[1], addr[0]);
  717. }
  718. return NULL;
  719. }
  720. int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  721. int nslookup_main(int argc UNUSED_PARAM, char **argv)
  722. {
  723. unsigned types;
  724. int rc;
  725. int err;
  726. INIT_G();
  727. /* manpage: "Options can also be specified on the command line
  728. * if they precede the arguments and are prefixed with a hyphen."
  729. */
  730. types = 0;
  731. argv++;
  732. for (;;) {
  733. const char *options =
  734. // bind-utils-9.11.3 accept these:
  735. // class= cl=
  736. // type= ty= querytype= query= qu= q=
  737. // domain= do=
  738. // port= po=
  739. // timeout= t=
  740. // retry= ret=
  741. // ndots=
  742. // recurse
  743. // norecurse
  744. // defname
  745. // nodefname
  746. // vc
  747. // novc
  748. // debug
  749. // nodebug
  750. // d2
  751. // nod2
  752. // search
  753. // nosearch
  754. // sil
  755. // fail
  756. // nofail
  757. // ver (prints version and exits)
  758. "type\0" /* 0 */
  759. "querytype\0" /* 1 */
  760. "port\0" /* 2 */
  761. "retry\0" /* 3 */
  762. "debug\0" /* 4 */
  763. "t\0" /* disambiguate with "type": else -t=2 fails */
  764. "timeout\0" /* 6 */
  765. "";
  766. int i;
  767. char *arg;
  768. char *val;
  769. if (!*argv)
  770. bb_show_usage();
  771. if (argv[0][0] != '-')
  772. break;
  773. /* Separate out "=val" part */
  774. arg = (*argv++) + 1;
  775. val = strchrnul(arg, '=');
  776. if (*val)
  777. *val++ = '\0';
  778. i = index_in_substrings(options, arg);
  779. //bb_error_msg("i:%d arg:'%s' val:'%s'", i, arg, val);
  780. if (i < 0)
  781. bb_show_usage();
  782. if (i <= 1) {
  783. for (i = 0;; i++) {
  784. if (i == ARRAY_SIZE(qtypes))
  785. bb_error_msg_and_die("invalid query type \"%s\"", val);
  786. if (strcasecmp(qtypes[i].name, val) == 0)
  787. break;
  788. }
  789. types |= (1 << i);
  790. continue;
  791. }
  792. if (i == 2) {
  793. G.default_port = xatou_range(val, 1, 0xffff);
  794. }
  795. if (i == 3) {
  796. G.default_retry = xatou_range(val, 1, INT_MAX);
  797. }
  798. if (i == 4) {
  799. option_mask32 |= OPT_debug;
  800. }
  801. if (i > 4) {
  802. G.default_timeout = xatou_range(val, 1, INT_MAX / 1000);
  803. }
  804. }
  805. /* Use given DNS server if present */
  806. if (argv[1]) {
  807. if (argv[2])
  808. bb_show_usage();
  809. add_ns(argv[1]);
  810. } else {
  811. parse_resolvconf();
  812. /* Fall back to localhost if we could not find NS in resolv.conf */
  813. if (G.serv_count == 0)
  814. add_ns("127.0.0.1");
  815. }
  816. if (types == 0) {
  817. /* No explicit type given, guess query type.
  818. * If we can convert the domain argument into a ptr (means that
  819. * inet_pton() could read it) we assume a PTR request, else
  820. * we issue A+AAAA queries and switch to an output format
  821. * mimicking the one of the traditional nslookup applet.
  822. */
  823. char *ptr;
  824. ptr = make_ptr(argv[0]);
  825. if (ptr) {
  826. add_query(T_PTR, ptr);
  827. } else {
  828. add_query_with_search(T_A, argv[0]);
  829. #if ENABLE_FEATURE_IPV6
  830. add_query_with_search(T_AAAA, argv[0]);
  831. #endif
  832. }
  833. } else {
  834. int c;
  835. for (c = 0; c < ARRAY_SIZE(qtypes); c++) {
  836. if (types & (1 << c))
  837. add_query_with_search(qtypes[c].type, argv[0]);
  838. }
  839. }
  840. for (rc = 0; rc < G.serv_count;) {
  841. int c;
  842. c = send_queries(&G.server[rc]);
  843. if (c > 0) {
  844. /* more than zero replies received */
  845. #if 0 /* which version does this? */
  846. if (option_mask32 & OPT_debug) {
  847. printf("Replies:\t%d\n", G.server[rc].replies);
  848. printf("Failures:\t%d\n\n", G.server[rc].failures);
  849. }
  850. #endif
  851. break;
  852. //FIXME: we "break" even though some queries may still be not answered, and other servers may know them?
  853. }
  854. /* c = 0: timed out waiting for replies */
  855. /* c < 0: error (message already printed) */
  856. rc++;
  857. if (rc >= G.serv_count) {
  858. //
  859. // NB: bind-utils-9.11.3 behavior (all to stdout, not stderr):
  860. //
  861. // $ nslookup gmail.com 8.8.8.8
  862. // ;; connection timed out; no servers could be reached
  863. //
  864. // Using TCP mode:
  865. // $ nslookup -vc gmail.com 8.8.8.8; echo EXITCODE:$?
  866. // <~10 sec>
  867. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  868. // <~10 sec>
  869. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  870. // <~10 sec>
  871. // ;; connection timed out; no servers could be reached
  872. // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
  873. // <empty line>
  874. // EXITCODE:1
  875. // $ _
  876. printf(";; connection timed out; no servers could be reached\n\n");
  877. return EXIT_FAILURE;
  878. }
  879. }
  880. err = 0;
  881. for (rc = 0; rc < G.query_count; rc++) {
  882. if (G.query[rc].qlen) {
  883. printf("*** Can't find %s: No answer\n", G.query[rc].name);
  884. err = 1;
  885. }
  886. }
  887. if (err) /* should this affect exicode too? */
  888. bb_putchar('\n');
  889. if (ENABLE_FEATURE_CLEAN_UP) {
  890. free(G.server);
  891. free(G.query);
  892. }
  893. return G.exitcode;
  894. }
  895. #endif