1 From 8c1440a0934dd8b3ad6aae48d6653b5ba6fce8a1 Mon Sep 17 00:00:00 2001
2 From: Jo-Philipp Wich <jo@mein.io>
3 Date: Tue, 14 Mar 2017 22:21:34 +0100
4 Subject: [PATCH] networking: add LEDE nslookup applet
6 Add a new LEDE nslookup applet which is compatible with musl libc
7 and providing more features like ability to specify query type.
9 In contrast to busybox' builtin nslookup applet, this variant does
10 not rely on libc resolver internals but uses explicit send logic
11 and the libresolv primitives to parse received DNS responses.
13 Signed-off-by: Jo-Philipp Wich <jo@mein.io>
15 networking/nslookup_lede.c | 869 +++++++++++++++++++++++++++++++++++++++++++++
16 2 files changed, 875 insertions(+)
17 create mode 100644 networking/nslookup_lede.c
19 diff --git a/networking/nslookup_lede.c b/networking/nslookup_lede.c
21 index 0000000..fe927ad
23 +++ b/networking/nslookup_lede.c
26 + * nslookup_lede - musl compatible replacement for busybox nslookup
28 + * Copyright (C) 2017 Jo-Philipp Wich <jo@mein.io>
30 + * Permission to use, copy, modify, and/or distribute this software for any
31 + * purpose with or without fee is hereby granted, provided that the above
32 + * copyright notice and this permission notice appear in all copies.
34 + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
35 + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
36 + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
37 + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
38 + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
39 + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
40 + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
43 +//config:config NSLOOKUP_LEDE
44 +//config: bool "nslookup_lede"
45 +//config: depends on !NSLOOKUP
48 +//config: nslookup is a tool to query Internet name servers (LEDE flavor).
50 +//config:config FEATURE_NSLOOKUP_LEDE_LONG_OPTIONS
51 +//config: bool "Enable long options"
53 +//config: depends on NSLOOKUP_LEDE && LONG_OPTS
55 +//config: Support long options for the nslookup applet.
57 +//applet:IF_NSLOOKUP_LEDE(APPLET(nslookup, BB_DIR_USR_BIN, BB_SUID_DROP))
59 +//kbuild:lib-$(CONFIG_NSLOOKUP_LEDE) += nslookup_lede.o
61 +//usage:#define nslookup_lede_trivial_usage
62 +//usage: "[HOST] [SERVER]"
63 +//usage:#define nslookup_lede_full_usage "\n\n"
64 +//usage: "Query the nameserver for the IP address of the given HOST\n"
65 +//usage: "optionally using a specified DNS server"
67 +//usage:#define nslookup_lede_example_usage
68 +//usage: "$ nslookup localhost\n"
69 +//usage: "Server: default\n"
70 +//usage: "Address: default\n"
72 +//usage: "Name: debian\n"
73 +//usage: "Address: 127.0.0.1\n"
83 +#include <sys/socket.h>
84 +#include <arpa/inet.h>
92 + len_and_sockaddr addr;
100 + unsigned char query[512], reply[512];
101 + unsigned long latency;
109 + { ns_t_soa, "SOA" },
112 + { ns_t_aaaa, "AAAA" },
113 + { ns_t_cname, "CNAME" },
115 + { ns_t_txt, "TXT" },
116 + { ns_t_ptr, "PTR" },
117 + { ns_t_any, "ANY" },
121 +static const char *rcodes[] = {
141 +static unsigned int default_port = 53;
142 +static unsigned int default_retry = 2;
143 +static unsigned int default_timeout = 5;
146 +static int parse_reply(const unsigned char *msg, size_t len)
151 + const char *format = NULL;
152 + char astr[INET6_ADDRSTRLEN], dname[MAXDNAME];
153 + const unsigned char *cp;
155 + if (ns_initparse(msg, len, &handle) != 0) {
156 + //fprintf(stderr, "Unable to parse reply: %s\n", strerror(errno));
160 + for (i = 0; i < ns_msg_count(handle, ns_s_an); i++) {
161 + if (ns_parserr(&handle, ns_s_an, i, &rr) != 0) {
162 + //fprintf(stderr, "Unable to parse resource record: %s\n", strerror(errno));
166 + rdlen = ns_rr_rdlen(rr);
168 + switch (ns_rr_type(rr))
172 + //fprintf(stderr, "Unexpected A record length\n");
175 + inet_ntop(AF_INET, ns_rr_rdata(rr), astr, sizeof(astr));
176 + printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
181 + //fprintf(stderr, "Unexpected AAAA record length\n");
184 + inet_ntop(AF_INET6, ns_rr_rdata(rr), astr, sizeof(astr));
185 + printf("%s\thas AAAA address %s\n", ns_rr_name(rr), astr);
190 + format = "%s\tnameserver = %s\n";
195 + format = "%s\tcanonical name = %s\n";
200 + format = "%s\tname = %s\n";
201 + if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
202 + ns_rr_rdata(rr), dname, sizeof(dname)) < 0) {
203 + //fprintf(stderr, "Unable to uncompress domain: %s\n", strerror(errno));
206 + printf(format, ns_rr_name(rr), dname);
211 + fprintf(stderr, "MX record too short\n");
214 + n = ns_get16(ns_rr_rdata(rr));
215 + if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
216 + ns_rr_rdata(rr) + 2, dname, sizeof(dname)) < 0) {
217 + //fprintf(stderr, "Cannot uncompress MX domain: %s\n", strerror(errno));
220 + printf("%s\tmail exchanger = %d %s\n", ns_rr_name(rr), n, dname);
225 + //fprintf(stderr, "TXT record too short\n");
228 + n = *(unsigned char *)ns_rr_rdata(rr);
230 + memset(dname, 0, sizeof(dname));
231 + memcpy(dname, ns_rr_rdata(rr) + 1, n);
232 + printf("%s\ttext = \"%s\"\n", ns_rr_name(rr), dname);
238 + //fprintf(stderr, "SOA record too short\n");
242 + printf("%s\n", ns_rr_name(rr));
244 + cp = ns_rr_rdata(rr);
245 + n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
246 + cp, dname, sizeof(dname));
249 + //fprintf(stderr, "Unable to uncompress domain: %s\n", strerror(errno));
253 + printf("\torigin = %s\n", dname);
256 + n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
257 + cp, dname, sizeof(dname));
260 + //fprintf(stderr, "Unable to uncompress domain: %s\n", strerror(errno));
264 + printf("\tmail addr = %s\n", dname);
267 + printf("\tserial = %lu\n", ns_get32(cp));
270 + printf("\trefresh = %lu\n", ns_get32(cp));
273 + printf("\tretry = %lu\n", ns_get32(cp));
276 + printf("\texpire = %lu\n", ns_get32(cp));
279 + printf("\tminimum = %lu\n", ns_get32(cp));
290 +static int parse_nsaddr(const char *addrstr, len_and_sockaddr *lsa)
292 + char *eptr, *hash, ifname[IFNAMSIZ];
293 + unsigned int port = default_port;
294 + unsigned int scope = 0;
296 + hash = strchr(addrstr, '#');
300 + port = strtoul(hash, &eptr, 10);
302 + if (eptr == hash || *eptr != '\0' || port > 65535) {
308 + hash = strchr(addrstr, '%');
311 + for (eptr = ++hash; *eptr != '\0' && *eptr != '#'; eptr++) {
312 + if ((eptr - hash) >= IFNAMSIZ) {
317 + ifname[eptr - hash] = *eptr;
320 + ifname[eptr - hash] = '\0';
321 + scope = if_nametoindex(ifname);
329 + if (inet_pton(AF_INET6, addrstr, &lsa->u.sin6.sin6_addr)) {
330 + lsa->u.sin6.sin6_family = AF_INET6;
331 + lsa->u.sin6.sin6_port = htons(port);
332 + lsa->u.sin6.sin6_scope_id = scope;
333 + lsa->len = sizeof(lsa->u.sin6);
337 + if (!scope && inet_pton(AF_INET, addrstr, &lsa->u.sin.sin_addr)) {
338 + lsa->u.sin.sin_family = AF_INET;
339 + lsa->u.sin.sin_port = htons(port);
340 + lsa->len = sizeof(lsa->u.sin);
348 +static char *make_ptr(const char *addrstr)
350 + const char *hexdigit = "0123456789abcdef";
351 + static char ptrstr[73];
352 + unsigned char addr[16];
353 + char *ptr = ptrstr;
356 + if (inet_pton(AF_INET6, addrstr, addr)) {
357 + if (memcmp(addr, "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12) != 0) {
358 + for (i = 0; i < 16; i++) {
359 + *ptr++ = hexdigit[(unsigned char)addr[15 - i] & 0xf];
361 + *ptr++ = hexdigit[(unsigned char)addr[15 - i] >> 4];
364 + strcpy(ptr, "ip6.arpa");
367 + sprintf(ptr, "%u.%u.%u.%u.in-addr.arpa",
368 + addr[15], addr[14], addr[13], addr[12]);
374 + if (inet_pton(AF_INET, addrstr, addr)) {
375 + sprintf(ptr, "%u.%u.%u.%u.in-addr.arpa",
376 + addr[3], addr[2], addr[1], addr[0]);
383 +static unsigned long mtime(void)
385 + struct timespec ts;
386 + clock_gettime(CLOCK_REALTIME, &ts);
387 + return (unsigned long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
390 +static void to_v4_mapped(len_and_sockaddr *a)
392 + if (a->u.sa.sa_family != AF_INET)
395 + memcpy(a->u.sin6.sin6_addr.s6_addr + 12,
396 + &a->u.sin.sin_addr, 4);
398 + memcpy(a->u.sin6.sin6_addr.s6_addr,
399 + "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
401 + a->u.sin6.sin6_family = AF_INET6;
402 + a->u.sin6.sin6_flowinfo = 0;
403 + a->u.sin6.sin6_scope_id = 0;
404 + a->len = sizeof(a->u.sin6);
409 + * Function logic borrowed & modified from musl libc, res_msend.c
412 +static int send_queries(struct ns *ns, int n_ns, struct query *queries, int n_queries)
415 + int timeout = default_timeout * 1000, retry_interval, servfail_retry = 0;
416 + len_and_sockaddr from = { };
421 + unsigned long t0, t1, t2;
422 + int nn, qn, next_query = 0;
424 + from.u.sa.sa_family = AF_INET;
425 + from.len = sizeof(from.u.sin);
427 + for (nn = 0; nn < n_ns; nn++) {
428 + if (ns[nn].addr.u.sa.sa_family == AF_INET6) {
429 + from.u.sa.sa_family = AF_INET6;
430 + from.len = sizeof(from.u.sin6);
435 + /* Get local address and open/bind a socket */
436 + fd = socket(from.u.sa.sa_family, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
438 + /* Handle case where system lacks IPv6 support */
439 + if (fd < 0 && from.u.sa.sa_family == AF_INET6 && errno == EAFNOSUPPORT) {
440 + fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
441 + from.u.sa.sa_family = AF_INET;
447 + if (bind(fd, &from.u.sa, from.len) < 0) {
452 + /* Convert any IPv4 addresses in a mixed environment to v4-mapped */
453 + if (from.u.sa.sa_family == AF_INET6) {
454 + setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
456 + for (nn = 0; nn < n_ns; nn++)
457 + to_v4_mapped(&ns[nn].addr);
461 + pfd.events = POLLIN;
462 + retry_interval = timeout / default_retry;
464 + t1 = t2 - retry_interval;
466 + for (; t2 - t0 < timeout; t2 = mtime()) {
467 + if (t2 - t1 >= retry_interval) {
468 + for (qn = 0; qn < n_queries; qn++) {
469 + if (queries[qn].rlen)
472 + for (nn = 0; nn < n_ns; nn++) {
473 + sendto(fd, queries[qn].query, queries[qn].qlen,
474 + MSG_NOSIGNAL, &ns[nn].addr.u.sa, ns[nn].addr.len);
479 + servfail_retry = 2 * n_queries;
482 + /* Wait for a response, or until time to retry */
483 + if (poll(&pfd, 1, t1+retry_interval-t2) <= 0)
487 + recvlen = recvfrom(fd, queries[next_query].reply,
488 + sizeof(queries[next_query].reply), 0,
489 + &from.u.sa, &from.len);
495 + /* Ignore non-identifiable packets */
499 + /* Ignore replies from addresses we didn't send to */
500 + for (nn = 0; nn < n_ns; nn++)
501 + if (memcmp(&from.u.sa, &ns[nn].addr.u.sa, from.len) == 0)
507 + /* Find which query this answer goes with, if any */
508 + for (qn = next_query; qn < n_queries; qn++)
509 + if (!memcmp(queries[next_query].reply, queries[qn].query, 2))
512 + if (qn >= n_queries || queries[qn].rlen)
515 + queries[qn].rcode = queries[next_query].reply[3] & 15;
516 + queries[qn].latency = mtime() - t0;
517 + queries[qn].n_ns = nn;
521 + /* Only accept positive or negative responses;
522 + * retry immediately on server failure, and ignore
523 + * all other codes such as refusal. */
524 + switch (queries[qn].rcode) {
530 + if (servfail_retry && servfail_retry--) {
532 + sendto(fd, queries[qn].query, queries[qn].qlen,
533 + MSG_NOSIGNAL, &ns[nn].addr.u.sa, ns[nn].addr.len);
544 + queries[qn].rlen = recvlen;
546 + if (qn == next_query) {
547 + while (next_query < n_queries) {
548 + if (!queries[next_query].rlen)
555 + memcpy(queries[qn].reply, queries[next_query].reply, recvlen);
558 + if (next_query >= n_queries)
566 +static struct ns *add_ns(struct ns **ns, int *n_ns, const char *addr)
568 + char portstr[sizeof("65535")], *p;
569 + len_and_sockaddr a = { };
571 + struct addrinfo *ai, *aip, hints = {
572 + .ai_flags = AI_NUMERICSERV,
573 + .ai_socktype = SOCK_DGRAM
576 + if (parse_nsaddr(addr, &a)) {
577 + /* Maybe we got a domain name, attempt to resolve it using the standard
578 + * resolver routines */
580 + p = strchr(addr, '#');
581 + snprintf(portstr, sizeof(portstr), "%hu",
582 + (unsigned short)(p ? strtoul(p, NULL, 10) : default_port));
584 + if (!getaddrinfo(addr, portstr, &hints, &ai)) {
585 + for (aip = ai; aip; aip = aip->ai_next) {
586 + if (aip->ai_addr->sa_family != AF_INET &&
587 + aip->ai_addr->sa_family != AF_INET6)
590 + tmp = realloc(*ns, sizeof(**ns) * (*n_ns + 1));
597 + (*ns)[*n_ns].name = addr;
598 + (*ns)[*n_ns].replies = 0;
599 + (*ns)[*n_ns].failures = 0;
600 + (*ns)[*n_ns].addr.len = aip->ai_addrlen;
602 + memcpy(&(*ns)[*n_ns].addr.u.sa, aip->ai_addr, aip->ai_addrlen);
609 + return &(*ns)[*n_ns];
615 + tmp = realloc(*ns, sizeof(**ns) * (*n_ns + 1));
622 + (*ns)[*n_ns].addr = a;
623 + (*ns)[*n_ns].name = addr;
624 + (*ns)[*n_ns].replies = 0;
625 + (*ns)[*n_ns].failures = 0;
627 + return &(*ns)[(*n_ns)++];
630 +static int parse_resolvconf(struct ns **ns, int *n_ns)
632 + int prev_n_ns = *n_ns;
633 + char line[128], *p;
636 + if ((resolv = fopen("/etc/resolv.conf", "r")) != NULL) {
637 + while (fgets(line, sizeof(line), resolv)) {
638 + p = strtok(line, " \t\n");
640 + if (!p || strcmp(p, "nameserver"))
643 + p = strtok(NULL, " \t\n");
648 + if (!add_ns(ns, n_ns, strdup(p))) {
657 + return *n_ns - prev_n_ns;
660 +static struct query *add_query(struct query **queries, int *n_queries,
661 + int type, const char *dname)
666 + tmp = realloc(*queries, sizeof(**queries) * (*n_queries + 1));
671 + memset(&tmp[*n_queries], 0, sizeof(*tmp));
673 + qlen = res_mkquery(QUERY, dname, C_IN, type, NULL, 0, NULL,
674 + tmp[*n_queries].query, sizeof(tmp[*n_queries].query));
676 + tmp[*n_queries].qlen = qlen;
677 + tmp[*n_queries].name = dname;
680 + return &tmp[(*n_queries)++];
683 +static char *sal2str(len_and_sockaddr *a)
685 + static char buf[INET6_ADDRSTRLEN + 1 + IFNAMSIZ + 1 + 5 + 1];
688 + if (a->u.sa.sa_family == AF_INET6) {
689 + inet_ntop(AF_INET6, &a->u.sin6.sin6_addr, buf, sizeof(buf));
692 + if (a->u.sin6.sin6_scope_id) {
693 + if (if_indextoname(a->u.sin6.sin6_scope_id, p + 1)) {
700 + inet_ntop(AF_INET, &a->u.sin.sin_addr, buf, sizeof(buf));
704 + sprintf(p, "#%hu", ntohs(a->u.sin6.sin6_port));
710 +#if ENABLE_FEATURE_NSLOOKUP_LEDE_LONG_OPTIONS
711 +static const char nslookup_longopts[] ALIGN1 =
712 + "type\0" Required_argument "q"
713 + "querytype\0" Required_argument "q"
714 + "port\0" Required_argument "p"
715 + "retry\0" Required_argument "r"
716 + "timeout\0" Required_argument "t"
717 + "stats\0" Required_argument "s"
721 +int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
722 +int nslookup_main(int argc, char **argv)
726 + struct ns *ns = NULL;
727 + struct query *queries = NULL;
728 + llist_t *type_strings = NULL;
729 + int n_ns = 0, n_queries = 0;
730 + int c, opts, option_index = 0;
732 + unsigned int types = 0;
735 +#if ENABLE_FEATURE_NSLOOKUP_LEDE_LONG_OPTIONS
736 + applet_long_options = nslookup_longopts;
739 + opts = getopt32(argv, "+q:*p:+r:+t:+s",
740 + &type_strings, &default_port,
741 + &default_retry, &default_timeout);
743 + while (type_strings) {
744 + ptr = llist_pop(&type_strings);
746 + /* skip leading text, e.g. when invoked with -querytype=AAAA */
747 + if ((chr = strchr(ptr, '=')) != NULL) {
752 + for (c = 0; qtypes[c].name; c++)
753 + if (!strcmp(qtypes[c].name, ptr))
756 + if (!qtypes[c].name) {
757 + fprintf(stderr, "Invalid query type \"%s\"\n", ptr);
764 + if (default_port > 65535) {
765 + fprintf(stderr, "Invalid server port\n");
769 + if (!default_retry) {
770 + fprintf(stderr, "Invalid retry value\n");
774 + if (!default_timeout) {
775 + fprintf(stderr, "Invalid timeout value\n");
779 + stats = (opts & 16);
781 + if (optind >= argc)
784 + for (option_index = optind;
785 + option_index < ((argc - optind) > 1 ? argc - 1 : argc);
788 + /* No explicit type given, guess query type.
789 + * If we can convert the domain argument into a ptr (means that
790 + * inet_pton() could read it) we assume a PTR request, else
791 + * we issue A queries. */
793 + ptr = make_ptr(argv[option_index]);
796 + add_query(&queries, &n_queries, T_PTR, ptr);
798 + add_query(&queries, &n_queries, T_A, argv[option_index]);
801 + for (c = 0; qtypes[c].name; c++)
802 + if (types & (1 << c))
803 + add_query(&queries, &n_queries, qtypes[c].type,
804 + argv[option_index]);
808 + /* Use given DNS server if present */
809 + if (option_index < argc) {
810 + if (!add_ns(&ns, &n_ns, argv[option_index])) {
811 + fprintf(stderr, "Invalid NS server address \"%s\": %s\n",
812 + argv[option_index], strerror(errno));
817 + parse_resolvconf(&ns, &n_ns);
820 + /* Fall back to localhost if we could not find NS in resolv.conf */
822 + add_ns(&ns, &n_ns, "127.0.0.1");
825 + for (c = 0; c < n_ns; c++) {
826 + rc = send_queries(&ns[c], 1, queries, n_queries);
829 + fprintf(stderr, "Failed to send queries: %s\n", strerror(errno));
831 + } else if (rc > 0) {
838 + ";; connection timed out; no servers could be reached\n\n");
843 + printf("Server:\t\t%s\n", ns[c].name);
844 + printf("Address:\t%s\n", sal2str(&ns[c].addr));
847 + printf("Replies:\t%d\n", ns[c].replies);
848 + printf("Failures:\t%d\n", ns[c].failures);
853 + for (rc = 0; rc < n_queries; rc++) {
855 + printf("Query #%d completed in %lums:\n", rc, queries[rc].latency);
858 + if (queries[rc].rcode != 0) {
859 + printf("** server can't find %s: %s\n", queries[rc].name,
860 + rcodes[queries[rc].rcode]);
866 + if (queries[rc].rlen) {
867 + header = (HEADER *)queries[rc].reply;
870 + printf("Non-authoritative answer:\n");
872 + c = parse_reply(queries[rc].reply, queries[rc].rlen);
876 + printf("*** Can't find %s: No answer\n", queries[rc].name);
878 + printf("*** Can't find %s: Parse error\n", queries[rc].name);