nslookup.c 24 KB

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