2 * Copyright (c) 2014-2018 Andreas Schneider <asn@samba.org>
3 * Copyright (c) 2014-2016 Jakub Hrozek <jakub.hrozek@posteo.se>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the author nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 #include <arpa/inet.h>
39 #ifdef HAVE_ARPA_NAMESER_H
40 #include <arpa/nameser.h>
41 #endif /* HAVE_ARPA_NAMESER_H */
42 #include <netinet/in.h>
43 #include <sys/socket.h>
44 #include <sys/types.h>
55 /* GCC has printf type attribute check. */
56 #ifdef HAVE_ATTRIBUTE_PRINTF_FORMAT
57 #define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
59 #define PRINTF_ATTRIBUTE(a,b)
60 #endif /* HAVE_ATTRIBUTE_PRINTF_FORMAT */
62 #ifdef HAVE_DESTRUCTOR_ATTRIBUTE
63 #define DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor))
65 #define DESTRUCTOR_ATTRIBUTE
66 #endif /* HAVE_DESTRUCTOR_ATTRIBUTE */
68 #ifndef RWRAP_DEFAULT_FAKE_TTL
69 #define RWRAP_DEFAULT_FAKE_TTL 600
70 #endif /* RWRAP_DEFAULT_FAKE_TTL */
72 #ifndef HAVE_NS_NAME_COMPRESS
73 #define ns_name_compress dn_comp
86 static void rwrap_log(enum rwrap_dbglvl_e dbglvl, const char *func, const char *format, ...) PRINTF_ATTRIBUTE(3, 4);
87 # define RWRAP_LOG(dbglvl, ...) rwrap_log((dbglvl), __func__, __VA_ARGS__)
89 static void rwrap_log(enum rwrap_dbglvl_e dbglvl,
91 const char *format, ...)
98 const char *prefix = NULL;
100 d = getenv("RESOLV_WRAPPER_DEBUGLEVEL");
109 va_start(va, format);
110 vsnprintf(buffer, sizeof(buffer), format, va);
114 case RWRAP_LOG_ERROR:
115 prefix = "RWRAP_ERROR";
118 prefix = "RWRAP_WARN";
120 case RWRAP_LOG_NOTICE:
121 prefix = "RWRAP_NOTICE";
123 case RWRAP_LOG_DEBUG:
124 prefix = "RWRAP_DEBUG";
126 case RWRAP_LOG_TRACE:
127 prefix = "RWRAP_TRACE";
140 #define SAFE_FREE(x) do { if ((x) != NULL) {free(x); (x)=NULL;} } while(0)
143 #define NEXT_KEY(buf, key) do { \
144 (key) = (buf) ? strpbrk((buf), " \t") : NULL; \
145 if ((key) != NULL) { \
149 while ((key) != NULL \
150 && (isblank((int)(key)[0]))) { \
155 #define RWRAP_MAX_RECURSION 64
157 /* Priority and weight can be omitted from the hosts file, but need to be part
160 #define DFL_SRV_PRIO 1
161 #define DFL_SRV_WEIGHT 100
162 #define DFL_URI_PRIO 1
163 #define DFL_URI_WEIGHT 100
165 struct rwrap_srv_rrdata {
169 char hostname[MAXDNAME];
172 struct rwrap_uri_rrdata {
178 struct rwrap_soa_rrdata {
184 char nameserver[MAXDNAME];
185 char mailbox[MAXDNAME];
188 struct rwrap_fake_rr {
190 struct in_addr a_rec;
191 struct in6_addr aaaa_rec;
192 struct rwrap_srv_rrdata srv_rec;
193 struct rwrap_uri_rrdata uri_rec;
194 struct rwrap_soa_rrdata soa_rec;
195 char cname_rec[MAXDNAME];
196 char ptr_rec[MAXDNAME];
200 int type; /* ns_t_* */
203 static void rwrap_fake_rr_init(struct rwrap_fake_rr *rr, size_t len)
207 for (i = 0; i < len; i++) {
208 rr[i].type = ns_t_invalid;
212 static int rwrap_create_fake_a_rr(const char *key,
214 struct rwrap_fake_rr *rr)
218 ok = inet_pton(AF_INET, value, &rr->rrdata.a_rec);
220 RWRAP_LOG(RWRAP_LOG_ERROR,
221 "Failed to convert [%s] to binary\n", value);
225 memcpy(rr->key, key, strlen(key) + 1);
230 static int rwrap_create_fake_aaaa_rr(const char *key,
232 struct rwrap_fake_rr *rr)
236 ok = inet_pton(AF_INET6, value, &rr->rrdata.aaaa_rec);
238 RWRAP_LOG(RWRAP_LOG_ERROR,
239 "Failed to convert [%s] to binary\n", value);
243 memcpy(rr->key, key, strlen(key) + 1);
244 rr->type = ns_t_aaaa;
247 static int rwrap_create_fake_ns_rr(const char *key,
249 struct rwrap_fake_rr *rr)
251 memcpy(rr->rrdata.srv_rec.hostname, value, strlen(value) + 1);
252 memcpy(rr->key, key, strlen(key) + 1);
257 static int rwrap_create_fake_srv_rr(const char *key,
259 struct rwrap_fake_rr *rr)
264 const char *hostname;
266 /* parse the value into priority, weight, port and hostname
267 * and check the validity */
269 NEXT_KEY(hostname, str_port);
270 NEXT_KEY(str_port, str_prio);
271 NEXT_KEY(str_prio, str_weight);
272 if (str_port == NULL || hostname == NULL) {
273 RWRAP_LOG(RWRAP_LOG_ERROR,
274 "Malformed SRV entry [%s]\n", value);
279 rr->rrdata.srv_rec.prio = atoi(str_prio);
281 rr->rrdata.srv_rec.prio = DFL_SRV_PRIO;
284 rr->rrdata.srv_rec.weight = atoi(str_weight);
286 rr->rrdata.srv_rec.weight = DFL_SRV_WEIGHT;
288 rr->rrdata.srv_rec.port = atoi(str_port);
289 memcpy(rr->rrdata.srv_rec.hostname , hostname, strlen(hostname) + 1);
291 memcpy(rr->key, key, strlen(key) + 1);
296 static int rwrap_create_fake_uri_rr(const char *key,
298 struct rwrap_fake_rr *rr)
304 /* parse the value into priority, weight, and uri
305 * and check the validity */
307 NEXT_KEY(uri, str_prio);
308 NEXT_KEY(str_prio, str_weight);
310 RWRAP_LOG(RWRAP_LOG_ERROR,
311 "Malformed URI entry [%s]\n", value);
316 rr->rrdata.uri_rec.prio = atoi(str_prio);
318 rr->rrdata.uri_rec.prio = DFL_URI_PRIO;
321 rr->rrdata.uri_rec.weight = atoi(str_weight);
323 rr->rrdata.uri_rec.weight = DFL_URI_WEIGHT;
325 memcpy(rr->rrdata.uri_rec.uri, uri, strlen(uri) + 1);
327 memcpy(rr->key, key, strlen(key) + 1);
332 static int rwrap_create_fake_soa_rr(const char *key,
334 struct rwrap_fake_rr *rr)
336 const char *nameserver;
344 /* parse the value into nameserver, mailbox, serial, refresh,
345 * retry, expire, minimum and check the validity
348 NEXT_KEY(nameserver, mailbox);
349 NEXT_KEY(mailbox, str_serial);
350 NEXT_KEY(str_serial, str_refresh);
351 NEXT_KEY(str_refresh, str_retry);
352 NEXT_KEY(str_retry, str_expire);
353 NEXT_KEY(str_expire, str_minimum);
354 if (nameserver == NULL || mailbox == NULL || str_serial == NULL ||
355 str_refresh == NULL || str_retry == NULL || str_expire == NULL ||
356 str_minimum == NULL) {
357 RWRAP_LOG(RWRAP_LOG_ERROR,
358 "Malformed SOA entry [%s]\n", value);
362 memcpy(rr->rrdata.soa_rec.nameserver, nameserver, strlen(nameserver)+1);
363 memcpy(rr->rrdata.soa_rec.mailbox, mailbox, strlen(mailbox)+1);
365 rr->rrdata.soa_rec.serial = atoi(str_serial);
366 rr->rrdata.soa_rec.refresh = atoi(str_refresh);
367 rr->rrdata.soa_rec.retry = atoi(str_retry);
368 rr->rrdata.soa_rec.expire = atoi(str_expire);
369 rr->rrdata.soa_rec.minimum = atoi(str_minimum);
371 memcpy(rr->key, key, strlen(key) + 1);
376 static int rwrap_create_fake_cname_rr(const char *key,
378 struct rwrap_fake_rr *rr)
380 memcpy(rr->rrdata.cname_rec , value, strlen(value) + 1);
381 memcpy(rr->key, key, strlen(key) + 1);
382 rr->type = ns_t_cname;
386 static int rwrap_create_fake_ptr_rr(const char *key,
388 struct rwrap_fake_rr *rr)
390 memcpy(rr->rrdata.ptr_rec , value, strlen(value) + 1);
391 memcpy(rr->key, key, strlen(key) + 1);
396 /* Prepares a fake header with a single response. Advances header_blob */
397 static ssize_t rwrap_fake_header(uint8_t **header_blob, size_t remaining,
398 size_t ancount, size_t arcount)
405 if (remaining < NS_HFIXEDSZ) {
406 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small!\n");
410 h.blob = *header_blob;
411 memset(h.blob, 0, NS_HFIXEDSZ);
413 h.header->id = res_randomid(); /* random query ID */
414 h.header->qr = 1; /* response flag */
415 h.header->rd = 1; /* recursion desired */
416 h.header->ra = 1; /* recursion available */
418 h.header->qdcount = htons(1); /* no. of questions */
419 h.header->ancount = htons(ancount); /* no. of answers */
420 h.header->arcount = htons(arcount); /* no. of add'tl records */
422 /* move past the header */
423 *header_blob = h.blob += NS_HFIXEDSZ;
428 static ssize_t rwrap_fake_question(const char *question,
430 uint8_t **question_ptr,
433 uint8_t *qb = *question_ptr;
436 n = ns_name_compress(question, qb, remaining, NULL, NULL);
438 RWRAP_LOG(RWRAP_LOG_ERROR,
439 "Failed to compress [%s]\n", question);
446 if (remaining < 2 * sizeof(uint16_t)) {
447 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small!\n");
452 NS_PUT16(ns_c_in, qb);
455 return n + 2 * sizeof(uint16_t);
458 static ssize_t rwrap_fake_rdata_common(uint16_t type,
464 uint8_t *rd = *rdata_ptr;
467 written = ns_name_compress(key, rd, remaining, NULL, NULL);
469 RWRAP_LOG(RWRAP_LOG_ERROR,
470 "Failed to compress [%s]\n", key);
474 remaining -= written;
476 if (remaining < 3 * sizeof(uint16_t) + sizeof(uint32_t)) {
477 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small\n");
482 NS_PUT16(ns_c_in, rd);
483 NS_PUT32(RWRAP_DEFAULT_FAKE_TTL, rd);
484 NS_PUT16(rdata_size, rd);
486 if (remaining < rdata_size) {
487 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small\n");
492 return written + 3 * sizeof(uint16_t) + sizeof(uint32_t) + rdata_size;
495 static ssize_t rwrap_fake_a(struct rwrap_fake_rr *rr,
499 uint8_t *a = answer_ptr;
502 if (rr->type != ns_t_a) {
503 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
506 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding A RR");
508 resp_size = rwrap_fake_rdata_common(ns_t_a, sizeof(struct in_addr), rr->key,
514 memcpy(a, &rr->rrdata.a_rec, sizeof(struct in_addr));
519 static ssize_t rwrap_fake_aaaa(struct rwrap_fake_rr *rr,
526 if (rr->type != ns_t_aaaa) {
527 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
530 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding AAAA RR");
532 resp_size = rwrap_fake_rdata_common(ns_t_aaaa, sizeof(struct in6_addr),
533 rr->key, anslen, &a);
538 memcpy(a, &rr->rrdata.aaaa_rec, sizeof(struct in6_addr));
543 static ssize_t rwrap_fake_ns(struct rwrap_fake_rr *rr,
548 ssize_t resp_size = 0;
550 unsigned char hostname_compressed[MAXDNAME];
551 ssize_t compressed_len;
553 if (rr->type != ns_t_ns) {
554 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
557 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding NS RR");
559 /* Prepare the data to write */
560 compressed_len = ns_name_compress(rr->rrdata.srv_rec.hostname,
565 if (compressed_len < 0) {
569 /* Is this enough? */
570 rdata_size = compressed_len;
572 resp_size = rwrap_fake_rdata_common(ns_t_ns, rdata_size,
573 rr->key, anslen, &a);
578 memcpy(a, hostname_compressed, compressed_len);
583 static ssize_t rwrap_fake_srv(struct rwrap_fake_rr *rr,
590 unsigned char hostname_compressed[MAXDNAME];
591 ssize_t compressed_len;
593 if (rr->type != ns_t_srv) {
594 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
597 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding SRV RR");
598 rdata_size = 3 * sizeof(uint16_t);
600 /* Prepare the data to write */
601 compressed_len = ns_name_compress(rr->rrdata.srv_rec.hostname,
602 hostname_compressed, MAXDNAME,
604 if (compressed_len < 0) {
607 rdata_size += compressed_len;
609 resp_size = rwrap_fake_rdata_common(ns_t_srv, rdata_size,
610 rr->key, anslen, &a);
615 NS_PUT16(rr->rrdata.srv_rec.prio, a);
616 NS_PUT16(rr->rrdata.srv_rec.weight, a);
617 NS_PUT16(rr->rrdata.srv_rec.port, a);
618 memcpy(a, hostname_compressed, compressed_len);
623 static ssize_t rwrap_fake_uri(struct rwrap_fake_rr *rr,
632 if (rr->type != ns_t_uri) {
633 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
636 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding URI RR");
637 rdata_size = 3 * sizeof(uint16_t);
638 uri_len = strlen(rr->rrdata.uri_rec.uri) + 1;
639 rdata_size += uri_len;
641 resp_size = rwrap_fake_rdata_common(ns_t_uri, rdata_size,
642 rr->key, anslen, &a);
647 NS_PUT16(rr->rrdata.uri_rec.prio, a);
648 NS_PUT16(rr->rrdata.uri_rec.weight, a);
649 memcpy(a, rr->rrdata.uri_rec.uri, uri_len);
654 static ssize_t rwrap_fake_soa(struct rwrap_fake_rr *rr,
661 unsigned char nameser_compressed[MAXDNAME];
662 ssize_t compressed_ns_len;
663 unsigned char mailbox_compressed[MAXDNAME];
664 ssize_t compressed_mb_len;
666 if (rr->type != ns_t_soa) {
667 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
670 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding SOA RR");
671 rdata_size = 5 * sizeof(uint16_t);
673 compressed_ns_len = ns_name_compress(rr->rrdata.soa_rec.nameserver,
675 MAXDNAME, NULL, NULL);
676 if (compressed_ns_len < 0) {
679 rdata_size += compressed_ns_len;
681 compressed_mb_len = ns_name_compress(rr->rrdata.soa_rec.mailbox,
683 MAXDNAME, NULL, NULL);
684 if (compressed_mb_len < 0) {
687 rdata_size += compressed_mb_len;
689 resp_size = rwrap_fake_rdata_common(ns_t_soa, rdata_size,
690 rr->key, anslen, &a);
695 memcpy(a, nameser_compressed, compressed_ns_len);
696 a += compressed_ns_len;
697 memcpy(a, mailbox_compressed, compressed_mb_len);
698 a += compressed_mb_len;
699 NS_PUT32(rr->rrdata.soa_rec.serial, a);
700 NS_PUT32(rr->rrdata.soa_rec.refresh, a);
701 NS_PUT32(rr->rrdata.soa_rec.retry, a);
702 NS_PUT32(rr->rrdata.soa_rec.expire, a);
703 NS_PUT32(rr->rrdata.soa_rec.minimum, a);
708 static ssize_t rwrap_fake_cname(struct rwrap_fake_rr *rr,
714 unsigned char hostname_compressed[MAXDNAME];
717 if (rr->type != ns_t_cname) {
718 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
721 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding CNAME RR");
723 /* Prepare the data to write */
724 rdata_size = ns_name_compress(rr->rrdata.cname_rec,
725 hostname_compressed, MAXDNAME,
727 if (rdata_size < 0) {
731 resp_size = rwrap_fake_rdata_common(ns_t_cname, rdata_size,
732 rr->key, anslen, &a);
737 memcpy(a, hostname_compressed, rdata_size);
742 static ssize_t rwrap_fake_ptr(struct rwrap_fake_rr *rr,
749 unsigned char hostname_compressed[MAXDNAME];
751 if (rr->type != ns_t_ptr) {
752 RWRAP_LOG(RWRAP_LOG_ERROR, "Wrong type!\n");
755 RWRAP_LOG(RWRAP_LOG_TRACE, "Adding PTR RR");
757 /* Prepare the data to write */
758 rdata_size = ns_name_compress(rr->rrdata.ptr_rec,
759 hostname_compressed, MAXDNAME,
761 if (rdata_size < 0) {
765 resp_size = rwrap_fake_rdata_common(ns_t_ptr, rdata_size,
766 rr->key, anslen, &a);
771 memcpy(a, hostname_compressed, rdata_size);
776 #define RESOLV_MATCH(line, name) \
777 (strncmp(line, name, sizeof(name) - 1) == 0 && \
778 (line[sizeof(name) - 1] == ' ' || \
779 line[sizeof(name) - 1] == '\t'))
781 #define TYPE_MATCH(type, ns_type, rec_type, str_type, key, query) \
782 ((type) == (ns_type) && \
783 (strncmp((rec_type), (str_type), sizeof(str_type)) == 0) && \
784 (strcasecmp(key, query)) == 0)
787 static int rwrap_get_record(const char *hostfile, unsigned recursion,
788 const char *query, int type,
789 struct rwrap_fake_rr *rr);
791 static int rwrap_uri_recurse(const char *hostfile, unsigned recursion,
792 const char *query, struct rwrap_fake_rr *rr)
796 rc = rwrap_get_record(hostfile, recursion, query, ns_t_uri, rr);
804 static int rwrap_srv_recurse(const char *hostfile, unsigned recursion,
805 const char *query, struct rwrap_fake_rr *rr)
809 rc = rwrap_get_record(hostfile, recursion, query, ns_t_a, rr);
810 if (rc == 0) return 0;
812 rc = rwrap_get_record(hostfile, recursion, query, ns_t_aaaa, rr);
813 if (rc == ENOENT) rc = 0;
818 static int rwrap_cname_recurse(const char *hostfile, unsigned recursion,
819 const char *query, struct rwrap_fake_rr *rr)
823 rc = rwrap_get_record(hostfile, recursion, query, ns_t_a, rr);
824 if (rc == 0) return 0;
826 rc = rwrap_get_record(hostfile, recursion, query, ns_t_aaaa, rr);
827 if (rc == 0) return 0;
829 rc = rwrap_get_record(hostfile, recursion, query, ns_t_cname, rr);
830 if (rc == ENOENT) rc = 0;
835 static int rwrap_get_record(const char *hostfile, unsigned recursion,
836 const char *query, int type,
837 struct rwrap_fake_rr *rr)
844 unsigned num_uris = 0;
846 if (recursion >= RWRAP_MAX_RECURSION) {
847 RWRAP_LOG(RWRAP_LOG_ERROR, "Recursed too deep!\n");
851 RWRAP_LOG(RWRAP_LOG_TRACE,
852 "Searching in fake hosts file %s for %s:%d\n", hostfile,
855 fp = fopen(hostfile, "r");
857 RWRAP_LOG(RWRAP_LOG_WARN,
858 "Opening %s failed: %s",
859 hostfile, strerror(errno));
863 while (fgets(buf, sizeof(buf), fp) != NULL) {
870 NEXT_KEY(rec_type, key);
871 NEXT_KEY(key, value);
873 if (key == NULL || value == NULL) {
874 RWRAP_LOG(RWRAP_LOG_WARN,
875 "Malformed line: not enough parts, use \"rec_type key data\n"
876 "For example \"A cwrap.org 10.10.10.10\"");
881 while(q[0] != '\n' && q[0] != '\0') {
886 if (type == ns_t_uri && recursion > 0) {
887 /* Skip non-URI records. */
888 if (!TYPE_MATCH(type, ns_t_uri, rec_type, "URI", key, query)) {
891 /* Skip previous records based on the recurse depth. */
893 if (num_uris <= recursion) {
898 if (TYPE_MATCH(type, ns_t_a, rec_type, "A", key, query)) {
899 rc = rwrap_create_fake_a_rr(key, value, rr);
901 } else if (TYPE_MATCH(type, ns_t_aaaa,
902 rec_type, "AAAA", key, query)) {
903 rc = rwrap_create_fake_aaaa_rr(key, value, rr);
905 } else if (TYPE_MATCH(type, ns_t_ns,
906 rec_type, "NS", key, query)) {
907 rc = rwrap_create_fake_ns_rr(key, value, rr);
909 } else if (TYPE_MATCH(type, ns_t_srv,
910 rec_type, "SRV", key, query)) {
911 rc = rwrap_create_fake_srv_rr(key, value, rr);
913 rc = rwrap_srv_recurse(hostfile, recursion+1,
914 rr->rrdata.srv_rec.hostname,
918 } else if (TYPE_MATCH(type, ns_t_uri,
919 rec_type, "URI", key, query)) {
920 rc = rwrap_create_fake_uri_rr(key, value, rr);
922 /* Recurse to collect multiple URI answers under a single key. */
923 rc = rwrap_uri_recurse(hostfile, recursion + 1, key, rr + 1);
926 } else if (TYPE_MATCH(type, ns_t_soa,
927 rec_type, "SOA", key, query)) {
928 rc = rwrap_create_fake_soa_rr(key, value, rr);
930 } else if (TYPE_MATCH(type, ns_t_cname,
931 rec_type, "CNAME", key, query)) {
932 rc = rwrap_create_fake_cname_rr(key, value, rr);
934 rc = rwrap_cname_recurse(hostfile, recursion+1,
938 } else if (TYPE_MATCH(type, ns_t_a, rec_type, "CNAME", key, query)) {
939 rc = rwrap_create_fake_cname_rr(key, value, rr);
941 rc = rwrap_cname_recurse(hostfile, recursion+1,
945 } else if (TYPE_MATCH(type, ns_t_ptr,
946 rec_type, "PTR", key, query)) {
947 rc = rwrap_create_fake_ptr_rr(key, value, rr);
952 if (rc == ENOENT && recursion == 0 && key != NULL) {
953 RWRAP_LOG(RWRAP_LOG_TRACE, "Record for [%s] not found\n", query);
954 memcpy(rr->key, key, strlen(key) + 1);
961 static ssize_t rwrap_fake_empty(int type,
962 const char *question,
967 size_t remaining = anslen;
969 resp_data = rwrap_fake_header(&answer, remaining, 0, 0);
973 remaining -= resp_data;
975 resp_data += rwrap_fake_question(question, type, &answer, remaining);
979 remaining -= resp_data;
981 resp_data += rwrap_fake_rdata_common(type, 0, question,
990 static inline bool rwrap_known_type(int type)
1007 static int rwrap_ancount(struct rwrap_fake_rr *rrs, int qtype)
1012 /* For URI return the number of URIs. */
1013 if (qtype == ns_t_uri) {
1014 for (i = 0; i < RWRAP_MAX_RECURSION; i++) {
1015 if (rwrap_known_type(rrs[i].type) &&
1016 rrs[i].type == qtype) {
1023 /* Include all RRs in the stack until the sought type
1024 * in the answer section. This is the case i.e. when looking
1025 * up an A record but the name points to a CNAME
1027 for (i = 0; i < RWRAP_MAX_RECURSION; i++) {
1030 if (rwrap_known_type(rrs[i].type) &&
1031 rrs[i].type == qtype) {
1036 /* Return 0 records if the sought type wasn't in the stack */
1037 return i < RWRAP_MAX_RECURSION ? ancount : 0;
1040 static int rwrap_arcount(struct rwrap_fake_rr *rrs, int ancount)
1045 /* start from index ancount */
1046 for (i = ancount; i < RWRAP_MAX_RECURSION; i++) {
1047 if (rwrap_known_type(rrs[i].type)) {
1055 static ssize_t rwrap_add_rr(struct rwrap_fake_rr *rr,
1062 RWRAP_LOG(RWRAP_LOG_ERROR, "Internal error!\n");
1068 resp_data = rwrap_fake_a(rr, answer, anslen);
1071 resp_data = rwrap_fake_aaaa(rr, answer, anslen);
1074 resp_data = rwrap_fake_ns(rr, answer, anslen);
1077 resp_data = rwrap_fake_srv(rr, answer, anslen);
1080 resp_data = rwrap_fake_uri(rr, answer, anslen);
1083 resp_data = rwrap_fake_soa(rr, answer, anslen);
1086 resp_data = rwrap_fake_cname(rr, answer, anslen);
1089 resp_data = rwrap_fake_ptr(rr, answer, anslen);
1098 static ssize_t rwrap_fake_answer(struct rwrap_fake_rr *rrs,
1106 size_t remaining = anslen;
1111 ancount = rwrap_ancount(rrs, type);
1112 arcount = rwrap_arcount(rrs, ancount);
1113 RWRAP_LOG(RWRAP_LOG_TRACE,
1114 "Got %d answers and %d additional records\n", ancount, arcount);
1116 resp_data = rwrap_fake_header(&answer, remaining, ancount, arcount);
1117 if (resp_data < 0) {
1120 remaining -= resp_data;
1122 resp_data += rwrap_fake_question(rrs->key, rrs->type, &answer, remaining);
1123 if (resp_data < 0) {
1126 remaining -= resp_data;
1129 for (i = 0; i < ancount; i++) {
1130 rrlen = rwrap_add_rr(&rrs[i], answer, remaining);
1139 /* add authoritative NS here? */
1141 /* additional records */
1142 for (i = ancount; i < ancount + arcount; i++) {
1143 rrlen = rwrap_add_rr(&rrs[i], answer, remaining);
1155 /* Reads in a file in the following format:
1158 * Malformed entries are silently skipped.
1159 * Allocates answer buffer of size anslen that has to be freed after use.
1161 static int rwrap_res_fake_hosts(const char *hostfile,
1164 unsigned char *answer,
1168 char *query_name = NULL;
1169 size_t qlen = strlen(query);
1170 struct rwrap_fake_rr rrs[RWRAP_MAX_RECURSION];
1173 RWRAP_LOG(RWRAP_LOG_TRACE,
1174 "Searching in fake hosts file %s\n", hostfile);
1176 if (qlen > 0 && query[qlen-1] == '.') {
1180 query_name = strndup(query, qlen);
1181 if (query_name == NULL) {
1185 rwrap_fake_rr_init(rrs, RWRAP_MAX_RECURSION);
1187 rc = rwrap_get_record(hostfile, 0, query_name, type, rrs);
1190 RWRAP_LOG(RWRAP_LOG_TRACE,
1191 "Found record for [%s]\n", query_name);
1192 resp_size = rwrap_fake_answer(rrs, type, answer, anslen);
1195 RWRAP_LOG(RWRAP_LOG_TRACE,
1196 "No record for [%s]\n", query_name);
1197 resp_size = rwrap_fake_empty(type, rrs->key, answer, anslen);
1200 RWRAP_LOG(RWRAP_LOG_NOTICE,
1201 "Searching for [%s] did not return any results\n",
1207 switch (resp_size) {
1209 RWRAP_LOG(RWRAP_LOG_ERROR,
1210 "Error faking answer for [%s]\n", query_name);
1213 RWRAP_LOG(RWRAP_LOG_TRACE,
1214 "Successfully faked answer for [%s]\n",
1223 /*********************************************************
1224 * RWRAP LOADING LIBC FUNCTIONS
1225 *********************************************************/
1229 typedef int (*__libc_res_ninit)(struct __res_state *state);
1230 typedef int (*__libc___res_ninit)(struct __res_state *state);
1231 typedef void (*__libc_res_nclose)(struct __res_state *state);
1232 typedef void (*__libc___res_nclose)(struct __res_state *state);
1233 typedef int (*__libc_res_nquery)(struct __res_state *state,
1237 unsigned char *answer,
1239 typedef int (*__libc___res_nquery)(struct __res_state *state,
1243 unsigned char *answer,
1245 typedef int (*__libc_res_nsearch)(struct __res_state *state,
1249 unsigned char *answer,
1251 typedef int (*__libc___res_nsearch)(struct __res_state *state,
1255 unsigned char *answer,
1258 #define RWRAP_SYMBOL_ENTRY(i) \
1264 struct rwrap_libc_symbols {
1265 RWRAP_SYMBOL_ENTRY(res_ninit);
1266 RWRAP_SYMBOL_ENTRY(__res_ninit);
1267 RWRAP_SYMBOL_ENTRY(res_nclose);
1268 RWRAP_SYMBOL_ENTRY(__res_nclose);
1269 RWRAP_SYMBOL_ENTRY(res_nquery);
1270 RWRAP_SYMBOL_ENTRY(__res_nquery);
1271 RWRAP_SYMBOL_ENTRY(res_nsearch);
1272 RWRAP_SYMBOL_ENTRY(__res_nsearch);
1274 #undef RWRAP_SYMBOL_ENTRY
1279 struct rwrap_libc_symbols symbols;
1284 struct rwrap_libc_symbols symbols;
1293 static struct rwrap rwrap;
1300 static const char *rwrap_str_lib(enum rwrap_lib lib)
1305 case RWRAP_LIBRESOLV:
1309 /* Compiler would warn us about unhandled enum value if we get here */
1313 static void *rwrap_load_lib_handle(enum rwrap_lib lib)
1315 int flags = RTLD_LAZY;
1316 void *handle = NULL;
1319 #ifdef RTLD_DEEPBIND
1320 const char *env_preload = getenv("LD_PRELOAD");
1321 const char *env_deepbind = getenv("RESOLV_WRAPPER_DISABLE_DEEPBIND");
1322 bool enable_deepbind = true;
1324 /* Don't do a deepbind if we run with libasan */
1325 if (env_preload != NULL && strlen(env_preload) < 1024) {
1326 const char *p = strstr(env_preload, "libasan.so");
1328 enable_deepbind = false;
1332 if (env_deepbind != NULL && strlen(env_deepbind) >= 1) {
1333 enable_deepbind = false;
1336 if (enable_deepbind) {
1337 flags |= RTLD_DEEPBIND;
1342 case RWRAP_LIBRESOLV:
1343 #ifdef HAVE_LIBRESOLV
1344 handle = rwrap.libresolv.handle;
1345 if (handle == NULL) {
1346 for (i = 10; i >= 0; i--) {
1347 char soname[256] = {0};
1349 snprintf(soname, sizeof(soname), "libresolv.so.%d", i);
1350 handle = dlopen(soname, flags);
1351 if (handle != NULL) {
1356 rwrap.libresolv.handle = handle;
1362 handle = rwrap.libc.handle;
1364 if (handle == NULL) {
1365 handle = dlopen(LIBC_SO, flags);
1367 rwrap.libc.handle = handle;
1370 if (handle == NULL) {
1371 for (i = 10; i >= 0; i--) {
1372 char soname[256] = {0};
1374 snprintf(soname, sizeof(soname), "libc.so.%d", i);
1375 handle = dlopen(soname, flags);
1376 if (handle != NULL) {
1381 rwrap.libc.handle = handle;
1386 if (handle == NULL) {
1388 handle = rwrap.libc.handle = rwrap.libresolv.handle = RTLD_NEXT;
1390 RWRAP_LOG(RWRAP_LOG_ERROR,
1391 "Failed to dlopen library: %s\n",
1400 static void *_rwrap_bind_symbol(enum rwrap_lib lib, const char *fn_name)
1405 handle = rwrap_load_lib_handle(lib);
1407 func = dlsym(handle, fn_name);
1409 RWRAP_LOG(RWRAP_LOG_ERROR,
1410 "Failed to find %s: %s\n",
1411 fn_name, dlerror());
1415 RWRAP_LOG(RWRAP_LOG_TRACE,
1416 "Loaded %s from %s",
1417 fn_name, rwrap_str_lib(lib));
1421 #define rwrap_bind_symbol_libc(sym_name) \
1422 if (rwrap.libc.symbols._libc_##sym_name.obj == NULL) { \
1423 rwrap.libc.symbols._libc_##sym_name.obj = \
1424 _rwrap_bind_symbol(RWRAP_LIBC, #sym_name); \
1427 #define rwrap_bind_symbol_libresolv(sym_name) \
1428 if (rwrap.libresolv.symbols._libc_##sym_name.obj == NULL) { \
1429 rwrap.libresolv.symbols._libc_##sym_name.obj = \
1430 _rwrap_bind_symbol(RWRAP_LIBRESOLV, #sym_name); \
1436 * Functions especially from libc need to be loaded individually, you can't load
1437 * all at once or gdb will segfault at startup. The same applies to valgrind and
1438 * has probably something todo with with the linker.
1439 * So we need load each function at the point it is called the first time.
1442 static int libc_res_ninit(struct __res_state *state)
1444 #if !defined(res_ninit) && defined(HAVE_RES_NINIT)
1446 #if defined(HAVE_RES_NINIT_IN_LIBRESOLV)
1447 rwrap_bind_symbol_libresolv(res_ninit);
1449 return rwrap.libresolv.symbols._libc_res_ninit.f(state);
1450 #else /* HAVE_RES_NINIT_IN_LIBRESOLV */
1451 rwrap_bind_symbol_libc(res_ninit);
1453 return rwrap.libc.symbols._libc_res_ninit.f(state);
1454 #endif /* HAVE_RES_NINIT_IN_LIBRESOLV */
1456 #elif defined(HAVE___RES_NINIT)
1457 rwrap_bind_symbol_libc(__res_ninit);
1459 return rwrap.libc.symbols._libc___res_ninit.f(state);
1461 #error "No res_ninit function"
1465 static void libc_res_nclose(struct __res_state *state)
1467 #if !defined(res_close) && defined(HAVE_RES_NCLOSE)
1469 #if defined(HAVE_RES_NCLOSE_IN_LIBRESOLV)
1470 rwrap_bind_symbol_libresolv(res_nclose);
1472 rwrap.libresolv.symbols._libc_res_nclose.f(state);
1474 #else /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
1475 rwrap_bind_symbol_libc(res_nclose);
1477 rwrap.libc.symbols._libc_res_nclose.f(state);
1479 #endif /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
1481 #elif defined(HAVE___RES_NCLOSE)
1482 rwrap_bind_symbol_libc(__res_nclose);
1484 rwrap.libc.symbols._libc___res_nclose.f(state);
1486 #error "No res_nclose function"
1490 static int libc_res_nquery(struct __res_state *state,
1494 unsigned char *answer,
1497 #if !defined(res_nquery) && defined(HAVE_RES_NQUERY)
1498 rwrap_bind_symbol_libresolv(res_nquery);
1500 return rwrap.libresolv.symbols._libc_res_nquery.f(state,
1506 #elif defined(HAVE___RES_NQUERY)
1507 rwrap_bind_symbol_libresolv(__res_nquery);
1509 return rwrap.libresolv.symbols._libc___res_nquery.f(state,
1516 #error "No res_nquery function"
1520 static int libc_res_nsearch(struct __res_state *state,
1524 unsigned char *answer,
1527 #if !defined(res_nsearch) && defined(HAVE_RES_NSEARCH)
1528 rwrap_bind_symbol_libresolv(res_nsearch);
1530 return rwrap.libresolv.symbols._libc_res_nsearch.f(state,
1536 #elif defined(HAVE___RES_NSEARCH)
1537 rwrap_bind_symbol_libresolv(__res_nsearch);
1539 return rwrap.libresolv.symbols._libc___res_nsearch.f(state,
1546 #error "No res_nsearch function"
1550 /****************************************************************************
1552 ***************************************************************************/
1554 static int rwrap_parse_resolv_conf(struct __res_state *state,
1555 const char *resolv_conf)
1561 fp = fopen(resolv_conf, "r");
1563 RWRAP_LOG(RWRAP_LOG_ERROR,
1564 "Opening %s failed: %s",
1565 resolv_conf, strerror(errno));
1569 while(fgets(buf, sizeof(buf), fp) != NULL) {
1572 /* Ignore comments */
1573 if (buf[0] == '#' || buf[0] == ';') {
1577 if (RESOLV_MATCH(buf, "nameserver") && nserv < MAXNS) {
1582 p = buf + strlen("nameserver");
1584 /* Skip spaces and tabs */
1585 while(isblank((int)p[0])) {
1590 while(q[0] != '\n' && q[0] != '\0') {
1595 ok = inet_pton(AF_INET, p, &a);
1597 state->nsaddr_list[state->nscount] = (struct sockaddr_in) {
1598 .sin_family = AF_INET,
1600 .sin_port = htons(53),
1607 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1610 ok = inet_pton(AF_INET6, p, &a6);
1612 struct sockaddr_in6 *sa6;
1614 sa6 = malloc(sizeof(*sa6));
1620 sa6->sin6_family = AF_INET6;
1621 sa6->sin6_port = htons(53);
1622 sa6->sin6_flowinfo = 0;
1623 sa6->sin6_addr = a6;
1625 state->_u._ext.nsaddrs[state->_u._ext.nscount] = sa6;
1626 state->_u._ext.nssocks[state->_u._ext.nscount] = -1;
1627 state->_u._ext.nsmap[state->_u._ext.nscount] = MAXNS + 1;
1629 state->_u._ext.nscount++;
1632 RWRAP_LOG(RWRAP_LOG_ERROR,
1633 "Malformed DNS server");
1636 #else /* !HAVE_RESOLV_IPV6_NSADDRS */
1638 * BSD uses an opaque structure to store the
1639 * IPv6 addresses. So we can not simply store
1640 * these addresses the same way as above.
1642 RWRAP_LOG(RWRAP_LOG_WARN,
1643 "resolve_wrapper does not support "
1644 "IPv6 on this platform");
1649 } /* TODO: match other keywords */
1653 RWRAP_LOG(RWRAP_LOG_ERROR,
1654 "Reading from %s failed",
1664 /****************************************************************************
1666 ***************************************************************************/
1668 static int rwrap_res_ninit(struct __res_state *state)
1672 rc = libc_res_ninit(state);
1674 const char *resolv_conf = getenv("RESOLV_WRAPPER_CONF");
1676 if (resolv_conf != NULL) {
1679 (void)i; /* maybe unused */
1681 /* Delete name servers */
1683 memset(state->nsaddr_list, 0, sizeof(state->nsaddr_list));
1685 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1686 state->_u._ext.nscount = 0;
1687 for (i = 0; i < state->_u._ext.nscount; i++) {
1688 SAFE_FREE(state->_u._ext.nsaddrs[i]);
1692 rc = rwrap_parse_resolv_conf(state, resolv_conf);
1699 #if !defined(res_ninit) && defined(HAVE_RES_NINIT)
1700 int res_ninit(struct __res_state *state)
1701 #elif defined(HAVE___RES_NINIT)
1702 int __res_ninit(struct __res_state *state)
1705 return rwrap_res_ninit(state);
1708 /****************************************************************************
1710 ***************************************************************************/
1712 static struct __res_state rwrap_res_state;
1714 static int rwrap_res_init(void)
1718 rc = rwrap_res_ninit(&rwrap_res_state);
1723 #if !defined(res_ninit) && defined(HAVE_RES_INIT)
1725 #elif defined(HAVE___RES_INIT)
1726 int __res_init(void)
1729 return rwrap_res_init();
1732 /****************************************************************************
1734 ***************************************************************************/
1736 static void rwrap_res_nclose(struct __res_state *state)
1738 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1742 libc_res_nclose(state);
1744 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1745 if (state != NULL) {
1746 for (i = 0; i < state->_u._ext.nscount; i++) {
1747 SAFE_FREE(state->_u._ext.nsaddrs[i]);
1753 #if !defined(res_nclose) && defined(HAVE_RES_NCLOSE)
1754 void res_nclose(struct __res_state *state)
1755 #elif defined(HAVE___RES_NCLOSE)
1756 void __res_nclose(struct __res_state *state)
1759 rwrap_res_nclose(state);
1762 /****************************************************************************
1764 ***************************************************************************/
1766 static void rwrap_res_close(void)
1768 rwrap_res_nclose(&rwrap_res_state);
1771 #if defined(HAVE_RES_CLOSE)
1772 void res_close(void)
1773 #elif defined(HAVE___RES_CLOSE)
1774 void __res_close(void)
1780 /****************************************************************************
1782 ***************************************************************************/
1784 static int rwrap_res_nquery(struct __res_state *state,
1788 unsigned char *answer,
1792 const char *fake_hosts;
1797 RWRAP_LOG(RWRAP_LOG_TRACE,
1798 "Resolve the domain name [%s] - class=%d, type=%d",
1799 dname, class, type);
1801 for (i = 0; i < state->nscount; i++) {
1802 char ip[INET6_ADDRSTRLEN];
1804 inet_ntop(AF_INET, &state->nsaddr_list[i].sin_addr, ip, sizeof(ip));
1805 RWRAP_LOG(RWRAP_LOG_TRACE,
1811 fake_hosts = getenv("RESOLV_WRAPPER_HOSTS");
1812 if (fake_hosts != NULL) {
1813 rc = rwrap_res_fake_hosts(fake_hosts, dname, type, answer, anslen);
1815 rc = libc_res_nquery(state, dname, class, type, answer, anslen);
1819 RWRAP_LOG(RWRAP_LOG_TRACE,
1820 "The returned response length is: %d",
1826 #if !defined(res_nquery) && defined(HAVE_RES_NQUERY)
1827 int res_nquery(struct __res_state *state,
1831 unsigned char *answer,
1833 #elif defined(HAVE___RES_NQUERY)
1834 int __res_nquery(struct __res_state *state,
1838 unsigned char *answer,
1842 return rwrap_res_nquery(state, dname, class, type, answer, anslen);
1845 /****************************************************************************
1847 ***************************************************************************/
1849 static int rwrap_res_query(const char *dname,
1852 unsigned char *answer,
1857 rc = rwrap_res_ninit(&rwrap_res_state);
1862 rc = rwrap_res_nquery(&rwrap_res_state,
1872 #if !defined(res_query) && defined(HAVE_RES_QUERY)
1873 int res_query(const char *dname,
1876 unsigned char *answer,
1878 #elif defined(HAVE___RES_QUERY)
1879 int __res_query(const char *dname,
1882 unsigned char *answer,
1886 return rwrap_res_query(dname, class, type, answer, anslen);
1889 /****************************************************************************
1891 ***************************************************************************/
1893 static int rwrap_res_nsearch(struct __res_state *state,
1897 unsigned char *answer,
1901 const char *fake_hosts;
1906 RWRAP_LOG(RWRAP_LOG_TRACE,
1907 "Resolve the domain name [%s] - class=%d, type=%d",
1908 dname, class, type);
1910 for (i = 0; i < state->nscount; i++) {
1911 char ip[INET6_ADDRSTRLEN];
1913 inet_ntop(AF_INET, &state->nsaddr_list[i].sin_addr, ip, sizeof(ip));
1914 RWRAP_LOG(RWRAP_LOG_TRACE,
1920 fake_hosts = getenv("RESOLV_WRAPPER_HOSTS");
1921 if (fake_hosts != NULL) {
1922 rc = rwrap_res_fake_hosts(fake_hosts, dname, type, answer, anslen);
1924 rc = libc_res_nsearch(state, dname, class, type, answer, anslen);
1927 RWRAP_LOG(RWRAP_LOG_TRACE,
1928 "The returned response length is: %d",
1934 #if !defined(res_nsearch) && defined(HAVE_RES_NSEARCH)
1935 int res_nsearch(struct __res_state *state,
1939 unsigned char *answer,
1941 #elif defined(HAVE___RES_NSEARCH)
1942 int __res_nsearch(struct __res_state *state,
1946 unsigned char *answer,
1950 return rwrap_res_nsearch(state, dname, class, type, answer, anslen);
1953 /****************************************************************************
1955 ***************************************************************************/
1957 static int rwrap_res_search(const char *dname,
1960 unsigned char *answer,
1965 rc = rwrap_res_ninit(&rwrap_res_state);
1970 rc = rwrap_res_nsearch(&rwrap_res_state,
1980 #if !defined(res_search) && defined(HAVE_RES_SEARCH)
1981 int res_search(const char *dname,
1984 unsigned char *answer,
1986 #elif defined(HAVE___RES_SEARCH)
1987 int __res_search(const char *dname,
1990 unsigned char *answer,
1994 return rwrap_res_search(dname, class, type, answer, anslen);