1 /* vi: set sw=4 ts=4: */
3 //config:config NSLOOKUP
4 //config: bool "nslookup (4.5 kb)"
7 //config: nslookup is a tool to query Internet name servers.
9 //config:config FEATURE_NSLOOKUP_BIG
10 //config: bool "Use internal resolver code instead of libc"
11 //config: depends on NSLOOKUP
14 //config:config FEATURE_NSLOOKUP_LONG_OPTIONS
15 //config: bool "Enable long options"
17 //config: depends on FEATURE_NSLOOKUP_BIG && LONG_OPTS
19 //applet:IF_NSLOOKUP(APPLET(nslookup, BB_DIR_USR_BIN, BB_SUID_DROP))
21 //kbuild:lib-$(CONFIG_NSLOOKUP) += nslookup.o
23 //usage:#define nslookup_trivial_usage
24 //usage: IF_FEATURE_NSLOOKUP_BIG("[-type=QUERY_TYPE] [-debug] ") "HOST [DNS_SERVER]"
25 //usage:#define nslookup_full_usage "\n\n"
26 //usage: "Query DNS about HOST"
27 //usage: IF_FEATURE_NSLOOKUP_BIG("\n")
28 //usage: IF_FEATURE_NSLOOKUP_BIG("\nQUERY_TYPE: soa,ns,a,"IF_FEATURE_IPV6("aaaa,")"cname,mx,txt,ptr,any")
29 //usage:#define nslookup_example_usage
30 //usage: "$ nslookup localhost\n"
31 //usage: "Server: default\n"
32 //usage: "Address: default\n"
34 //usage: "Name: debian\n"
35 //usage: "Address: 127.0.0.1\n"
38 #include <net/if.h> /* for IFNAMSIZ */
39 //#include <arpa/inet.h>
42 #include "common_bufsiz.h"
45 #if !ENABLE_FEATURE_NSLOOKUP_BIG
48 * Mini nslookup implementation for busybox
50 * Copyright (C) 1999,2000 by Lineo, inc. and John Beppu
51 * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
53 * Correct default name server display and explicit name server option
54 * added by Ben Zeckel <bzeckel@hmc.edu> June 2001
56 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
60 * I'm only implementing non-interactive mode;
61 * I totally forgot nslookup even had an interactive mode.
63 * This applet is the only user of res_init(). Without it,
64 * you may avoid pulling in _res global from libc.
67 /* Examples of 'standard' nslookup output
68 * $ nslookup yahoo.com
69 * Server: 128.193.0.10
70 * Address: 128.193.0.10#53
72 * Non-authoritative answer:
74 * Address: 216.109.112.135
76 * Address: 66.94.234.13
78 * $ nslookup 204.152.191.37
79 * Server: 128.193.4.20
80 * Address: 128.193.4.20#53
82 * Non-authoritative answer:
83 * 37.191.152.204.in-addr.arpa canonical name = 37.32-27.191.152.204.in-addr.arpa.
84 * 37.32-27.191.152.204.in-addr.arpa name = zeus-pub2.kernel.org.
86 * Authoritative answers can be found from:
87 * 32-27.191.152.204.in-addr.arpa nameserver = ns1.kernel.org.
88 * 32-27.191.152.204.in-addr.arpa nameserver = ns2.kernel.org.
89 * 32-27.191.152.204.in-addr.arpa nameserver = ns3.kernel.org.
90 * ns1.kernel.org internet address = 140.211.167.34
91 * ns2.kernel.org internet address = 204.152.191.4
92 * ns3.kernel.org internet address = 204.152.191.36
95 static int print_host(const char *hostname, const char *header)
97 /* We can't use xhost2sockaddr() - we want to get ALL addresses,
99 struct addrinfo *result = NULL;
101 struct addrinfo hint;
103 memset(&hint, 0 , sizeof(hint));
104 /* hint.ai_family = AF_UNSPEC; - zero anyway */
105 /* Needed. Or else we will get each address thrice (or more)
106 * for each possible socket type (tcp,udp,raw...): */
107 hint.ai_socktype = SOCK_STREAM;
108 // hint.ai_flags = AI_CANONNAME;
109 rc = getaddrinfo(hostname, NULL /*service*/, &hint, &result);
112 struct addrinfo *cur = result;
115 printf("%-10s %s\n", header, hostname);
116 // puts(cur->ai_canonname); ?
118 char *dotted, *revhost;
119 dotted = xmalloc_sockaddr2dotted_noport(cur->ai_addr);
120 revhost = xmalloc_sockaddr2hostonly_noport(cur->ai_addr);
122 printf("Address %u: %s%c", ++cnt, dotted, revhost ? ' ' : '\n');
125 if (ENABLE_FEATURE_CLEAN_UP)
128 if (ENABLE_FEATURE_CLEAN_UP)
133 #if ENABLE_VERBOSE_RESOLUTION_ERRORS
134 bb_error_msg("can't resolve '%s': %s", hostname, gai_strerror(rc));
136 bb_error_msg("can't resolve '%s'", hostname);
139 if (ENABLE_FEATURE_CLEAN_UP && result)
140 freeaddrinfo(result);
144 /* lookup the default nameserver and display it */
145 static void server_print(void)
150 #if ENABLE_FEATURE_IPV6
151 sa = (struct sockaddr*)_res._u._ext.nsaddrs[0];
154 sa = (struct sockaddr*)&_res.nsaddr_list[0];
155 server = xmalloc_sockaddr2dotted_noport(sa);
157 print_host(server, "Server:");
158 if (ENABLE_FEATURE_CLEAN_UP)
163 /* alter the global _res nameserver structure to use
164 an explicit dns server instead of what is in /etc/resolv.conf */
165 static void set_default_dns(const char *server)
167 len_and_sockaddr *lsa;
172 /* NB: this works even with, say, "[::1]:5353"! :) */
173 lsa = xhost2sockaddr(server, 53);
175 if (lsa->u.sa.sa_family == AF_INET) {
178 _res.nsaddr_list[0] = lsa->u.sin;
180 #if ENABLE_FEATURE_IPV6
181 /* Hoped libc can cope with IPv4 address there too.
182 * No such luck, glibc 2.4 segfaults even with IPv6,
183 * maybe I misunderstand how to make glibc use IPv6 addr?
184 * (uclibc 0.9.31+ should work) */
185 if (lsa->u.sa.sa_family == AF_INET6) {
186 // glibc neither SEGVs nor sends any dgrams with this
187 // (strace shows no socket ops):
189 _res._u._ext.nscount = 1;
190 /* store a pointer to part of malloc'ed lsa */
191 _res._u._ext.nsaddrs[0] = &lsa->u.sin6;
192 /* must not free(lsa)! */
197 int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
198 int nslookup_main(int argc, char **argv)
200 /* We allow 1 or 2 arguments.
201 * The first is the name to be looked up and the second is an
202 * optional DNS server with which to do the lookup.
203 * More than 3 arguments is an error to follow the pattern of the
204 * standard nslookup */
205 if (!argv[1] || argv[1][0] == '-' || argc > 3)
208 /* initialize DNS structure _res used in printing the default
209 * name server and in the explicit name server option feature. */
211 /* rfc2133 says this enables IPv6 lookups */
212 /* (but it also says "may be enabled in /etc/resolv.conf") */
213 /*_res.options |= RES_USE_INET6;*/
215 set_default_dns(argv[2]);
219 /* getaddrinfo and friends are free to request a resolver
220 * reinitialization. Just in case, set_default_dns() again
221 * after getaddrinfo (in server_print). This reportedly helps
222 * with bug 675 "nslookup does not properly use second argument"
223 * at least on Debian Wheezy and Openwrt AA (eglibc based).
225 set_default_dns(argv[2]);
227 return print_host(argv[1], "Name:");
231 #else /****** A version from LEDE / OpenWRT ******/
234 * musl compatible nslookup
236 * Copyright (C) 2017 Jo-Philipp Wich <jo@mein.io>
238 * Permission to use, copy, modify, and/or distribute this software for any
239 * purpose with or without fee is hereby granted, provided that the above
240 * copyright notice and this permission notice appear in all copies.
242 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
243 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
244 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
245 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
246 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
247 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
248 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
252 # define dbg(...) fprintf(stderr, __VA_ARGS__)
254 # define dbg(...) ((void)0)
259 len_and_sockaddr *lsa;
269 unsigned char query[512];
270 // unsigned char reply[512];
273 static const struct {
280 #if ENABLE_FEATURE_IPV6
281 { ns_t_aaaa, "AAAA" },
283 { ns_t_cname, "CNAME" },
290 static const char *const rcodes[] = {
302 "11", // 11 not assigned
303 "12", // 12 not assigned
304 "13", // 13 not assigned
305 "14", // 14 not assigned
306 "15", // 15 not assigned
309 #if ENABLE_FEATURE_IPV6
310 static const char v4_mapped[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xff,0xff };
314 unsigned default_port;
315 unsigned default_retry;
316 unsigned default_timeout;
317 unsigned query_count;
322 smalluint have_search_directive;
324 #define G (*(struct globals*)bb_common_bufsiz1)
325 #define INIT_G() do { \
326 setup_common_bufsiz(); \
327 G.default_port = 53; \
328 G.default_retry = 2; \
329 G.default_timeout = 5; \
333 OPT_debug = (1 << 0),
336 static int parse_reply(const unsigned char *msg, size_t len)
343 const char *format = NULL;
344 char astr[INET6_ADDRSTRLEN], dname[MAXDNAME];
345 const unsigned char *cp;
347 header = (HEADER *)msg;
349 printf("Non-authoritative answer:\n");
351 if (ns_initparse(msg, len, &handle) != 0) {
352 //printf("Unable to parse reply: %s\n", strerror(errno));
356 for (i = 0; i < ns_msg_count(handle, ns_s_an); i++) {
357 if (ns_parserr(&handle, ns_s_an, i, &rr) != 0) {
358 //printf("Unable to parse resource record: %s\n", strerror(errno));
362 rdlen = ns_rr_rdlen(rr);
364 switch (ns_rr_type(rr))
368 dbg("unexpected A record length %d\n", rdlen);
371 inet_ntop(AF_INET, ns_rr_rdata(rr), astr, sizeof(astr));
372 printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
375 #if ENABLE_FEATURE_IPV6
378 dbg("unexpected AAAA record length %d\n", rdlen);
381 inet_ntop(AF_INET6, ns_rr_rdata(rr), astr, sizeof(astr));
382 /* bind-utils-9.11.3 uses the same format for A and AAAA answers */
383 printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
389 format = "%s\tnameserver = %s\n";
394 format = "%s\tcanonical name = %s\n";
399 format = "%s\tname = %s\n";
400 if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
401 ns_rr_rdata(rr), dname, sizeof(dname)) < 0
403 //printf("Unable to uncompress domain: %s\n", strerror(errno));
406 printf(format, ns_rr_name(rr), dname);
411 printf("MX record too short\n");
414 n = ns_get16(ns_rr_rdata(rr));
415 if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
416 ns_rr_rdata(rr) + 2, dname, sizeof(dname)) < 0
418 //printf("Cannot uncompress MX domain: %s\n", strerror(errno));
421 printf("%s\tmail exchanger = %d %s\n", ns_rr_name(rr), n, dname);
426 //printf("TXT record too short\n");
429 n = *(unsigned char *)ns_rr_rdata(rr);
431 memset(dname, 0, sizeof(dname));
432 memcpy(dname, ns_rr_rdata(rr) + 1, n);
433 printf("%s\ttext = \"%s\"\n", ns_rr_name(rr), dname);
439 dbg("SOA record too short:%d\n", rdlen);
443 printf("%s\n", ns_rr_name(rr));
445 cp = ns_rr_rdata(rr);
446 n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
447 cp, dname, sizeof(dname));
449 //printf("Unable to uncompress domain: %s\n", strerror(errno));
453 printf("\torigin = %s\n", dname);
456 n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
457 cp, dname, sizeof(dname));
459 //printf("Unable to uncompress domain: %s\n", strerror(errno));
463 printf("\tmail addr = %s\n", dname);
466 printf("\tserial = %lu\n", ns_get32(cp));
469 printf("\trefresh = %lu\n", ns_get32(cp));
472 printf("\tretry = %lu\n", ns_get32(cp));
475 printf("\texpire = %lu\n", ns_get32(cp));
478 printf("\tminimum = %lu\n", ns_get32(cp));
490 * Function logic borrowed & modified from musl libc, res_msend.c
491 * G.query_count is always > 0.
493 static int send_queries(struct ns *ns)
495 unsigned char reply[512];
497 len_and_sockaddr *local_lsa;
499 int servfail_retry = 0;
502 unsigned retry_interval;
503 unsigned timeout = G.default_timeout * 1000;
504 unsigned tstart, tsent, tcur;
507 pfd.fd = xsocket_type(&local_lsa, ns->lsa->u.sa.sa_family, SOCK_DGRAM);
509 * local_lsa has "null" address and port 0 now.
510 * bind() ensures we have a *particular port* selected by kernel
511 * and remembered in fd, thus later recv(fd)
512 * receives only packets sent to this port.
514 xbind(pfd.fd, &local_lsa->u.sa, local_lsa->len);
516 /* Make read/writes know the destination */
517 xconnect(pfd.fd, &ns->lsa->u.sa, ns->lsa->len);
520 retry_interval = timeout / G.default_retry;
521 tstart = tcur = monotonic_ms();
524 while (tcur - tstart < timeout) {
528 if (tcur - tsent >= retry_interval) {
530 for (qn = 0; qn < G.query_count; qn++) {
531 if (G.query[qn].qlen == 0)
532 continue; /* this one was replied already */
534 if (write(pfd.fd, G.query[qn].query, G.query[qn].qlen) < 0) {
535 bb_perror_msg("write to '%s'", ns->name);
536 n_replies = -1; /* "no go, try next server" */
539 dbg("query %u sent\n", qn);
542 servfail_retry = 2 * G.query_count;
545 /* Wait for a response, or until time to retry */
546 if (poll(&pfd, 1, retry_interval - (tcur - tsent)) <= 0)
549 recvlen = read(pfd.fd, reply, sizeof(reply));
551 bb_perror_msg("read");
553 tcur = monotonic_ms();
557 if (ns->replies++ == 0) {
558 printf("Server:\t\t%s\n", ns->name);
559 printf("Address:\t%s\n\n",
560 auto_string(xmalloc_sockaddr2dotted(&ns->lsa->u.sa))
562 /* In "Address", bind-utils-9.11.3 show port after a hash: "1.2.3.4#53" */
563 /* Should we do the same? */
566 /* Non-identifiable packet */
568 dbg("read is too short:%d\n", recvlen);
572 /* Find which query this answer goes with, if any */
576 if (memcmp(reply, G.query[qn].query, 2) == 0) {
577 dbg("response matches query %u\n", qn);
580 if (++qn >= G.query_count) {
581 dbg("response does not match any query\n");
586 if (G.query[qn].qlen == 0) {
587 dbg("dropped duplicate response to query %u\n", qn);
591 rcode = reply[3] & 0x0f;
592 dbg("query %u rcode:%s\n", qn, rcodes[rcode]);
594 /* Retry immediately on SERVFAIL */
597 if (servfail_retry) {
599 write(pfd.fd, G.query[qn].query, G.query[qn].qlen);
600 dbg("query %u resent\n", qn);
606 G.query[qn].qlen = 0; /* flag: "reply received" */
607 tcur = monotonic_ms();
609 if (option_mask32 & OPT_debug) {
610 printf("Query #%d completed in %ums:\n", qn, tcur - tstart);
613 printf("** server can't find %s: %s\n",
614 G.query[qn].name, rcodes[rcode]);
616 if (parse_reply(reply, recvlen) < 0)
617 printf("*** Can't find %s: Parse error\n", G.query[qn].name);
621 if (n_replies >= G.query_count)
624 //used to store replies and process them later
625 G.query[qn].latency = tcur - tstart;
627 if (qn != save_idx) {
628 /* "wrong" receive buffer, move to correct one */
629 memcpy(G.query[qn].reply, G.query[save_idx].reply, recvlen);
632 /* G.query[0..save_idx] have replies, move to next one, if exists */
635 if (save_idx >= G.query_count)
636 goto ret; /* all are full: we have all results */
637 if (!G.query[save_idx].rlen)
638 break; /* this one is empty */
649 static void add_ns(const char *addr)
654 dbg("%s: addr:'%s'\n", __func__, addr);
656 count = G.serv_count++;
658 G.server = xrealloc_vector(G.server, /*8=2^3:*/ 3, count);
659 ns = &G.server[count];
661 ns->lsa = xhost2sockaddr(addr, G.default_port);
662 /*ns->replies = 0; - already is */
663 /*ns->failures = 0; - already is */
666 static void parse_resolvconf(void)
670 resolv = fopen("/etc/resolv.conf", "r");
672 char line[512]; /* "search" is defined to be up to 256 chars */
674 while (fgets(line, sizeof(line), resolv)) {
677 p = strtok(line, " \t\n");
680 dbg("resolv_key:'%s'\n", p);
681 arg = strtok(NULL, "\n");
682 dbg("resolv_arg:'%s'\n", arg);
686 if (strcmp(p, "domain") == 0) {
688 if (!G.have_search_directive)
692 if (strcmp(p, "search") == 0) {
693 /* search DOM1 DOM2... */
694 G.have_search_directive = 1;
697 G.search = xstrdup(arg);
698 dbg("search='%s'\n", G.search);
702 if (strcmp(p, "nameserver") != 0)
706 add_ns(xstrdup(arg));
713 /* default search domain is domain part of hostname */
714 char *h = safe_gethostname();
715 char *d = strchr(h, '.');
718 dbg("search='%s' (from hostname)\n", G.search);
723 /* Cater for case of "domain ." in resolv.conf */
724 if (G.search && LONE_CHAR(G.search, '.'))
728 static void add_query(int type, const char *dname)
734 count = G.query_count++;
736 G.query = xrealloc_vector(G.query, /*4=2^2:*/ 2, count);
737 new_q = &G.query[count];
739 dbg("new query#%u type %u for '%s'\n", count, type, dname);
742 qlen = res_mkquery(QUERY, dname, C_IN, type,
743 /*data:*/ NULL, /*datalen:*/ 0,
745 new_q->query, sizeof(new_q->query)
750 static void add_query_with_search(int type, const char *dname)
754 if (type == T_PTR || !G.search || strchr(dname, '.')) {
755 add_query(type, dname);
763 e = skip_non_whitespace(s);
764 fullname = xasprintf("%s.%.*s", dname, (int)(e - s), s);
765 add_query(type, fullname);
766 s = skip_whitespace(e);
772 static char *make_ptr(const char *addrstr)
774 unsigned char addr[16];
776 #if ENABLE_FEATURE_IPV6
777 if (inet_pton(AF_INET6, addrstr, addr)) {
778 if (memcmp(addr, v4_mapped, 12) != 0) {
782 for (i = 0; i < 16; i++) {
783 *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] & 0xf];
785 *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] >> 4];
788 strcpy(ptr, "ip6.arpa");
789 return xstrdup(resbuf);
791 return xasprintf("%u.%u.%u.%u.in-addr.arpa",
792 addr[15], addr[14], addr[13], addr[12]);
796 if (inet_pton(AF_INET, addrstr, addr)) {
797 return xasprintf("%u.%u.%u.%u.in-addr.arpa",
798 addr[3], addr[2], addr[1], addr[0]);
804 int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
805 int nslookup_main(int argc UNUSED_PARAM, char **argv)
813 /* manpage: "Options can also be specified on the command line
814 * if they precede the arguments and are prefixed with a hyphen."
819 const char *options =
820 // bind-utils-9.11.3 accept these:
822 // type= ty= querytype= query= qu= q=
843 // ver (prints version and exits)
845 "querytype\0" /* 1 */
849 "t\0" /* disambiguate with "type": else -t=2 fails */
858 if (argv[0][0] != '-')
861 /* Separate out "=val" part */
863 val = strchrnul(arg, '=');
867 i = index_in_substrings(options, arg);
868 //bb_error_msg("i:%d arg:'%s' val:'%s'", i, arg, val);
874 if (i == ARRAY_SIZE(qtypes))
875 bb_error_msg_and_die("invalid query type \"%s\"", val);
876 if (strcasecmp(qtypes[i].name, val) == 0)
883 G.default_port = xatou_range(val, 1, 0xffff);
886 G.default_retry = xatou_range(val, 1, INT_MAX);
889 option_mask32 |= OPT_debug;
892 G.default_timeout = xatou_range(val, 1, INT_MAX / 1000);
896 /* Use given DNS server if present */
903 /* Fall back to localhost if we could not find NS in resolv.conf */
904 if (G.serv_count == 0)
909 /* No explicit type given, guess query type.
910 * If we can convert the domain argument into a ptr (means that
911 * inet_pton() could read it) we assume a PTR request, else
912 * we issue A+AAAA queries and switch to an output format
913 * mimicking the one of the traditional nslookup applet.
917 ptr = make_ptr(argv[0]);
919 add_query(T_PTR, ptr);
921 add_query_with_search(T_A, argv[0]);
922 #if ENABLE_FEATURE_IPV6
923 add_query_with_search(T_AAAA, argv[0]);
928 for (c = 0; c < ARRAY_SIZE(qtypes); c++) {
929 if (types & (1 << c))
930 add_query_with_search(qtypes[c].type, argv[0]);
934 for (rc = 0; rc < G.serv_count;) {
937 c = send_queries(&G.server[rc]);
939 /* more than zero replies received */
940 #if 0 /* which version does this? */
941 if (option_mask32 & OPT_debug) {
942 printf("Replies:\t%d\n", G.server[rc].replies);
943 printf("Failures:\t%d\n\n", G.server[rc].failures);
947 //FIXME: we "break" even though some queries may still be not answered, and other servers may know them?
949 /* c = 0: timed out waiting for replies */
950 /* c < 0: error (message already printed) */
952 if (rc >= G.serv_count) {
954 // NB: bind-utils-9.11.3 behavior (all to stdout, not stderr):
956 // $ nslookup gmail.com 8.8.8.8
957 // ;; connection timed out; no servers could be reached
960 // $ nslookup -vc gmail.com 8.8.8.8; echo EXITCODE:$?
962 // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
964 // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
966 // ;; connection timed out; no servers could be reached
967 // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
971 printf(";; connection timed out; no servers could be reached\n\n");
977 for (rc = 0; rc < G.query_count; rc++) {
978 if (G.query[rc].qlen) {
979 printf("*** Can't find %s: No answer\n", G.query[rc].name);
983 if (err) /* should this affect exicode too? */
986 if (ENABLE_FEATURE_CLEAN_UP) {