nslookup.c 26 KB

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