nslookup.c 24 KB

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