1 From 2285cd400a10b1bde5472fe1cec3311300ee943c 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 | 893 +++++++++++++++++++++++++++++++++++++++++++++
16 1 file changed, 893 insertions(+)
17 create mode 100644 networking/nslookup_lede.c
19 diff --git a/networking/nslookup_lede.c b/networking/nslookup_lede.c
21 index 000000000..6f1f86502
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 +#if ENABLE_FEATURE_IPV6
113 + { ns_t_aaaa, "AAAA" },
115 + { ns_t_cname, "CNAME" },
117 + { ns_t_txt, "TXT" },
118 + { ns_t_ptr, "PTR" },
119 + { ns_t_any, "ANY" },
123 +static const char *rcodes[] = {
143 +static unsigned int default_port = 53;
144 +static unsigned int default_retry = 2;
145 +static unsigned int default_timeout = 5;
148 +static int parse_reply(const unsigned char *msg, size_t len)
153 + const char *format = NULL;
154 + char astr[INET6_ADDRSTRLEN], dname[MAXDNAME];
155 + const unsigned char *cp;
157 + if (ns_initparse(msg, len, &handle) != 0) {
158 + //fprintf(stderr, "Unable to parse reply: %s\n", strerror(errno));
162 + for (i = 0; i < ns_msg_count(handle, ns_s_an); i++) {
163 + if (ns_parserr(&handle, ns_s_an, i, &rr) != 0) {
164 + //fprintf(stderr, "Unable to parse resource record: %s\n", strerror(errno));
168 + rdlen = ns_rr_rdlen(rr);
170 + switch (ns_rr_type(rr))
174 + //fprintf(stderr, "Unexpected A record length\n");
177 + inet_ntop(AF_INET, ns_rr_rdata(rr), astr, sizeof(astr));
178 + printf("Name:\t%s\nAddress: %s\n", ns_rr_name(rr), astr);
181 +#if ENABLE_FEATURE_IPV6
184 + //fprintf(stderr, "Unexpected AAAA record length\n");
187 + inet_ntop(AF_INET6, ns_rr_rdata(rr), astr, sizeof(astr));
188 + printf("%s\thas AAAA address %s\n", ns_rr_name(rr), astr);
194 + format = "%s\tnameserver = %s\n";
199 + format = "%s\tcanonical name = %s\n";
204 + format = "%s\tname = %s\n";
205 + if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
206 + ns_rr_rdata(rr), dname, sizeof(dname)) < 0) {
207 + //fprintf(stderr, "Unable to uncompress domain: %s\n", strerror(errno));
210 + printf(format, ns_rr_name(rr), dname);
215 + fprintf(stderr, "MX record too short\n");
218 + n = ns_get16(ns_rr_rdata(rr));
219 + if (ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
220 + ns_rr_rdata(rr) + 2, dname, sizeof(dname)) < 0) {
221 + //fprintf(stderr, "Cannot uncompress MX domain: %s\n", strerror(errno));
224 + printf("%s\tmail exchanger = %d %s\n", ns_rr_name(rr), n, dname);
229 + //fprintf(stderr, "TXT record too short\n");
232 + n = *(unsigned char *)ns_rr_rdata(rr);
234 + memset(dname, 0, sizeof(dname));
235 + memcpy(dname, ns_rr_rdata(rr) + 1, n);
236 + printf("%s\ttext = \"%s\"\n", ns_rr_name(rr), dname);
242 + //fprintf(stderr, "SOA record too short\n");
246 + printf("%s\n", ns_rr_name(rr));
248 + cp = ns_rr_rdata(rr);
249 + n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
250 + cp, dname, sizeof(dname));
253 + //fprintf(stderr, "Unable to uncompress domain: %s\n", strerror(errno));
257 + printf("\torigin = %s\n", dname);
260 + n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
261 + cp, dname, sizeof(dname));
264 + //fprintf(stderr, "Unable to uncompress domain: %s\n", strerror(errno));
268 + printf("\tmail addr = %s\n", dname);
271 + printf("\tserial = %lu\n", ns_get32(cp));
274 + printf("\trefresh = %lu\n", ns_get32(cp));
277 + printf("\tretry = %lu\n", ns_get32(cp));
280 + printf("\texpire = %lu\n", ns_get32(cp));
283 + printf("\tminimum = %lu\n", ns_get32(cp));
294 +static int parse_nsaddr(const char *addrstr, len_and_sockaddr *lsa)
296 + char *eptr, *hash, ifname[IFNAMSIZ];
297 + unsigned int port = default_port;
298 + unsigned int scope = 0;
300 + hash = strchr(addrstr, '#');
304 + port = strtoul(hash, &eptr, 10);
306 + if (eptr == hash || *eptr != '\0' || port > 65535) {
312 + hash = strchr(addrstr, '%');
315 + for (eptr = ++hash; *eptr != '\0' && *eptr != '#'; eptr++) {
316 + if ((eptr - hash) >= IFNAMSIZ) {
321 + ifname[eptr - hash] = *eptr;
324 + ifname[eptr - hash] = '\0';
325 + scope = if_nametoindex(ifname);
333 +#if ENABLE_FEATURE_IPV6
334 + if (inet_pton(AF_INET6, addrstr, &lsa->u.sin6.sin6_addr)) {
335 + lsa->u.sin6.sin6_family = AF_INET6;
336 + lsa->u.sin6.sin6_port = htons(port);
337 + lsa->u.sin6.sin6_scope_id = scope;
338 + lsa->len = sizeof(lsa->u.sin6);
343 + if (!scope && inet_pton(AF_INET, addrstr, &lsa->u.sin.sin_addr)) {
344 + lsa->u.sin.sin_family = AF_INET;
345 + lsa->u.sin.sin_port = htons(port);
346 + lsa->len = sizeof(lsa->u.sin);
354 +static char *make_ptr(const char *addrstr)
356 + const char *hexdigit = "0123456789abcdef";
357 + static char ptrstr[73];
358 + unsigned char addr[16];
359 + char *ptr = ptrstr;
362 + if (inet_pton(AF_INET6, addrstr, addr)) {
363 + if (memcmp(addr, "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12) != 0) {
364 + for (i = 0; i < 16; i++) {
365 + *ptr++ = hexdigit[(unsigned char)addr[15 - i] & 0xf];
367 + *ptr++ = hexdigit[(unsigned char)addr[15 - i] >> 4];
370 + strcpy(ptr, "ip6.arpa");
373 + sprintf(ptr, "%u.%u.%u.%u.in-addr.arpa",
374 + addr[15], addr[14], addr[13], addr[12]);
380 + if (inet_pton(AF_INET, addrstr, addr)) {
381 + sprintf(ptr, "%u.%u.%u.%u.in-addr.arpa",
382 + addr[3], addr[2], addr[1], addr[0]);
389 +static unsigned long mtime(void)
391 + struct timespec ts;
392 + clock_gettime(CLOCK_REALTIME, &ts);
393 + return (unsigned long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
396 +#if ENABLE_FEATURE_IPV6
397 +static void to_v4_mapped(len_and_sockaddr *a)
399 + if (a->u.sa.sa_family != AF_INET)
402 + memcpy(a->u.sin6.sin6_addr.s6_addr + 12,
403 + &a->u.sin.sin_addr, 4);
405 + memcpy(a->u.sin6.sin6_addr.s6_addr,
406 + "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
408 + a->u.sin6.sin6_family = AF_INET6;
409 + a->u.sin6.sin6_flowinfo = 0;
410 + a->u.sin6.sin6_scope_id = 0;
411 + a->len = sizeof(a->u.sin6);
417 + * Function logic borrowed & modified from musl libc, res_msend.c
420 +static int send_queries(struct ns *ns, int n_ns, struct query *queries, int n_queries)
423 + int timeout = default_timeout * 1000, retry_interval, servfail_retry = 0;
424 + len_and_sockaddr from = { };
425 +#if ENABLE_FEATURE_IPV6
431 + unsigned long t0, t1, t2;
432 + int nn, qn, next_query = 0;
434 + from.u.sa.sa_family = AF_INET;
435 + from.len = sizeof(from.u.sin);
437 +#if ENABLE_FEATURE_IPV6
438 + for (nn = 0; nn < n_ns; nn++) {
439 + if (ns[nn].addr.u.sa.sa_family == AF_INET6) {
440 + from.u.sa.sa_family = AF_INET6;
441 + from.len = sizeof(from.u.sin6);
447 + /* Get local address and open/bind a socket */
448 + fd = socket(from.u.sa.sa_family, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
450 +#if ENABLE_FEATURE_IPV6
451 + /* Handle case where system lacks IPv6 support */
452 + if (fd < 0 && from.u.sa.sa_family == AF_INET6 && errno == EAFNOSUPPORT) {
453 + fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
454 + from.u.sa.sa_family = AF_INET;
461 + if (bind(fd, &from.u.sa, from.len) < 0) {
466 +#if ENABLE_FEATURE_IPV6
467 + /* Convert any IPv4 addresses in a mixed environment to v4-mapped */
468 + if (from.u.sa.sa_family == AF_INET6) {
469 + setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
471 + for (nn = 0; nn < n_ns; nn++)
472 + to_v4_mapped(&ns[nn].addr);
477 + pfd.events = POLLIN;
478 + retry_interval = timeout / default_retry;
480 + t1 = t2 - retry_interval;
482 + for (; t2 - t0 < timeout; t2 = mtime()) {
483 + if (t2 - t1 >= retry_interval) {
484 + for (qn = 0; qn < n_queries; qn++) {
485 + if (queries[qn].rlen)
488 + for (nn = 0; nn < n_ns; nn++) {
489 + sendto(fd, queries[qn].query, queries[qn].qlen,
490 + MSG_NOSIGNAL, &ns[nn].addr.u.sa, ns[nn].addr.len);
495 + servfail_retry = 2 * n_queries;
498 + /* Wait for a response, or until time to retry */
499 + if (poll(&pfd, 1, t1+retry_interval-t2) <= 0)
503 + recvlen = recvfrom(fd, queries[next_query].reply,
504 + sizeof(queries[next_query].reply), 0,
505 + &from.u.sa, &from.len);
511 + /* Ignore non-identifiable packets */
515 + /* Ignore replies from addresses we didn't send to */
516 + for (nn = 0; nn < n_ns; nn++)
517 + if (memcmp(&from.u.sa, &ns[nn].addr.u.sa, from.len) == 0)
523 + /* Find which query this answer goes with, if any */
524 + for (qn = next_query; qn < n_queries; qn++)
525 + if (!memcmp(queries[next_query].reply, queries[qn].query, 2))
528 + if (qn >= n_queries || queries[qn].rlen)
531 + queries[qn].rcode = queries[next_query].reply[3] & 15;
532 + queries[qn].latency = mtime() - t0;
533 + queries[qn].n_ns = nn;
537 + /* Only accept positive or negative responses;
538 + * retry immediately on server failure, and ignore
539 + * all other codes such as refusal. */
540 + switch (queries[qn].rcode) {
546 + if (servfail_retry && servfail_retry--) {
548 + sendto(fd, queries[qn].query, queries[qn].qlen,
549 + MSG_NOSIGNAL, &ns[nn].addr.u.sa, ns[nn].addr.len);
560 + queries[qn].rlen = recvlen;
562 + if (qn == next_query) {
563 + while (next_query < n_queries) {
564 + if (!queries[next_query].rlen)
571 + memcpy(queries[qn].reply, queries[next_query].reply, recvlen);
574 + if (next_query >= n_queries)
582 +static struct ns *add_ns(struct ns **ns, int *n_ns, const char *addr)
584 + char portstr[sizeof("65535")], *p;
585 + len_and_sockaddr a = { };
587 + struct addrinfo *ai, *aip, hints = {
588 + .ai_flags = AI_NUMERICSERV,
589 + .ai_socktype = SOCK_DGRAM
592 + if (parse_nsaddr(addr, &a)) {
593 + /* Maybe we got a domain name, attempt to resolve it using the standard
594 + * resolver routines */
596 + p = strchr(addr, '#');
597 + snprintf(portstr, sizeof(portstr), "%hu",
598 + (unsigned short)(p ? strtoul(p, NULL, 10) : default_port));
600 + if (!getaddrinfo(addr, portstr, &hints, &ai)) {
601 + for (aip = ai; aip; aip = aip->ai_next) {
602 + if (aip->ai_addr->sa_family != AF_INET &&
603 + aip->ai_addr->sa_family != AF_INET6)
606 +#if ! ENABLE_FEATURE_IPV6
607 + if (aip->ai_addr->sa_family != AF_INET)
611 + tmp = realloc(*ns, sizeof(**ns) * (*n_ns + 1));
618 + (*ns)[*n_ns].name = addr;
619 + (*ns)[*n_ns].replies = 0;
620 + (*ns)[*n_ns].failures = 0;
621 + (*ns)[*n_ns].addr.len = aip->ai_addrlen;
623 + memcpy(&(*ns)[*n_ns].addr.u.sa, aip->ai_addr, aip->ai_addrlen);
630 + return &(*ns)[*n_ns];
636 + tmp = realloc(*ns, sizeof(**ns) * (*n_ns + 1));
643 + (*ns)[*n_ns].addr = a;
644 + (*ns)[*n_ns].name = addr;
645 + (*ns)[*n_ns].replies = 0;
646 + (*ns)[*n_ns].failures = 0;
648 + return &(*ns)[(*n_ns)++];
651 +static int parse_resolvconf(struct ns **ns, int *n_ns)
653 + int prev_n_ns = *n_ns;
654 + char line[128], *p;
657 + if ((resolv = fopen("/etc/resolv.conf", "r")) != NULL) {
658 + while (fgets(line, sizeof(line), resolv)) {
659 + p = strtok(line, " \t\n");
661 + if (!p || strcmp(p, "nameserver"))
664 + p = strtok(NULL, " \t\n");
669 + if (!add_ns(ns, n_ns, strdup(p))) {
678 + return *n_ns - prev_n_ns;
681 +static struct query *add_query(struct query **queries, int *n_queries,
682 + int type, const char *dname)
687 + tmp = realloc(*queries, sizeof(**queries) * (*n_queries + 1));
692 + memset(&tmp[*n_queries], 0, sizeof(*tmp));
694 + qlen = res_mkquery(QUERY, dname, C_IN, type, NULL, 0, NULL,
695 + tmp[*n_queries].query, sizeof(tmp[*n_queries].query));
697 + tmp[*n_queries].qlen = qlen;
698 + tmp[*n_queries].name = dname;
701 + return &tmp[(*n_queries)++];
704 +static char *sal2str(len_and_sockaddr *a)
706 + static char buf[INET6_ADDRSTRLEN + 1 + IFNAMSIZ + 1 + 5 + 1];
709 +#if ENABLE_FEATURE_IPV6
710 + if (a->u.sa.sa_family == AF_INET6) {
711 + inet_ntop(AF_INET6, &a->u.sin6.sin6_addr, buf, sizeof(buf));
714 + if (a->u.sin6.sin6_scope_id) {
715 + if (if_indextoname(a->u.sin6.sin6_scope_id, p + 1)) {
724 + inet_ntop(AF_INET, &a->u.sin.sin_addr, buf, sizeof(buf));
728 + sprintf(p, "#%hu", ntohs(a->u.sin.sin_port));
734 +#if ENABLE_FEATURE_NSLOOKUP_LEDE_LONG_OPTIONS
735 +static const char nslookup_longopts[] ALIGN1 =
736 + "type\0" Required_argument "q"
737 + "querytype\0" Required_argument "q"
738 + "port\0" Required_argument "p"
739 + "retry\0" Required_argument "r"
740 + "timeout\0" Required_argument "t"
741 + "stats\0" Required_argument "s"
745 +int nslookup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
746 +int nslookup_main(int argc, char **argv)
750 + struct ns *ns = NULL;
751 + struct query *queries = NULL;
752 + llist_t *type_strings = NULL;
753 + int n_ns = 0, n_queries = 0;
754 + int c, opts, option_index = 0;
756 + unsigned int types = 0;
759 +#if ENABLE_FEATURE_NSLOOKUP_LEDE_LONG_OPTIONS
760 + applet_long_options = nslookup_longopts;
763 + opts = getopt32(argv, "+q:*p:+r:+t:+s",
764 + &type_strings, &default_port,
765 + &default_retry, &default_timeout);
767 + while (type_strings) {
768 + ptr = llist_pop(&type_strings);
770 + /* skip leading text, e.g. when invoked with -querytype=AAAA */
771 + if ((chr = strchr(ptr, '=')) != NULL) {
776 + for (c = 0; qtypes[c].name; c++)
777 + if (!strcmp(qtypes[c].name, ptr))
780 + if (!qtypes[c].name) {
781 + fprintf(stderr, "Invalid query type \"%s\"\n", ptr);
788 + if (default_port > 65535) {
789 + fprintf(stderr, "Invalid server port\n");
793 + if (!default_retry) {
794 + fprintf(stderr, "Invalid retry value\n");
798 + if (!default_timeout) {
799 + fprintf(stderr, "Invalid timeout value\n");
803 + stats = (opts & 16);
805 + if (optind >= argc)
808 + for (option_index = optind;
809 + option_index < ((argc - optind) > 1 ? argc - 1 : argc);
812 + /* No explicit type given, guess query type.
813 + * If we can convert the domain argument into a ptr (means that
814 + * inet_pton() could read it) we assume a PTR request, else
815 + * we issue A queries. */
817 + ptr = make_ptr(argv[option_index]);
820 + add_query(&queries, &n_queries, T_PTR, ptr);
822 + add_query(&queries, &n_queries, T_A, argv[option_index]);
825 + for (c = 0; qtypes[c].name; c++)
826 + if (types & (1 << c))
827 + add_query(&queries, &n_queries, qtypes[c].type,
828 + argv[option_index]);
832 + /* Use given DNS server if present */
833 + if (option_index < argc) {
834 + if (!add_ns(&ns, &n_ns, argv[option_index])) {
835 + fprintf(stderr, "Invalid NS server address \"%s\": %s\n",
836 + argv[option_index], strerror(errno));
841 + parse_resolvconf(&ns, &n_ns);
844 + /* Fall back to localhost if we could not find NS in resolv.conf */
846 + add_ns(&ns, &n_ns, "127.0.0.1");
849 + for (c = 0; c < n_ns; c++) {
850 + rc = send_queries(&ns[c], 1, queries, n_queries);
853 + fprintf(stderr, "Failed to send queries: %s\n", strerror(errno));
855 + } else if (rc > 0) {
862 + ";; connection timed out; no servers could be reached\n\n");
867 + printf("Server:\t\t%s\n", ns[c].name);
868 + printf("Address:\t%s\n", sal2str(&ns[c].addr));
871 + printf("Replies:\t%d\n", ns[c].replies);
872 + printf("Failures:\t%d\n", ns[c].failures);
877 + for (rc = 0; rc < n_queries; rc++) {
879 + printf("Query #%d completed in %lums:\n", rc, queries[rc].latency);
882 + if (queries[rc].rcode != 0) {
883 + printf("** server can't find %s: %s\n", queries[rc].name,
884 + rcodes[queries[rc].rcode]);
890 + if (queries[rc].rlen) {
891 + header = (HEADER *)queries[rc].reply;
894 + printf("Non-authoritative answer:\n");
896 + c = parse_reply(queries[rc].reply, queries[rc].rlen);
900 + printf("*** Can't find %s: No answer\n", queries[rc].name);
902 + printf("*** Can't find %s: Parse error\n", queries[rc].name);