grep: add proper support for pattern_list
[oweals/busybox.git] / networking / nslookup.c
1 /* vi: set sw=4 ts=4: */
2
3 //config:config NSLOOKUP
4 //config:       bool "nslookup (9.7 kb)"
5 //config:       default y
6 //config:       help
7 //config:       nslookup is a tool to query Internet name servers.
8 //config:
9 //config:config FEATURE_NSLOOKUP_BIG
10 //config:       bool "Use internal resolver code instead of libc"
11 //config:       depends on NSLOOKUP
12 //config:       default y
13 //config:
14 //config:config FEATURE_NSLOOKUP_LONG_OPTIONS
15 //config:       bool "Enable long options"
16 //config:       default y
17 //config:       depends on FEATURE_NSLOOKUP_BIG && LONG_OPTS
18
19 //applet:IF_NSLOOKUP(APPLET(nslookup, BB_DIR_USR_BIN, BB_SUID_DROP))
20
21 //kbuild:lib-$(CONFIG_NSLOOKUP) += nslookup.o
22
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"
33 //usage:       "\n"
34 //usage:       "Name:       debian\n"
35 //usage:       "Address:    127.0.0.1\n"
36
37 #include <resolv.h>
38 #include <net/if.h>     /* for IFNAMSIZ */
39 //#include <arpa/inet.h>
40 //#include <netdb.h>
41 #include "libbb.h"
42 #include "common_bufsiz.h"
43
44
45 #if !ENABLE_FEATURE_NSLOOKUP_BIG
46
47 /*
48  * Mini nslookup implementation for busybox
49  *
50  * Copyright (C) 1999,2000 by Lineo, inc. and John Beppu
51  * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
52  *
53  * Correct default name server display and explicit name server option
54  * added by Ben Zeckel <bzeckel@hmc.edu> June 2001
55  *
56  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
57  */
58
59 /*
60  * I'm only implementing non-interactive mode;
61  * I totally forgot nslookup even had an interactive mode.
62  *
63  * This applet is the only user of res_init(). Without it,
64  * you may avoid pulling in _res global from libc.
65  */
66
67 /* Examples of 'standard' nslookup output
68  * $ nslookup yahoo.com
69  * Server:         128.193.0.10
70  * Address:        128.193.0.10#53
71  *
72  * Non-authoritative answer:
73  * Name:   yahoo.com
74  * Address: 216.109.112.135
75  * Name:   yahoo.com
76  * Address: 66.94.234.13
77  *
78  * $ nslookup 204.152.191.37
79  * Server:         128.193.4.20
80  * Address:        128.193.4.20#53
81  *
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.
85  *
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
93  */
94
95 static int print_host(const char *hostname, const char *header)
96 {
97         /* We can't use xhost2sockaddr() - we want to get ALL addresses,
98          * not just one */
99         struct addrinfo *result = NULL;
100         int rc;
101         struct addrinfo hint;
102
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);
110
111         if (rc == 0) {
112                 struct addrinfo *cur = result;
113                 unsigned cnt = 0;
114
115                 printf("%-10s %s\n", header, hostname);
116                 // puts(cur->ai_canonname); ?
117                 while (cur) {
118                         char *dotted, *revhost;
119                         dotted = xmalloc_sockaddr2dotted_noport(cur->ai_addr);
120                         revhost = xmalloc_sockaddr2hostonly_noport(cur->ai_addr);
121
122                         printf("Address %u: %s%c", ++cnt, dotted, revhost ? ' ' : '\n');
123                         if (revhost) {
124                                 puts(revhost);
125                                 if (ENABLE_FEATURE_CLEAN_UP)
126                                         free(revhost);
127                         }
128                         if (ENABLE_FEATURE_CLEAN_UP)
129                                 free(dotted);
130                         cur = cur->ai_next;
131                 }
132         } else {
133 #if ENABLE_VERBOSE_RESOLUTION_ERRORS
134                 bb_error_msg("can't resolve '%s': %s", hostname, gai_strerror(rc));
135 #else
136                 bb_error_msg("can't resolve '%s'", hostname);
137 #endif
138         }
139         if (ENABLE_FEATURE_CLEAN_UP && result)
140                 freeaddrinfo(result);
141         return (rc != 0);
142 }
143
144 /* lookup the default nameserver and display it */
145 static void server_print(void)
146 {
147         char *server;
148         struct sockaddr *sa;
149
150 #if ENABLE_FEATURE_IPV6
151         sa = (struct sockaddr*)_res._u._ext.nsaddrs[0];
152         if (!sa)
153 #endif
154                 sa = (struct sockaddr*)&_res.nsaddr_list[0];
155         server = xmalloc_sockaddr2dotted_noport(sa);
156
157         print_host(server, "Server:");
158         if (ENABLE_FEATURE_CLEAN_UP)
159                 free(server);
160         bb_putchar('\n');
161 }
162
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)
166 {
167         len_and_sockaddr *lsa;
168
169         if (!server)
170                 return;
171
172         /* NB: this works even with, say, "[::1]:5353"! :) */
173         lsa = xhost2sockaddr(server, 53);
174
175         if (lsa->u.sa.sa_family == AF_INET) {
176                 _res.nscount = 1;
177                 /* struct copy */
178                 _res.nsaddr_list[0] = lsa->u.sin;
179         }
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):
188                 //_res.nscount = 0;
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)! */
193         }
194 #endif
195 }
196
197 int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
198 int nslookup_main(int argc, char **argv)
199 {
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)
206                 bb_show_usage();
207
208         /* initialize DNS structure _res used in printing the default
209          * name server and in the explicit name server option feature. */
210         res_init();
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;*/
214
215         set_default_dns(argv[2]);
216
217         server_print();
218
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).
224          */
225         set_default_dns(argv[2]);
226
227         return print_host(argv[1], "Name:");
228 }
229
230
231 #else /****** A version from LEDE / OpenWRT ******/
232
233 /*
234  * musl compatible nslookup
235  *
236  * Copyright (C) 2017 Jo-Philipp Wich <jo@mein.io>
237  *
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.
241  *
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.
249  */
250
251 #if 0
252 # define dbg(...) fprintf(stderr, __VA_ARGS__)
253 #else
254 # define dbg(...) ((void)0)
255 #endif
256
257 struct ns {
258         const char *name;
259         len_and_sockaddr *lsa;
260         //UNUSED: int failures;
261         int replies;
262 };
263
264 struct query {
265         const char *name;
266         unsigned qlen;
267 //      unsigned latency;
268 //      uint8_t rcode;
269         unsigned char query[512];
270 //      unsigned char reply[512];
271 };
272
273 static const struct {
274         unsigned char type;
275         char name[7];
276 } qtypes[] = {
277         { ns_t_soa,   "SOA"   },
278         { ns_t_ns,    "NS"    },
279         { ns_t_a,     "A"     },
280 #if ENABLE_FEATURE_IPV6
281         { ns_t_aaaa,  "AAAA"  },
282 #endif
283         { ns_t_cname, "CNAME" },
284         { ns_t_mx,    "MX"    },
285         { ns_t_txt,   "TXT"   },
286         { ns_t_srv,   "SRV"   },
287         { ns_t_ptr,   "PTR"   },
288         { ns_t_any,   "ANY"   },
289 };
290
291 static const char *const rcodes[] = {
292         "NOERROR",    // 0
293         "FORMERR",    // 1
294         "SERVFAIL",   // 2
295         "NXDOMAIN",   // 3
296         "NOTIMP",     // 4
297         "REFUSED",    // 5
298         "YXDOMAIN",   // 6
299         "YXRRSET",    // 7
300         "NXRRSET",    // 8
301         "NOTAUTH",    // 9
302         "NOTZONE",    // 10
303         "11",         // 11 not assigned
304         "12",         // 12 not assigned
305         "13",         // 13 not assigned
306         "14",         // 14 not assigned
307         "15",         // 15 not assigned
308 };
309
310 #if ENABLE_FEATURE_IPV6
311 static const char v4_mapped[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xff,0xff };
312 #endif
313
314 struct globals {
315         unsigned default_port;
316         unsigned default_retry;
317         unsigned default_timeout;
318         unsigned query_count;
319         unsigned serv_count;
320         struct ns *server;
321         struct query *query;
322         char *search;
323         smalluint have_search_directive;
324         smalluint exitcode;
325 } FIX_ALIASING;
326 #define G (*(struct globals*)bb_common_bufsiz1)
327 #define INIT_G() do { \
328         setup_common_bufsiz(); \
329         G.default_port = 53; \
330         G.default_retry = 2; \
331         G.default_timeout = 5; \
332 } while (0)
333
334 enum {
335         OPT_debug = (1 << 0),
336 };
337
338 static int parse_reply(const unsigned char *msg, size_t len)
339 {
340         HEADER *header;
341
342         ns_msg handle;
343         ns_rr rr;
344         int i, n, rdlen;
345         const char *format = NULL;
346         char astr[INET6_ADDRSTRLEN], dname[MAXDNAME];
347         const unsigned char *cp;
348
349         header = (HEADER *)msg;
350         if (!header->aa)
351                 printf("Non-authoritative answer:\n");
352
353         if (ns_initparse(msg, len, &handle) != 0) {
354                 //printf("Unable to parse reply: %s\n", strerror(errno));
355                 return -1;
356         }
357
358         for (i = 0; i < ns_msg_count(handle, ns_s_an); i++) {
359                 if (ns_parserr(&handle, ns_s_an, i, &rr) != 0) {
360                         //printf("Unable to parse resource record: %s\n", strerror(errno));
361                         return -1;
362                 }
363
364                 rdlen = ns_rr_rdlen(rr);
365
366                 switch (ns_rr_type(rr))
367                 {
368                 case ns_t_a:
369                         if (rdlen != 4) {
370                                 dbg("unexpected A record length %d\n", rdlen);
371                                 return -1;
372                         }
373                         inet_ntop(AF_INET, ns_rr_rdata(rr), astr, sizeof(astr));
374                         printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
375                         break;
376
377 #if ENABLE_FEATURE_IPV6
378                 case ns_t_aaaa:
379                         if (rdlen != 16) {
380                                 dbg("unexpected AAAA record length %d\n", rdlen);
381                                 return -1;
382                         }
383                         inet_ntop(AF_INET6, ns_rr_rdata(rr), astr, sizeof(astr));
384                         /* bind-utils-9.11.3 uses the same format for A and AAAA answers */
385                         printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
386                         break;
387 #endif
388
389                 case ns_t_ns:
390                         if (!format)
391                                 format = "%s\tnameserver = %s\n";
392                         /* fall through */
393
394                 case ns_t_cname:
395                         if (!format)
396                                 format = "%s\tcanonical name = %s\n";
397                         /* fall through */
398
399                 case ns_t_ptr:
400                         if (!format)
401                                 format = "%s\tname = %s\n";
402                         if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
403                                         ns_rr_rdata(rr), dname, sizeof(dname)) < 0
404                         ) {
405                                 //printf("Unable to uncompress domain: %s\n", strerror(errno));
406                                 return -1;
407                         }
408                         printf(format, ns_rr_name(rr), dname);
409                         break;
410
411                 case ns_t_mx:
412                         if (rdlen < 2) {
413                                 printf("MX record too short\n");
414                                 return -1;
415                         }
416                         n = ns_get16(ns_rr_rdata(rr));
417                         if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
418                                         ns_rr_rdata(rr) + 2, dname, sizeof(dname)) < 0
419                         ) {
420                                 //printf("Cannot uncompress MX domain: %s\n", strerror(errno));
421                                 return -1;
422                         }
423                         printf("%s\tmail exchanger = %d %s\n", ns_rr_name(rr), n, dname);
424                         break;
425
426                 case ns_t_txt:
427                         if (rdlen < 1) {
428                                 //printf("TXT record too short\n");
429                                 return -1;
430                         }
431                         n = *(unsigned char *)ns_rr_rdata(rr);
432                         if (n > 0) {
433                                 memset(dname, 0, sizeof(dname));
434                                 memcpy(dname, ns_rr_rdata(rr) + 1, n);
435                                 printf("%s\ttext = \"%s\"\n", ns_rr_name(rr), dname);
436                         }
437                         break;
438
439                 case ns_t_srv:
440                         if (rdlen < 6) {
441                                 //printf("SRV record too short\n");
442                                 return -1;
443                         }
444
445                         cp = ns_rr_rdata(rr);
446                         n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
447                                                cp + 6, dname, sizeof(dname));
448
449                         if (n < 0) {
450                                 //printf("Unable to uncompress domain: %s\n", strerror(errno));
451                                 return -1;
452                         }
453
454                         printf("%s\tservice = %u %u %u %s\n", ns_rr_name(rr),
455                                 ns_get16(cp), ns_get16(cp + 2), ns_get16(cp + 4), dname);
456                         break;
457
458                 case ns_t_soa:
459                         if (rdlen < 20) {
460                                 dbg("SOA record too short:%d\n", rdlen);
461                                 return -1;
462                         }
463
464                         printf("%s\n", ns_rr_name(rr));
465
466                         cp = ns_rr_rdata(rr);
467                         n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
468                                                cp, dname, sizeof(dname));
469                         if (n < 0) {
470                                 //printf("Unable to uncompress domain: %s\n", strerror(errno));
471                                 return -1;
472                         }
473
474                         printf("\torigin = %s\n", dname);
475                         cp += n;
476
477                         n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
478                                                cp, dname, sizeof(dname));
479                         if (n < 0) {
480                                 //printf("Unable to uncompress domain: %s\n", strerror(errno));
481                                 return -1;
482                         }
483
484                         printf("\tmail addr = %s\n", dname);
485                         cp += n;
486
487                         printf("\tserial = %lu\n", ns_get32(cp));
488                         cp += 4;
489
490                         printf("\trefresh = %lu\n", ns_get32(cp));
491                         cp += 4;
492
493                         printf("\tretry = %lu\n", ns_get32(cp));
494                         cp += 4;
495
496                         printf("\texpire = %lu\n", ns_get32(cp));
497                         cp += 4;
498
499                         printf("\tminimum = %lu\n", ns_get32(cp));
500                         break;
501
502                 default:
503                         break;
504                 }
505         }
506
507         return i;
508 }
509
510 /*
511  * Function logic borrowed & modified from musl libc, res_msend.c
512  * G.query_count is always > 0.
513  */
514 static int send_queries(struct ns *ns)
515 {
516         unsigned char reply[512];
517         uint8_t rcode;
518         len_and_sockaddr *local_lsa;
519         struct pollfd pfd;
520         int servfail_retry = 0;
521         int n_replies = 0;
522 //      int save_idx = 0;
523         unsigned retry_interval;
524         unsigned timeout = G.default_timeout * 1000;
525         unsigned tstart, tsent, tcur;
526
527         pfd.events = POLLIN;
528         pfd.fd = xsocket_type(&local_lsa, ns->lsa->u.sa.sa_family, SOCK_DGRAM);
529         /*
530          * local_lsa has "null" address and port 0 now.
531          * bind() ensures we have a *particular port* selected by kernel
532          * and remembered in fd, thus later recv(fd)
533          * receives only packets sent to this port.
534          */
535         xbind(pfd.fd, &local_lsa->u.sa, local_lsa->len);
536         free(local_lsa);
537         /* Make read/writes know the destination */
538         xconnect(pfd.fd, &ns->lsa->u.sa, ns->lsa->len);
539         ndelay_on(pfd.fd);
540
541         retry_interval = timeout / G.default_retry;
542         tstart = tcur = monotonic_ms();
543         goto send;
544
545         while (tcur - tstart < timeout) {
546                 int qn;
547                 int recvlen;
548
549                 if (tcur - tsent >= retry_interval) {
550  send:
551                         for (qn = 0; qn < G.query_count; qn++) {
552                                 if (G.query[qn].qlen == 0)
553                                         continue; /* this one was replied already */
554
555                                 if (write(pfd.fd, G.query[qn].query, G.query[qn].qlen) < 0) {
556                                         bb_perror_msg("write to '%s'", ns->name);
557                                         n_replies = -1; /* "no go, try next server" */
558                                         goto ret;
559                                 }
560                                 dbg("query %u sent\n", qn);
561                         }
562                         tsent = tcur;
563                         servfail_retry = 2 * G.query_count;
564                 }
565
566                 /* Wait for a response, or until time to retry */
567                 if (poll(&pfd, 1, retry_interval - (tcur - tsent)) <= 0)
568                         goto next;
569
570                 recvlen = read(pfd.fd, reply, sizeof(reply));
571                 if (recvlen < 0) {
572                         bb_simple_perror_msg("read");
573  next:
574                         tcur = monotonic_ms();
575                         continue;
576                 }
577
578                 if (ns->replies++ == 0) {
579                         printf("Server:\t\t%s\n", ns->name);
580                         printf("Address:\t%s\n\n",
581                                 auto_string(xmalloc_sockaddr2dotted(&ns->lsa->u.sa))
582                         );
583                         /* In "Address", bind-utils-9.11.3 show port after a hash: "1.2.3.4#53" */
584                         /* Should we do the same? */
585                 }
586
587                 /* Non-identifiable packet */
588                 if (recvlen < 4) {
589                         dbg("read is too short:%d\n", recvlen);
590                         goto next;
591                 }
592
593                 /* Find which query this answer goes with, if any */
594 //              qn = save_idx;
595                 qn = 0;
596                 for (;;) {
597                         if (memcmp(reply, G.query[qn].query, 2) == 0) {
598                                 dbg("response matches query %u\n", qn);
599                                 break;
600                         }
601                         if (++qn >= G.query_count) {
602                                 dbg("response does not match any query\n");
603                                 goto next;
604                         }
605                 }
606
607                 if (G.query[qn].qlen == 0) {
608                         dbg("dropped duplicate response to query %u\n", qn);
609                         goto next;
610                 }
611
612                 rcode = reply[3] & 0x0f;
613                 dbg("query %u rcode:%s\n", qn, rcodes[rcode]);
614
615                 /* Retry immediately on SERVFAIL */
616                 if (rcode == 2) {
617                         //UNUSED: ns->failures++;
618                         if (servfail_retry) {
619                                 servfail_retry--;
620                                 write(pfd.fd, G.query[qn].query, G.query[qn].qlen);
621                                 dbg("query %u resent\n", qn);
622                                 goto next;
623                         }
624                 }
625
626                 /* Process reply */
627                 G.query[qn].qlen = 0; /* flag: "reply received" */
628                 tcur = monotonic_ms();
629 #if 1
630                 if (option_mask32 & OPT_debug) {
631                         printf("Query #%d completed in %ums:\n", qn, tcur - tstart);
632                 }
633                 if (rcode != 0) {
634                         printf("** server can't find %s: %s\n",
635                                         G.query[qn].name, rcodes[rcode]);
636                         G.exitcode = EXIT_FAILURE;
637                 } else {
638                         switch (parse_reply(reply, recvlen)) {
639                         case -1:
640                                 printf("*** Can't find %s: Parse error\n", G.query[qn].name);
641                                 G.exitcode = EXIT_FAILURE;
642                                 break;
643
644                         case 0:
645                                 printf("*** Can't find %s: No answer\n", G.query[qn].name);
646                                 break;
647                         }
648                 }
649                 bb_putchar('\n');
650                 n_replies++;
651                 if (n_replies >= G.query_count)
652                         goto ret;
653 #else
654 //used to store replies and process them later
655                 G.query[qn].latency = tcur - tstart;
656                 n_replies++;
657                 if (qn != save_idx) {
658                         /* "wrong" receive buffer, move to correct one */
659                         memcpy(G.query[qn].reply, G.query[save_idx].reply, recvlen);
660                         continue;
661                 }
662                 /* G.query[0..save_idx] have replies, move to next one, if exists */
663                 for (;;) {
664                         save_idx++;
665                         if (save_idx >= G.query_count)
666                                 goto ret; /* all are full: we have all results */
667                         if (!G.query[save_idx].rlen)
668                                 break; /* this one is empty */
669                 }
670 #endif
671         } /* while() */
672
673  ret:
674         close(pfd.fd);
675
676         return n_replies;
677 }
678
679 static void add_ns(const char *addr)
680 {
681         struct ns *ns;
682         unsigned count;
683
684         dbg("%s: addr:'%s'\n", __func__, addr);
685
686         count = G.serv_count++;
687
688         G.server = xrealloc_vector(G.server, /*8=2^3:*/ 3, count);
689         ns = &G.server[count];
690         ns->name = addr;
691         ns->lsa = xhost2sockaddr(addr, G.default_port);
692         /*ns->replies = 0; - already is */
693         /*ns->failures = 0; - already is */
694 }
695
696 static void parse_resolvconf(void)
697 {
698         FILE *resolv;
699
700         resolv = fopen("/etc/resolv.conf", "r");
701         if (resolv) {
702                 char line[512]; /* "search" is defined to be up to 256 chars */
703
704                 while (fgets(line, sizeof(line), resolv)) {
705                         char *p, *arg;
706
707                         p = strtok(line, " \t\n");
708                         if (!p)
709                                 continue;
710                         dbg("resolv_key:'%s'\n", p);
711                         arg = strtok(NULL, "\n");
712                         dbg("resolv_arg:'%s'\n", arg);
713                         if (!arg)
714                                 continue;
715
716                         if (strcmp(p, "domain") == 0) {
717                                 /* domain DOM */
718                                 if (!G.have_search_directive)
719                                         goto set_search;
720                                 continue;
721                         }
722                         if (strcmp(p, "search") == 0) {
723                                 /* search DOM1 DOM2... */
724                                 G.have_search_directive = 1;
725  set_search:
726                                 free(G.search);
727                                 G.search = xstrdup(arg);
728                                 dbg("search='%s'\n", G.search);
729                                 continue;
730                         }
731
732                         if (strcmp(p, "nameserver") != 0)
733                                 continue;
734
735                         /* nameserver DNS */
736                         add_ns(xstrdup(arg));
737                 }
738
739                 fclose(resolv);
740         }
741
742         if (!G.search) {
743                 /* default search domain is domain part of hostname */
744                 char *h = safe_gethostname();
745                 char *d = strchr(h, '.');
746                 if (d) {
747                         G.search = d + 1;
748                         dbg("search='%s' (from hostname)\n", G.search);
749                 }
750                 /* else free(h); */
751         }
752
753         /* Cater for case of "domain ." in resolv.conf */
754         if (G.search && LONE_CHAR(G.search, '.'))
755                 G.search = NULL;
756 }
757
758 static void add_query(int type, const char *dname)
759 {
760         struct query *new_q;
761         unsigned count;
762         ssize_t qlen;
763
764         count = G.query_count++;
765
766         G.query = xrealloc_vector(G.query, /*4=2^2:*/ 2, count);
767         new_q = &G.query[count];
768
769         dbg("new query#%u type %u for '%s'\n", count, type, dname);
770         new_q->name = dname;
771
772         qlen = res_mkquery(QUERY, dname, C_IN, type,
773                         /*data:*/ NULL, /*datalen:*/ 0,
774                         /*newrr:*/ NULL,
775                         new_q->query, sizeof(new_q->query)
776         );
777         new_q->qlen = qlen;
778 }
779
780 static void add_query_with_search(int type, const char *dname)
781 {
782         char *s;
783
784         if (type == T_PTR || !G.search || strchr(dname, '.')) {
785                 add_query(type, dname);
786                 return;
787         }
788
789         s = G.search;
790         for (;;) {
791                 char *fullname, *e;
792
793                 e = skip_non_whitespace(s);
794                 fullname = xasprintf("%s.%.*s", dname, (int)(e - s), s);
795                 add_query(type, fullname);
796                 s = skip_whitespace(e);
797                 if (!*s)
798                         break;
799         }
800 }
801
802 static char *make_ptr(const char *addrstr)
803 {
804         unsigned char addr[16];
805
806 #if ENABLE_FEATURE_IPV6
807         if (inet_pton(AF_INET6, addrstr, addr)) {
808                 if (memcmp(addr, v4_mapped, 12) != 0) {
809                         int i;
810                         char resbuf[80];
811                         char *ptr = resbuf;
812                         for (i = 0; i < 16; i++) {
813                                 *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] & 0xf];
814                                 *ptr++ = '.';
815                                 *ptr++ = 0x20 | bb_hexdigits_upcase[(unsigned char)addr[15 - i] >> 4];
816                                 *ptr++ = '.';
817                         }
818                         strcpy(ptr, "ip6.arpa");
819                         return xstrdup(resbuf);
820                 }
821                 return xasprintf("%u.%u.%u.%u.in-addr.arpa",
822                                 addr[15], addr[14], addr[13], addr[12]);
823         }
824 #endif
825
826         if (inet_pton(AF_INET, addrstr, addr)) {
827                 return xasprintf("%u.%u.%u.%u.in-addr.arpa",
828                         addr[3], addr[2], addr[1], addr[0]);
829         }
830
831         return NULL;
832 }
833
834 int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
835 int nslookup_main(int argc UNUSED_PARAM, char **argv)
836 {
837         unsigned types;
838         int rc;
839         int err;
840
841         INIT_G();
842
843         /* manpage: "Options can also be specified on the command line
844          * if they precede the arguments and are prefixed with a hyphen."
845          */
846         types = 0;
847         argv++;
848         for (;;) {
849                 const char *options =
850 // bind-utils-9.11.3 accept these:
851 // class=   cl=
852 // type=    ty= querytype= query= qu= q=
853 // domain=  do=
854 // port=    po=
855 // timeout= t=
856 // retry=   ret=
857 // ndots=
858 // recurse
859 // norecurse
860 // defname
861 // nodefname
862 // vc
863 // novc
864 // debug
865 // nodebug
866 // d2
867 // nod2
868 // search
869 // nosearch
870 // sil
871 // fail
872 // nofail
873 // ver (prints version and exits)
874                         "type\0"      /* 0 */
875                         "querytype\0" /* 1 */
876                         "port\0"      /* 2 */
877                         "retry\0"     /* 3 */
878                         "debug\0"     /* 4 */
879                         "t\0" /* disambiguate with "type": else -t=2 fails */
880                         "timeout\0"   /* 6 */
881                         "";
882                 int i;
883                 char *arg;
884                 char *val;
885
886                 if (!*argv)
887                         bb_show_usage();
888                 if (argv[0][0] != '-')
889                         break;
890
891                 /* Separate out "=val" part */
892                 arg = (*argv++) + 1;
893                 val = strchrnul(arg, '=');
894                 if (*val)
895                         *val++ = '\0';
896
897                 i = index_in_substrings(options, arg);
898                 //bb_error_msg("i:%d arg:'%s' val:'%s'", i, arg, val);
899                 if (i < 0)
900                         bb_show_usage();
901
902                 if (i <= 1) {
903                         for (i = 0;; i++) {
904                                 if (i == ARRAY_SIZE(qtypes))
905                                         bb_error_msg_and_die("invalid query type \"%s\"", val);
906                                 if (strcasecmp(qtypes[i].name, val) == 0)
907                                         break;
908                         }
909                         types |= (1 << i);
910                         continue;
911                 }
912                 if (i == 2) {
913                         G.default_port = xatou_range(val, 1, 0xffff);
914                 }
915                 if (i == 3) {
916                         G.default_retry = xatou_range(val, 1, INT_MAX);
917                 }
918                 if (i == 4) {
919                         option_mask32 |= OPT_debug;
920                 }
921                 if (i > 4) {
922                         G.default_timeout = xatou_range(val, 1, INT_MAX / 1000);
923                 }
924         }
925
926         /* Use given DNS server if present */
927         if (argv[1]) {
928                 if (argv[2])
929                         bb_show_usage();
930                 add_ns(argv[1]);
931         } else {
932                 parse_resolvconf();
933                 /* Fall back to localhost if we could not find NS in resolv.conf */
934                 if (G.serv_count == 0)
935                         add_ns("127.0.0.1");
936         }
937
938         if (types == 0) {
939                 /* No explicit type given, guess query type.
940                  * If we can convert the domain argument into a ptr (means that
941                  * inet_pton() could read it) we assume a PTR request, else
942                  * we issue A+AAAA queries and switch to an output format
943                  * mimicking the one of the traditional nslookup applet.
944                  */
945                 char *ptr;
946
947                 ptr = make_ptr(argv[0]);
948                 if (ptr) {
949                         add_query(T_PTR, ptr);
950                 } else {
951                         add_query_with_search(T_A, argv[0]);
952 #if ENABLE_FEATURE_IPV6
953                         add_query_with_search(T_AAAA, argv[0]);
954 #endif
955                 }
956         } else {
957                 int c;
958                 for (c = 0; c < ARRAY_SIZE(qtypes); c++) {
959                         if (types & (1 << c))
960                                 add_query_with_search(qtypes[c].type, argv[0]);
961                 }
962         }
963
964         for (rc = 0; rc < G.serv_count;) {
965                 int c;
966
967                 c = send_queries(&G.server[rc]);
968                 if (c > 0) {
969                         /* more than zero replies received */
970 #if 0 /* which version does this? */
971                         if (option_mask32 & OPT_debug) {
972                                 printf("Replies:\t%d\n", G.server[rc].replies);
973                                 printf("Failures:\t%d\n\n", G.server[rc].failures);
974                         }
975 #endif
976                         break;
977 //FIXME: we "break" even though some queries may still be not answered, and other servers may know them?
978                 }
979                 /* c = 0: timed out waiting for replies */
980                 /* c < 0: error (message already printed) */
981                 rc++;
982                 if (rc >= G.serv_count) {
983 //
984 // NB: bind-utils-9.11.3 behavior (all to stdout, not stderr):
985 //
986 // $ nslookup gmail.com 8.8.8.8
987 // ;; connection timed out; no servers could be reached
988 //
989 // Using TCP mode:
990 // $ nslookup -vc gmail.com 8.8.8.8; echo EXITCODE:$?
991 //     <~10 sec>
992 // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
993 //     <~10 sec>
994 // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
995 //     <~10 sec>
996 // ;; connection timed out; no servers could be reached
997 // ;; Connection to 8.8.8.8#53(8.8.8.8) for gmail.com failed: timed out.
998 //     <empty line>
999 // EXITCODE:1
1000 // $ _
1001                         printf(";; connection timed out; no servers could be reached\n\n");
1002                         return EXIT_FAILURE;
1003                 }
1004         }
1005
1006         err = 0;
1007         for (rc = 0; rc < G.query_count; rc++) {
1008                 if (G.query[rc].qlen) {
1009                         printf("*** Can't find %s: No answer\n", G.query[rc].name);
1010                         err = 1;
1011                 }
1012         }
1013         if (err) /* should this affect exicode too? */
1014                 bb_putchar('\n');
1015
1016         if (ENABLE_FEATURE_CLEAN_UP) {
1017                 free(G.server);
1018                 free(G.query);
1019         }
1020
1021         return G.exitcode;
1022 }
1023
1024 #endif