Refactor the dns_open_connection code so that duplicate code is removed and ensure...
[sfrench/samba-autobuild/.git] / lib / resolv_wrapper / resolv_wrapper.c
1 /*
2  * Copyright (c) 2014      Andreas Schneider <asn@samba.org>
3  * Copyright (c) 2014      Jakub Hrozek <jakub.hrozek@gmail.com>
4  *
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
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.
17  *
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.
21  *
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
32  * SUCH DAMAGE.
33  */
34
35 #include "config.h"
36
37 #include <errno.h>
38 #include <arpa/inet.h>
39 #include <netinet/in.h>
40 #include <sys/types.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <stdbool.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <ctype.h>
48
49 #include <resolv.h>
50
51 /* GCC has printf type attribute check. */
52 #ifdef HAVE_ATTRIBUTE_PRINTF_FORMAT
53 #define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
54 #else
55 #define PRINTF_ATTRIBUTE(a,b)
56 #endif /* HAVE_ATTRIBUTE_PRINTF_FORMAT */
57
58 #ifdef HAVE_DESTRUCTOR_ATTRIBUTE
59 #define DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor))
60 #else
61 #define DESTRUCTOR_ATTRIBUTE
62 #endif /* HAVE_DESTRUCTOR_ATTRIBUTE */
63
64 #ifndef RWRAP_DEFAULT_FAKE_TTL
65 #define RWRAP_DEFAULT_FAKE_TTL 600
66 #endif  /* RWRAP_DEFAULT_FAKE_TTL */
67
68 #ifndef HAVE_NS_NAME_COMPRESS
69 #define ns_name_compress dn_comp
70 #endif
71
72 enum rwrap_dbglvl_e {
73         RWRAP_LOG_ERROR = 0,
74         RWRAP_LOG_WARN,
75         RWRAP_LOG_DEBUG,
76         RWRAP_LOG_TRACE
77 };
78
79 #ifdef NDEBUG
80 # define RWRAP_LOG(...)
81 #else /* NDEBUG */
82
83 static void rwrap_log(enum rwrap_dbglvl_e dbglvl, const char *func, const char *format, ...) PRINTF_ATTRIBUTE(3, 4);
84 # define RWRAP_LOG(dbglvl, ...) rwrap_log((dbglvl), __func__, __VA_ARGS__)
85
86 static void rwrap_log(enum rwrap_dbglvl_e dbglvl,
87                       const char *func,
88                       const char *format, ...)
89 {
90         char buffer[1024];
91         va_list va;
92         const char *d;
93         unsigned int lvl = 0;
94         int pid = getpid();
95
96         d = getenv("RESOLV_WRAPPER_DEBUGLEVEL");
97         if (d != NULL) {
98                 lvl = atoi(d);
99         }
100
101         va_start(va, format);
102         vsnprintf(buffer, sizeof(buffer), format, va);
103         va_end(va);
104
105         if (lvl >= dbglvl) {
106                 switch (dbglvl) {
107                         case RWRAP_LOG_ERROR:
108                                 fprintf(stderr,
109                                         "RWRAP_ERROR(%d) - %s: %s\n",
110                                         pid, func, buffer);
111                                 break;
112                         case RWRAP_LOG_WARN:
113                                 fprintf(stderr,
114                                         "RWRAP_WARN(%d) - %s: %s\n",
115                                         pid, func, buffer);
116                                 break;
117                         case RWRAP_LOG_DEBUG:
118                                 fprintf(stderr,
119                                         "RWRAP_DEBUG(%d) - %s: %s\n",
120                                         pid, func, buffer);
121                                 break;
122                         case RWRAP_LOG_TRACE:
123                                 fprintf(stderr,
124                                         "RWRAP_TRACE(%d) - %s: %s\n",
125                                         pid, func, buffer);
126                                 break;
127                 }
128         }
129 }
130 #endif /* NDEBUG RWRAP_LOG */
131
132 #ifndef SAFE_FREE
133 #define SAFE_FREE(x) do { if ((x) != NULL) {free(x); (x)=NULL;} } while(0)
134 #endif
135
136 #define NEXT_KEY(buf, key) do {                                 \
137         (key) = (buf) ? strpbrk((buf), " \t") : NULL;           \
138         if ((key) != NULL) {                                    \
139                 (key)[0] = '\0';                                \
140                 (key)++;                                        \
141         }                                                       \
142         while ((key) != NULL                                    \
143                && (isblank((int)(key)[0]))) {                   \
144                 (key)++;                                        \
145         }                                                       \
146 } while(0);
147
148 #define RWRAP_MAX_RECURSION 5
149
150 /* Priority and weight can be omitted from the hosts file, but need to be part
151  * of the output
152  */
153 #define DFL_SRV_PRIO    1
154 #define DFL_SRV_WEIGHT  100
155
156 struct rwrap_srv_rrdata {
157         uint16_t port;
158         uint16_t prio;
159         uint16_t weight;
160         char hostname[MAXDNAME];
161 };
162
163 struct rwrap_soa_rrdata {
164         uint32_t serial;
165         uint32_t refresh;
166         uint32_t retry;
167         uint32_t expire;
168         uint32_t minimum;
169         char nameserver[MAXDNAME];
170         char mailbox[MAXDNAME];
171 };
172
173 struct rwrap_fake_rr {
174         union fake_rrdata {
175                 struct in_addr a_rec;
176                 struct in6_addr aaaa_rec;
177                 struct rwrap_srv_rrdata srv_rec;
178                 struct rwrap_soa_rrdata soa_rec;
179                 char cname_rec[MAXDNAME];
180         } rrdata;
181
182         char key[MAXDNAME];
183         int type; /* ns_t_* */
184 };
185
186 static void rwrap_fake_rr_init(struct rwrap_fake_rr *rr, size_t len)
187 {
188         size_t i;
189
190         for (i = 0; i < len; i++) {
191                 rr[i].type = ns_t_invalid;
192         }
193 }
194
195 static int rwrap_create_fake_a_rr(const char *key,
196                                   const char *value,
197                                   struct rwrap_fake_rr *rr)
198 {
199         int ok;
200
201         ok = inet_pton(AF_INET, value, &rr->rrdata.a_rec);
202         if (!ok) {
203                 RWRAP_LOG(RWRAP_LOG_ERROR,
204                           "Failed to convert [%s] to binary\n", value);
205                 return -1;
206         }
207
208         memcpy(rr->key, key, strlen(key) + 1);
209         rr->type = ns_t_a;
210         return 0;
211 }
212
213 static int rwrap_create_fake_aaaa_rr(const char *key,
214                                      const char *value,
215                                      struct rwrap_fake_rr *rr)
216 {
217         int ok;
218
219         ok = inet_pton(AF_INET6, value, &rr->rrdata.aaaa_rec);
220         if (!ok) {
221                 RWRAP_LOG(RWRAP_LOG_ERROR,
222                           "Failed to convert [%s] to binary\n", value);
223                 return -1;
224         }
225
226         memcpy(rr->key, key, strlen(key) + 1);
227         rr->type = ns_t_aaaa;
228         return 0;
229 }
230
231 static int rwrap_create_fake_srv_rr(const char *key,
232                                     const char *value,
233                                     struct rwrap_fake_rr *rr)
234 {
235         char *str_prio;
236         char *str_weight;
237         char *str_port;
238         const char *hostname;
239
240         /* parse the value into priority, weight, port and hostname
241          * and check the validity */
242         hostname = value;
243         NEXT_KEY(hostname, str_port);
244         NEXT_KEY(str_port, str_prio);
245         NEXT_KEY(str_prio, str_weight);
246         if (str_port == NULL || hostname == NULL) {
247                 RWRAP_LOG(RWRAP_LOG_ERROR,
248                           "Malformed SRV entry [%s]\n", value);
249                 return -1;
250         }
251
252         if (str_prio) {
253                 rr->rrdata.srv_rec.prio = atoi(str_prio);
254         } else {
255                 rr->rrdata.srv_rec.prio = DFL_SRV_PRIO;
256         }
257         if (str_weight) {
258                 rr->rrdata.srv_rec.weight = atoi(str_weight);
259         } else {
260                 rr->rrdata.srv_rec.weight = DFL_SRV_WEIGHT;
261         }
262         rr->rrdata.srv_rec.port = atoi(str_port);
263         memcpy(rr->rrdata.srv_rec.hostname , hostname, strlen(hostname) + 1);
264
265         memcpy(rr->key, key, strlen(key) + 1);
266         rr->type = ns_t_srv;
267         return 0;
268 }
269
270 static int rwrap_create_fake_soa_rr(const char *key,
271                                     const char *value,
272                                     struct rwrap_fake_rr *rr)
273 {
274         const char *nameserver;
275         char *mailbox;
276         char *str_serial;
277         char *str_refresh;
278         char *str_retry;
279         char *str_expire;
280         char *str_minimum;
281
282         /* parse the value into nameserver, mailbox, serial, refresh,
283          * retry, expire, minimum and check the validity
284          */
285         nameserver = value;
286         NEXT_KEY(nameserver, mailbox);
287         NEXT_KEY(mailbox, str_serial);
288         NEXT_KEY(str_serial, str_refresh);
289         NEXT_KEY(str_refresh, str_retry);
290         NEXT_KEY(str_retry, str_expire);
291         NEXT_KEY(str_expire, str_minimum);
292         if (nameserver == NULL || mailbox == NULL || str_serial == NULL ||
293             str_refresh == NULL || str_retry == NULL || str_expire == NULL ||
294             str_minimum == NULL) {
295                 RWRAP_LOG(RWRAP_LOG_ERROR,
296                           "Malformed SOA entry [%s]\n", value);
297                 return -1;
298         }
299
300         memcpy(rr->rrdata.soa_rec.nameserver, nameserver, strlen(nameserver)+1);
301         memcpy(rr->rrdata.soa_rec.mailbox, mailbox, strlen(mailbox)+1);
302
303         rr->rrdata.soa_rec.serial = atoi(str_serial);
304         rr->rrdata.soa_rec.refresh = atoi(str_refresh);
305         rr->rrdata.soa_rec.retry = atoi(str_retry);
306         rr->rrdata.soa_rec.expire = atoi(str_expire);
307         rr->rrdata.soa_rec.minimum = atoi(str_minimum);
308
309         memcpy(rr->key, key, strlen(key) + 1);
310         rr->type = ns_t_soa;
311         return 0;
312 }
313
314 static int rwrap_create_fake_cname_rr(const char *key,
315                                       const char *value,
316                                       struct rwrap_fake_rr *rr)
317 {
318         memcpy(rr->rrdata.cname_rec , value, strlen(value) + 1);
319         memcpy(rr->key, key, strlen(key) + 1);
320         rr->type = ns_t_cname;
321         return 0;
322 }
323
324 /* Prepares a fake header with a single response. Advances header_blob */
325 static ssize_t rwrap_fake_header(uint8_t **header_blob, size_t remaining,
326                                  size_t ancount, size_t arcount)
327 {
328         uint8_t *hb;
329         HEADER *h;
330
331         if (remaining < NS_HFIXEDSZ) {
332                 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small!\n");
333                 return -1;
334         }
335
336         hb = *header_blob;
337         memset(hb, 0, NS_HFIXEDSZ);
338
339         h = (HEADER *) hb;
340         h->id = res_randomid();         /* random query ID */
341         h->qr = 1;                      /* response flag */
342         h->rd = 1;                      /* recursion desired */
343         h->ra = 1;                      /* resursion available */
344
345         h->qdcount = htons(1);          /* no. of questions */
346         h->ancount = htons(ancount);    /* no. of answers */
347         h->arcount = htons(arcount);    /* no. of add'tl records */
348
349         hb += NS_HFIXEDSZ;              /* move past the header */
350         *header_blob = hb;
351
352         return NS_HFIXEDSZ;
353 }
354
355 static ssize_t rwrap_fake_question(const char *question,
356                                    uint16_t type,
357                                    uint8_t **question_ptr,
358                                    size_t remaining)
359 {
360         uint8_t *qb = *question_ptr;
361         int n;
362
363         n = ns_name_compress(question, qb, remaining, NULL, NULL);
364         if (n < 0) {
365                 RWRAP_LOG(RWRAP_LOG_ERROR,
366                           "Failed to compress [%s]\n", question);
367                 return -1;
368         }
369
370         qb += n;
371         remaining -= n;
372
373         if (remaining < 2 * sizeof(uint16_t)) {
374                 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small!\n");
375                 return -1;
376         }
377
378         NS_PUT16(type, qb);
379         NS_PUT16(ns_c_in, qb);
380
381         *question_ptr = qb;
382         return n + 2 * sizeof(uint16_t);
383 }
384
385 static ssize_t rwrap_fake_rdata_common(uint16_t type,
386                                        size_t rdata_size,
387                                        const char *key,
388                                        size_t remaining,
389                                        uint8_t **rdata_ptr)
390 {
391         uint8_t *rd = *rdata_ptr;
392         ssize_t written = 0;
393
394         written = ns_name_compress(key, rd, remaining, NULL, NULL);
395         if (written < 0) {
396                 RWRAP_LOG(RWRAP_LOG_ERROR,
397                           "Failed to compress [%s]\n", key);
398                 return -1;
399         }
400         rd += written;
401         remaining -= written;
402
403         if (remaining < 3 * sizeof(uint16_t) + sizeof(uint32_t)) {
404                 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small\n");
405                 return -1;
406         }
407
408         NS_PUT16(type, rd);
409         NS_PUT16(ns_c_in, rd);
410         NS_PUT32(RWRAP_DEFAULT_FAKE_TTL, rd);
411         NS_PUT16(rdata_size, rd);
412
413         if (remaining < rdata_size) {
414                 RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small\n");
415                 return -1;
416         }
417
418         *rdata_ptr = rd;
419         return written + 3 * sizeof(uint16_t) + sizeof(uint32_t) + rdata_size;
420 }
421
422 static ssize_t rwrap_fake_a(struct rwrap_fake_rr *rr,
423                             uint8_t *answer_ptr,
424                             size_t anslen)
425 {
426         uint8_t *a = answer_ptr;
427         ssize_t resp_size;
428
429         if (rr == NULL || rr->type != ns_t_a) {
430                 RWRAP_LOG(RWRAP_LOG_ERROR,
431                           "Malformed record, no or wrong value!\n");
432                 return -1;
433         }
434         RWRAP_LOG(RWRAP_LOG_TRACE, "Adding A RR");
435
436         resp_size = rwrap_fake_rdata_common(ns_t_a, sizeof(struct in_addr), rr->key,
437                                             anslen, &a);
438         if (resp_size < 0) {
439                 return -1;
440         }
441
442         memcpy(a, &rr->rrdata.a_rec, sizeof(struct in_addr));
443
444         return resp_size;
445 }
446
447 static ssize_t rwrap_fake_aaaa(struct rwrap_fake_rr *rr,
448                                uint8_t *answer,
449                                size_t anslen)
450 {
451         uint8_t *a = answer;
452         ssize_t resp_size;
453
454         if (rr == NULL || rr->type != ns_t_aaaa) {
455                 RWRAP_LOG(RWRAP_LOG_ERROR,
456                           "Malformed record, no or wrong value!\n");
457                 return -1;
458         }
459         RWRAP_LOG(RWRAP_LOG_TRACE, "Adding AAAA RR");
460
461         resp_size = rwrap_fake_rdata_common(ns_t_aaaa, sizeof(struct in6_addr),
462                                             rr->key, anslen, &a);
463         if (resp_size < 0) {
464                 return -1;
465         }
466
467         memcpy(a, &rr->rrdata.aaaa_rec, sizeof(struct in6_addr));
468
469         return resp_size;
470 }
471
472 static ssize_t rwrap_fake_srv(struct rwrap_fake_rr *rr,
473                               uint8_t *answer,
474                               size_t anslen)
475 {
476         uint8_t *a = answer;
477         ssize_t resp_size;
478         size_t rdata_size;
479         unsigned char hostname_compressed[MAXDNAME];
480         ssize_t compressed_len;
481
482         if (rr == NULL || rr->type != ns_t_srv) {
483                 RWRAP_LOG(RWRAP_LOG_ERROR,
484                           "Malformed record, no or wrong value!\n");
485                 return -1;
486         }
487         RWRAP_LOG(RWRAP_LOG_TRACE, "Adding SRV RR");
488         rdata_size = 3 * sizeof(uint16_t);
489
490         /* Prepare the data to write */
491         compressed_len = ns_name_compress(rr->rrdata.srv_rec.hostname,
492                                           hostname_compressed, MAXDNAME,
493                                           NULL, NULL);
494         if (compressed_len < 0) {
495                 return -1;
496         }
497         rdata_size += compressed_len;
498
499         resp_size = rwrap_fake_rdata_common(ns_t_srv, rdata_size,
500                                             rr->key, anslen, &a);
501         if (resp_size < 0) {
502                 return -1;
503         }
504
505         NS_PUT16(rr->rrdata.srv_rec.prio, a);
506         NS_PUT16(rr->rrdata.srv_rec.weight, a);
507         NS_PUT16(rr->rrdata.srv_rec.port, a);
508         memcpy(a, hostname_compressed, compressed_len);
509
510         return resp_size;
511 }
512
513 static ssize_t rwrap_fake_soa(struct rwrap_fake_rr *rr,
514                               uint8_t *answer,
515                               size_t anslen)
516 {
517         uint8_t *a = answer;
518         ssize_t resp_size;
519         size_t rdata_size;
520         unsigned char nameser_compressed[MAXDNAME];
521         ssize_t compressed_ns_len;
522         unsigned char mailbox_compressed[MAXDNAME];
523         ssize_t compressed_mb_len;
524
525         if (rr == NULL || rr->type != ns_t_soa) {
526                 RWRAP_LOG(RWRAP_LOG_ERROR,
527                           "Malformed record, no or wrong value!\n");
528                 return -1;
529         }
530         RWRAP_LOG(RWRAP_LOG_TRACE, "Adding SOA RR");
531         rdata_size = 5 * sizeof(uint16_t);
532
533         compressed_ns_len = ns_name_compress(rr->rrdata.soa_rec.nameserver,
534                                              nameser_compressed,
535                                              MAXDNAME, NULL, NULL);
536         if (compressed_ns_len < 0) {
537                 return -1;
538         }
539         rdata_size += compressed_ns_len;
540
541         compressed_mb_len = ns_name_compress(rr->rrdata.soa_rec.mailbox,
542                                              mailbox_compressed,
543                                              MAXDNAME, NULL, NULL);
544         if (compressed_mb_len < 0) {
545                 return -1;
546         }
547         rdata_size += compressed_mb_len;
548
549         resp_size = rwrap_fake_rdata_common(ns_t_soa, rdata_size,
550                                             rr->key, anslen, &a);
551         if (resp_size < 0) {
552                 return -1;
553         }
554
555         memcpy(a, nameser_compressed, compressed_ns_len);
556         a += compressed_ns_len;
557         memcpy(a, mailbox_compressed, compressed_mb_len);
558         a += compressed_mb_len;
559         NS_PUT32(rr->rrdata.soa_rec.serial, a);
560         NS_PUT32(rr->rrdata.soa_rec.refresh, a);
561         NS_PUT32(rr->rrdata.soa_rec.retry, a);
562         NS_PUT32(rr->rrdata.soa_rec.expire, a);
563         NS_PUT32(rr->rrdata.soa_rec.minimum, a);
564
565         return resp_size;
566 }
567
568 static ssize_t rwrap_fake_cname(struct rwrap_fake_rr *rr,
569                                 uint8_t *answer,
570                                 size_t anslen)
571 {
572         uint8_t *a = answer;
573         ssize_t resp_size;
574         unsigned char hostname_compressed[MAXDNAME];
575         ssize_t rdata_size;
576
577         if (rr == NULL || rr->type != ns_t_cname) {
578                 RWRAP_LOG(RWRAP_LOG_ERROR,
579                           "Malformed record, no or wrong value!\n");
580                 return -1;
581         }
582         RWRAP_LOG(RWRAP_LOG_TRACE, "Adding CNAME RR");
583
584         /* Prepare the data to write */
585         rdata_size = ns_name_compress(rr->rrdata.cname_rec,
586                                       hostname_compressed, MAXDNAME,
587                                       NULL, NULL);
588         if (rdata_size < 0) {
589                 return -1;
590         }
591
592         resp_size = rwrap_fake_rdata_common(ns_t_cname, rdata_size,
593                                             rr->key, anslen, &a);
594         if (resp_size < 0) {
595                 return -1;
596         }
597
598         memcpy(a, hostname_compressed, rdata_size);
599
600         return resp_size;
601 }
602
603 #define RESOLV_MATCH(line, name) \
604         (strncmp(line, name, sizeof(name) - 1) == 0 && \
605         (line[sizeof(name) - 1] == ' ' || \
606          line[sizeof(name) - 1] == '\t'))
607
608 #define TYPE_MATCH(type, ns_type, rec_type, str_type, key, query) \
609         ((type) == (ns_type) && \
610          (strncmp((rec_type), (str_type), sizeof(str_type)) == 0) && \
611          (strcasecmp(key, query)) == 0)
612
613
614 static int rwrap_get_record(const char *hostfile, unsigned recursion,
615                             const char *query, int type,
616                             struct rwrap_fake_rr *rr);
617
618 static int rwrap_srv_recurse(const char *hostfile, unsigned recursion,
619                              const char *query, struct rwrap_fake_rr *rr)
620 {
621         int rc;
622
623         rc = rwrap_get_record(hostfile, recursion, query, ns_t_a, rr);
624         if (rc == 0) return 0;
625
626         rc = rwrap_get_record(hostfile, recursion, query, ns_t_aaaa, rr);
627         if (rc == ENOENT) rc = 0;
628
629         return rc;
630 }
631
632 static int rwrap_cname_recurse(const char *hostfile, unsigned recursion,
633                                const char *query, struct rwrap_fake_rr *rr)
634 {
635         int rc;
636
637         rc = rwrap_get_record(hostfile, recursion, query, ns_t_a, rr);
638         if (rc == 0) return 0;
639
640         rc = rwrap_get_record(hostfile, recursion, query, ns_t_aaaa, rr);
641         if (rc == 0) return 0;
642
643         rc = rwrap_get_record(hostfile, recursion, query, ns_t_cname, rr);
644         if (rc == ENOENT) rc = 0;
645
646         return rc;
647 }
648
649 static int rwrap_get_record(const char *hostfile, unsigned recursion,
650                             const char *query, int type,
651                             struct rwrap_fake_rr *rr)
652 {
653         FILE *fp = NULL;
654         char buf[BUFSIZ];
655         char *key = NULL;
656         char *value = NULL;
657         int rc = ENOENT;
658
659         if (recursion >= RWRAP_MAX_RECURSION) {
660                 RWRAP_LOG(RWRAP_LOG_ERROR, "Recursed too deep!\n");
661                 return -1;
662         }
663
664         RWRAP_LOG(RWRAP_LOG_TRACE,
665                   "Searching in fake hosts file %s\n", hostfile);
666
667         fp = fopen(hostfile, "r");
668         if (fp == NULL) {
669                 RWRAP_LOG(RWRAP_LOG_ERROR,
670                           "Opening %s failed: %s",
671                           hostfile, strerror(errno));
672                 return -1;
673         }
674
675         while (fgets(buf, sizeof(buf), fp) != NULL) {
676                 char *rec_type;
677                 char *q;
678
679                 rec_type = buf;
680                 key = value = NULL;
681
682                 NEXT_KEY(rec_type, key);
683                 NEXT_KEY(key, value);
684
685                 if (key == NULL || value == NULL) {
686                         RWRAP_LOG(RWRAP_LOG_WARN,
687                                 "Malformed line: not enough parts, use \"rec_type key data\n"
688                                 "For example \"A cwrap.org 10.10.10.10\"");
689                         continue;
690                 }
691
692                 q = value;
693                 while(q[0] != '\n' && q[0] != '\0') {
694                         q++;
695                 }
696                 q[0] = '\0';
697
698                 if (TYPE_MATCH(type, ns_t_a, rec_type, "A", key, query)) {
699                         rc = rwrap_create_fake_a_rr(key, value, rr);
700                         break;
701                 } else if (TYPE_MATCH(type, ns_t_aaaa,
702                                       rec_type, "AAAA", key, query)) {
703                         rc = rwrap_create_fake_aaaa_rr(key, value, rr);
704                         break;
705                 } else if (TYPE_MATCH(type, ns_t_srv,
706                                       rec_type, "SRV", key, query)) {
707                         rc = rwrap_create_fake_srv_rr(key, value, rr);
708                         if (rc == 0) {
709                                 rc = rwrap_srv_recurse(hostfile, recursion+1,
710                                                 rr->rrdata.srv_rec.hostname,
711                                                 rr + 1);
712                         }
713                         break;
714                 } else if (TYPE_MATCH(type, ns_t_soa,
715                                       rec_type, "SOA", key, query)) {
716                         rc = rwrap_create_fake_soa_rr(key, value, rr);
717                         break;
718                 } else if (TYPE_MATCH(type, ns_t_cname,
719                                       rec_type, "CNAME", key, query)) {
720                         rc = rwrap_create_fake_cname_rr(key, value, rr);
721                         if (rc == 0) {
722                                 rc = rwrap_cname_recurse(hostfile, recursion+1,
723                                                          value, rr + 1);
724                         }
725                         break;
726                 } else if (TYPE_MATCH(type, ns_t_a, rec_type, "CNAME", key, query)) {
727                         rc = rwrap_create_fake_cname_rr(key, value, rr);
728                         if (rc == 0) {
729                                 rc = rwrap_cname_recurse(hostfile, recursion+1,
730                                                          value, rr + 1);
731                         }
732                         break;
733                 }
734         }
735
736         if (rc == ENOENT && recursion == 0 && key != NULL) {
737                 RWRAP_LOG(RWRAP_LOG_TRACE, "Record for [%s] not found\n", query);
738                 memcpy(rr->key, key, strlen(key) + 1);
739         }
740
741         fclose(fp);
742         return rc;
743 }
744
745 static ssize_t rwrap_fake_empty(int type,
746                                 const char *question,
747                                 uint8_t *answer,
748                                 size_t anslen)
749 {
750         ssize_t resp_data;
751         size_t remaining = anslen;
752
753         resp_data = rwrap_fake_header(&answer, remaining, 0, 0);
754         if (resp_data < 0) {
755                 return -1;
756         }
757         remaining -= resp_data;
758
759         resp_data += rwrap_fake_question(question, type, &answer, remaining);
760         if (resp_data < 0) {
761                 return -1;
762         }
763         remaining -= resp_data;
764
765         resp_data += rwrap_fake_rdata_common(type, 0, question,
766                                             remaining, &answer);
767         if (resp_data < 0) {
768                 return -1;
769         }
770
771         return resp_data;
772 }
773
774 static inline bool rwrap_known_type(int type)
775 {
776         switch (type) {
777         case ns_t_a:
778         case ns_t_aaaa:
779         case ns_t_srv:
780         case ns_t_soa:
781         case ns_t_cname:
782                 return true;
783         }
784
785         return false;
786 }
787
788 static int rwrap_ancount(struct rwrap_fake_rr *rrs, int qtype)
789 {
790         int i;
791         int ancount = 0;
792
793         /* Include all RRs in the stack until the sought type
794          * in the answer section. This is the case i.e. when looking
795          * up an A record but the name points to a CNAME
796          */
797         for (i = 0; i < RWRAP_MAX_RECURSION; i++) {
798                 ancount++;
799
800                 if (rwrap_known_type(rrs[i].type) &&
801                     rrs[i].type == qtype) {
802                         break;
803                 }
804         }
805
806         /* Return 0 records if the sought type wasn't in the stack */
807         return i < RWRAP_MAX_RECURSION ? ancount : 0;
808 }
809
810 static int rwrap_arcount(struct rwrap_fake_rr *rrs, int ancount)
811 {
812         int i;
813         int arcount = 0;
814
815         /* start from index ancount */
816         for (i = ancount; i < RWRAP_MAX_RECURSION; i++) {
817                 if (rwrap_known_type(rrs[i].type)) {
818                         arcount++;
819                 }
820         }
821
822         return arcount;
823 }
824
825 static ssize_t rwrap_add_rr(struct rwrap_fake_rr *rr,
826                             uint8_t *answer,
827                             size_t anslen)
828 {
829         ssize_t resp_data;
830
831         switch (rr->type) {
832         case ns_t_a:
833                 resp_data = rwrap_fake_a(rr, answer, anslen);
834                 break;
835         case ns_t_aaaa:
836                 resp_data = rwrap_fake_aaaa(rr, answer, anslen);
837                 break;
838         case ns_t_srv:
839                 resp_data = rwrap_fake_srv(rr, answer, anslen);
840                 break;
841         case ns_t_soa:
842                 resp_data = rwrap_fake_soa(rr, answer, anslen);
843                 break;
844         case ns_t_cname:
845                 resp_data = rwrap_fake_cname(rr, answer, anslen);
846                 break;
847         default:
848                 return -1;
849         }
850
851         return resp_data;
852 }
853
854 static ssize_t rwrap_fake_answer(struct rwrap_fake_rr *rrs,
855                                  int type,
856                                  uint8_t *answer,
857                                  size_t anslen)
858
859 {
860         ssize_t resp_data;
861         ssize_t rrlen;
862         size_t remaining = anslen;
863         int ancount;
864         int arcount;
865         int i;
866
867         ancount = rwrap_ancount(rrs, type);
868         arcount = rwrap_arcount(rrs, ancount);
869         RWRAP_LOG(RWRAP_LOG_TRACE,
870                   "Got %d answers and %d additional records\n", ancount, arcount);
871
872         resp_data = rwrap_fake_header(&answer, remaining, ancount, arcount);
873         if (resp_data < 0) {
874                 return -1;
875         }
876         remaining -= resp_data;
877
878         resp_data += rwrap_fake_question(rrs->key, rrs->type, &answer, remaining);
879         if (resp_data < 0) {
880                 return -1;
881         }
882         remaining -= resp_data;
883
884         /* answer */
885         for (i = 0; i < ancount; i++) {
886                 rrlen = rwrap_add_rr(&rrs[i], answer, remaining);
887                 if (rrlen < 0) {
888                         return -1;
889                 }
890                 remaining -= rrlen;
891                 answer += rrlen;
892                 resp_data += rrlen;
893         }
894
895         /* add authoritative NS here? */
896
897         /* additional records */
898         for (i = ancount; i < ancount + arcount; i++) {
899                 rrlen = rwrap_add_rr(&rrs[i], answer, remaining);
900                 if (rrlen < 0) {
901                         return -1;
902                 }
903                 remaining -= rrlen;
904                 answer += rrlen;
905                 resp_data += rrlen;
906         }
907
908         return resp_data;
909 }
910
911 /* Reads in a file in the following format:
912  * TYPE RDATA
913  *
914  * Malformed entried are silently skipped.
915  * Allocates answer buffer of size anslen that has to be freed after use.
916  */
917 static int rwrap_res_fake_hosts(const char *hostfile,
918                                 const char *query,
919                                 int type,
920                                 unsigned char *answer,
921                                 size_t anslen)
922 {
923         int rc = ENOENT;
924         char *query_name = NULL;
925         size_t qlen = strlen(query);
926         struct rwrap_fake_rr rrs[RWRAP_MAX_RECURSION];
927         ssize_t resp_size;
928
929         RWRAP_LOG(RWRAP_LOG_TRACE,
930                   "Searching in fake hosts file %s\n", hostfile);
931
932         if (qlen > 0 && query[qlen-1] == '.') {
933                 qlen--;
934         }
935
936         query_name = strndup(query, qlen);
937         if (query_name == NULL) {
938                 return -1;
939         }
940
941         rwrap_fake_rr_init(rrs, RWRAP_MAX_RECURSION);
942
943         rc = rwrap_get_record(hostfile, 0, query_name, type, rrs);
944         switch (rc) {
945         case 0:
946                 RWRAP_LOG(RWRAP_LOG_TRACE,
947                                 "Found record for [%s]\n", query_name);
948                 resp_size = rwrap_fake_answer(rrs, type, answer, anslen);
949                 break;
950         case ENOENT:
951                 RWRAP_LOG(RWRAP_LOG_TRACE,
952                                 "No record for [%s]\n", query_name);
953                 resp_size = rwrap_fake_empty(type, rrs->key, answer, anslen);
954                 break;
955         default:
956                 RWRAP_LOG(RWRAP_LOG_ERROR,
957                                 "Error searching for [%s]\n", query_name);
958                 free(query_name);
959                 return -1;
960         }
961
962         switch (resp_size) {
963         case -1:
964                 RWRAP_LOG(RWRAP_LOG_ERROR,
965                                 "Error faking answer for [%s]\n", query_name);
966                 break;
967         default:
968                 RWRAP_LOG(RWRAP_LOG_TRACE,
969                                 "Successfully faked answer for [%s]\n",
970                                 query_name);
971                 break;
972         }
973
974         free(query_name);
975         return resp_size;
976 }
977
978 /*********************************************************
979  * RWRAP LOADING LIBC FUNCTIONS
980  *********************************************************/
981
982 #include <dlfcn.h>
983
984 typedef int (*__libc_res_ninit)(struct __res_state *state);
985 typedef int (*__libc___res_ninit)(struct __res_state *state);
986 typedef void (*__libc_res_nclose)(struct __res_state *state);
987 typedef void (*__libc___res_nclose)(struct __res_state *state);
988 typedef int (*__libc_res_nquery)(struct __res_state *state,
989                                  const char *dname,
990                                  int class,
991                                  int type,
992                                  unsigned char *answer,
993                                  int anslen);
994 typedef int (*__libc___res_nquery)(struct __res_state *state,
995                                    const char *dname,
996                                    int class,
997                                    int type,
998                                    unsigned char *answer,
999                                    int anslen);
1000 typedef int (*__libc_res_nsearch)(struct __res_state *state,
1001                                   const char *dname,
1002                                   int class,
1003                                   int type,
1004                                   unsigned char *answer,
1005                                   int anslen);
1006 typedef int (*__libc___res_nsearch)(struct __res_state *state,
1007                                     const char *dname,
1008                                     int class,
1009                                     int type,
1010                                     unsigned char *answer,
1011                                     int anslen);
1012
1013 #define RWRAP_SYMBOL_ENTRY(i) \
1014         union { \
1015                 __libc_##i f; \
1016                 void *obj; \
1017         } _libc_##i
1018
1019 struct rwrap_libc_symbols {
1020         RWRAP_SYMBOL_ENTRY(res_ninit);
1021         RWRAP_SYMBOL_ENTRY(__res_ninit);
1022         RWRAP_SYMBOL_ENTRY(res_nclose);
1023         RWRAP_SYMBOL_ENTRY(__res_nclose);
1024         RWRAP_SYMBOL_ENTRY(res_nquery);
1025         RWRAP_SYMBOL_ENTRY(__res_nquery);
1026         RWRAP_SYMBOL_ENTRY(res_nsearch);
1027         RWRAP_SYMBOL_ENTRY(__res_nsearch);
1028 };
1029 #undef RWRAP_SYMBOL_ENTRY
1030
1031 struct rwrap {
1032         struct {
1033                 void *handle;
1034                 struct rwrap_libc_symbols symbols;
1035         } libc;
1036
1037         struct {
1038                 void *handle;
1039                 struct rwrap_libc_symbols symbols;
1040         } libresolv;
1041
1042         bool initialised;
1043         bool enabled;
1044
1045         char *socket_dir;
1046 };
1047
1048 static struct rwrap rwrap;
1049
1050 enum rwrap_lib {
1051     RWRAP_LIBC,
1052     RWRAP_LIBRESOLV
1053 };
1054
1055 #ifndef NDEBUG
1056 static const char *rwrap_str_lib(enum rwrap_lib lib)
1057 {
1058         switch (lib) {
1059         case RWRAP_LIBC:
1060                 return "libc";
1061         case RWRAP_LIBRESOLV:
1062                 return "libresolv";
1063         }
1064
1065         /* Compiler would warn us about unhandled enum value if we get here */
1066         return "unknown";
1067 }
1068 #endif
1069
1070 static void *rwrap_load_lib_handle(enum rwrap_lib lib)
1071 {
1072         int flags = RTLD_LAZY;
1073         void *handle = NULL;
1074         int i;
1075
1076 #ifdef RTLD_DEEPBIND
1077         flags |= RTLD_DEEPBIND;
1078 #endif
1079
1080         switch (lib) {
1081         case RWRAP_LIBRESOLV:
1082 #ifdef HAVE_LIBRESOLV
1083                 handle = rwrap.libresolv.handle;
1084                 if (handle == NULL) {
1085                         for (i = 10; i >= 0; i--) {
1086                                 char soname[256] = {0};
1087
1088                                 snprintf(soname, sizeof(soname), "libresolv.so.%d", i);
1089                                 handle = dlopen(soname, flags);
1090                                 if (handle != NULL) {
1091                                         break;
1092                                 }
1093                         }
1094
1095                         rwrap.libresolv.handle = handle;
1096                 }
1097                 break;
1098 #endif
1099                 /* FALL TROUGH */
1100         case RWRAP_LIBC:
1101                 handle = rwrap.libc.handle;
1102 #ifdef LIBC_SO
1103                 if (handle == NULL) {
1104                         handle = dlopen(LIBC_SO, flags);
1105
1106                         rwrap.libc.handle = handle;
1107                 }
1108 #endif
1109                 if (handle == NULL) {
1110                         for (i = 10; i >= 0; i--) {
1111                                 char soname[256] = {0};
1112
1113                                 snprintf(soname, sizeof(soname), "libc.so.%d", i);
1114                                 handle = dlopen(soname, flags);
1115                                 if (handle != NULL) {
1116                                         break;
1117                                 }
1118                         }
1119
1120                         rwrap.libc.handle = handle;
1121                 }
1122                 break;
1123         }
1124
1125         if (handle == NULL) {
1126 #ifdef RTLD_NEXT
1127                 handle = rwrap.libc.handle = rwrap.libresolv.handle = RTLD_NEXT;
1128 #else
1129                 RWRAP_LOG(RWRAP_LOG_ERROR,
1130                           "Failed to dlopen library: %s\n",
1131                           dlerror());
1132                 exit(-1);
1133 #endif
1134         }
1135
1136         return handle;
1137 }
1138
1139 static void *_rwrap_bind_symbol(enum rwrap_lib lib, const char *fn_name)
1140 {
1141         void *handle;
1142         void *func;
1143
1144         handle = rwrap_load_lib_handle(lib);
1145
1146         func = dlsym(handle, fn_name);
1147         if (func == NULL) {
1148                 RWRAP_LOG(RWRAP_LOG_ERROR,
1149                                 "Failed to find %s: %s\n",
1150                                 fn_name, dlerror());
1151                 exit(-1);
1152         }
1153
1154         RWRAP_LOG(RWRAP_LOG_TRACE,
1155                         "Loaded %s from %s",
1156                         fn_name, rwrap_str_lib(lib));
1157         return func;
1158 }
1159
1160 #define rwrap_bind_symbol_libc(sym_name) \
1161         if (rwrap.libc.symbols._libc_##sym_name.obj == NULL) { \
1162                 rwrap.libc.symbols._libc_##sym_name.obj = \
1163                         _rwrap_bind_symbol(RWRAP_LIBC, #sym_name); \
1164         }
1165
1166 #define rwrap_bind_symbol_libresolv(sym_name) \
1167         if (rwrap.libresolv.symbols._libc_##sym_name.obj == NULL) { \
1168                 rwrap.libresolv.symbols._libc_##sym_name.obj = \
1169                         _rwrap_bind_symbol(RWRAP_LIBRESOLV, #sym_name); \
1170         }
1171
1172 /*
1173  * IMPORTANT
1174  *
1175  * Functions especially from libc need to be loaded individually, you can't load
1176  * all at once or gdb will segfault at startup. The same applies to valgrind and
1177  * has probably something todo with with the linker.
1178  * So we need load each function at the point it is called the first time.
1179  */
1180
1181 static int libc_res_ninit(struct __res_state *state)
1182 {
1183 #if !defined(res_ninit) && defined(HAVE_RES_NINIT)
1184
1185 #if defined(HAVE_RES_NINIT_IN_LIBRESOLV)
1186         rwrap_bind_symbol_libresolv(res_ninit);
1187
1188         return rwrap.libresolv.symbols._libc_res_ninit.f(state);
1189 #else /* HAVE_RES_NINIT_IN_LIBRESOLV */
1190         rwrap_bind_symbol_libc(res_ninit);
1191
1192         return rwrap.libc.symbols._libc_res_ninit.f(state);
1193 #endif /* HAVE_RES_NINIT_IN_LIBRESOLV */
1194
1195 #elif defined(HAVE___RES_NINIT)
1196         rwrap_bind_symbol_libc(__res_ninit);
1197
1198         return rwrap.libc.symbols._libc___res_ninit.f(state);
1199 #else
1200 #error "No res_ninit function"
1201 #endif
1202 }
1203
1204 static void libc_res_nclose(struct __res_state *state)
1205 {
1206 #if !defined(res_close) && defined(HAVE_RES_NCLOSE)
1207
1208 #if defined(HAVE_RES_NCLOSE_IN_LIBRESOLV)
1209         rwrap_bind_symbol_libresolv(res_nclose);
1210
1211         rwrap.libresolv.symbols._libc_res_nclose.f(state);
1212         return;
1213 #else /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
1214         rwrap_bind_symbol_libc(res_nclose);
1215
1216         rwrap.libc.symbols._libc_res_nclose.f(state);
1217         return;
1218 #endif /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
1219
1220 #elif defined(HAVE___RES_NCLOSE)
1221         rwrap_bind_symbol_libc(__res_nclose);
1222
1223         rwrap.libc.symbols._libc___res_nclose.f(state);
1224 #else
1225 #error "No res_nclose function"
1226 #endif
1227 }
1228
1229 static int libc_res_nquery(struct __res_state *state,
1230                            const char *dname,
1231                            int class,
1232                            int type,
1233                            unsigned char *answer,
1234                            int anslen)
1235 {
1236 #if !defined(res_nquery) && defined(HAVE_RES_NQUERY)
1237         rwrap_bind_symbol_libresolv(res_nquery);
1238
1239         return rwrap.libresolv.symbols._libc_res_nquery.f(state,
1240                                                           dname,
1241                                                           class,
1242                                                           type,
1243                                                           answer,
1244                                                           anslen);
1245 #elif defined(HAVE___RES_NQUERY)
1246         rwrap_bind_symbol_libresolv(__res_nquery);
1247
1248         return rwrap.libresolv.symbols._libc___res_nquery.f(state,
1249                                                             dname,
1250                                                             class,
1251                                                             type,
1252                                                             answer,
1253                                                             anslen);
1254 #else
1255 #error "No res_nquery function"
1256 #endif
1257 }
1258
1259 static int libc_res_nsearch(struct __res_state *state,
1260                             const char *dname,
1261                             int class,
1262                             int type,
1263                             unsigned char *answer,
1264                             int anslen)
1265 {
1266 #if !defined(res_nsearch) && defined(HAVE_RES_NSEARCH)
1267         rwrap_bind_symbol_libresolv(res_nsearch);
1268
1269         return rwrap.libresolv.symbols._libc_res_nsearch.f(state,
1270                                                            dname,
1271                                                            class,
1272                                                            type,
1273                                                            answer,
1274                                                            anslen);
1275 #elif defined(HAVE___RES_NSEARCH)
1276         rwrap_bind_symbol_libresolv(__res_nsearch);
1277
1278         return rwrap.libresolv.symbols._libc___res_nsearch.f(state,
1279                                                              dname,
1280                                                              class,
1281                                                              type,
1282                                                              answer,
1283                                                              anslen);
1284 #else
1285 #error "No res_nsearch function"
1286 #endif
1287 }
1288
1289 /****************************************************************************
1290  *   RES_HELPER
1291  ***************************************************************************/
1292
1293 static int rwrap_parse_resolv_conf(struct __res_state *state,
1294                                    const char *resolv_conf)
1295 {
1296         FILE *fp;
1297         char buf[BUFSIZ];
1298         int nserv = 0;
1299
1300         fp = fopen(resolv_conf, "r");
1301         if (fp == NULL) {
1302                 RWRAP_LOG(RWRAP_LOG_ERROR,
1303                           "Opening %s failed: %s",
1304                           resolv_conf, strerror(errno));
1305                 return -1;
1306         }
1307
1308         while(fgets(buf, sizeof(buf), fp) != NULL) {
1309                 char *p;
1310
1311                 /* Ignore comments */
1312                 if (buf[0] == '#' || buf[0] == ';') {
1313                         continue;
1314                 }
1315
1316                 if (RESOLV_MATCH(buf, "nameserver") && nserv < MAXNS) {
1317                         struct in_addr a;
1318                         char *q;
1319                         int ok;
1320
1321                         p = buf + strlen("nameserver");
1322
1323                         /* Skip spaces and tabs */
1324                         while(isblank((int)p[0])) {
1325                                 p++;
1326                         }
1327
1328                         q = p;
1329                         while(q[0] != '\n' && q[0] != '\0') {
1330                                 q++;
1331                         }
1332                         q[0] = '\0';
1333
1334                         ok = inet_pton(AF_INET, p, &a);
1335                         if (ok) {
1336                                 state->nsaddr_list[state->nscount] = (struct sockaddr_in) {
1337                                         .sin_family = AF_INET,
1338                                         .sin_addr = a,
1339                                         .sin_port = htons(53),
1340                                         .sin_zero = { 0 },
1341                                 };
1342
1343                                 state->nscount++;
1344                                 nserv++;
1345                         } else {
1346 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1347                                 /* IPv6 */
1348                                 struct in6_addr a6;
1349                                 ok = inet_pton(AF_INET6, p, &a6);
1350                                 if (ok) {
1351                                         struct sockaddr_in6 *sa6;
1352
1353                                         sa6 = malloc(sizeof(*sa6));
1354                                         if (sa6 == NULL) {
1355                                                 fclose(fp);
1356                                                 return -1;
1357                                         }
1358
1359                                         sa6->sin6_family = AF_INET6;
1360                                         sa6->sin6_port = htons(53);
1361                                         sa6->sin6_flowinfo = 0;
1362                                         sa6->sin6_addr = a6;
1363
1364                                         state->_u._ext.nsaddrs[state->_u._ext.nscount] = sa6;
1365                                         state->_u._ext.nssocks[state->_u._ext.nscount] = -1;
1366                                         state->_u._ext.nsmap[state->_u._ext.nscount] = MAXNS + 1;
1367
1368                                         state->_u._ext.nscount++;
1369                                         nserv++;
1370                                 } else {
1371                                         RWRAP_LOG(RWRAP_LOG_ERROR,
1372                                                 "Malformed DNS server");
1373                                         continue;
1374                                 }
1375 #else /* !HAVE_RESOLV_IPV6_NSADDRS */
1376                                 /*
1377                                  * BSD uses an opaque structure to store the
1378                                  * IPv6 addresses. So we can not simply store
1379                                  * these addresses the same way as above.
1380                                  */
1381                                 RWRAP_LOG(RWRAP_LOG_WARN,
1382                                           "resolve_wrapper does not support "
1383                                           "IPv6 on this platform");
1384                                         continue;
1385 #endif
1386                         }
1387                         continue;
1388                 } /* TODO: match other keywords */
1389         }
1390
1391         if (ferror(fp)) {
1392                 RWRAP_LOG(RWRAP_LOG_ERROR,
1393                           "Reading from %s failed",
1394                           resolv_conf);
1395                 fclose(fp);
1396                 return -1;
1397         }
1398
1399         fclose(fp);
1400         return 0;
1401 }
1402
1403 /****************************************************************************
1404  *   RES_NINIT
1405  ***************************************************************************/
1406
1407 static int rwrap_res_ninit(struct __res_state *state)
1408 {
1409         int rc;
1410
1411         rc = libc_res_ninit(state);
1412         if (rc == 0) {
1413                 const char *resolv_conf = getenv("RESOLV_WRAPPER_CONF");
1414
1415                 if (resolv_conf != NULL) {
1416                         uint16_t i;
1417
1418                         (void)i; /* maybe unused */
1419
1420                         /* Delete name servers */
1421                         state->nscount = 0;
1422                         memset(state->nsaddr_list, 0, sizeof(state->nsaddr_list));
1423
1424                         state->_u._ext.nscount = 0;
1425 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1426                         for (i = 0; i < state->_u._ext.nscount; i++) {
1427                                 SAFE_FREE(state->_u._ext.nsaddrs[i]);
1428                         }
1429 #endif
1430
1431                         rc = rwrap_parse_resolv_conf(state, resolv_conf);
1432                 }
1433         }
1434
1435         return rc;
1436 }
1437
1438 #if !defined(res_ninit) && defined(HAVE_RES_NINIT)
1439 int res_ninit(struct __res_state *state)
1440 #elif defined(HAVE___RES_NINIT)
1441 int __res_ninit(struct __res_state *state)
1442 #endif
1443 {
1444         return rwrap_res_ninit(state);
1445 }
1446
1447 /****************************************************************************
1448  *   RES_INIT
1449  ***************************************************************************/
1450
1451 static struct __res_state rwrap_res_state;
1452
1453 static int rwrap_res_init(void)
1454 {
1455         int rc;
1456
1457         rc = rwrap_res_ninit(&rwrap_res_state);
1458
1459         return rc;
1460 }
1461
1462 #if !defined(res_ninit) && defined(HAVE_RES_INIT)
1463 int res_init(void)
1464 #elif defined(HAVE___RES_INIT)
1465 int __res_init(void)
1466 #endif
1467 {
1468         return rwrap_res_init();
1469 }
1470
1471 /****************************************************************************
1472  *   RES_NCLOSE
1473  ***************************************************************************/
1474
1475 static void rwrap_res_nclose(struct __res_state *state)
1476 {
1477 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1478         int i;
1479 #endif
1480
1481         libc_res_nclose(state);
1482
1483 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1484         if (state != NULL) {
1485                 for (i = 0; i < state->_u._ext.nscount; i++) {
1486                         SAFE_FREE(state->_u._ext.nsaddrs[i]);
1487                 }
1488         }
1489 #endif
1490 }
1491
1492 #if !defined(res_nclose) && defined(HAVE_RES_NCLOSE)
1493 void res_nclose(struct __res_state *state)
1494 #elif defined(HAVE___RES_NCLOSE)
1495 void __res_nclose(struct __res_state *state)
1496 #endif
1497 {
1498         rwrap_res_nclose(state);
1499 }
1500
1501 /****************************************************************************
1502  *   RES_CLOSE
1503  ***************************************************************************/
1504
1505 static void rwrap_res_close(void)
1506 {
1507         rwrap_res_nclose(&rwrap_res_state);
1508 }
1509
1510 #if defined(HAVE_RES_CLOSE)
1511 void res_close(void)
1512 #elif defined(HAVE___RES_CLOSE)
1513 void __res_close(void)
1514 #endif
1515 {
1516         rwrap_res_close();
1517 }
1518
1519 /****************************************************************************
1520  *   RES_NQUERY
1521  ***************************************************************************/
1522
1523 static int rwrap_res_nquery(struct __res_state *state,
1524                             const char *dname,
1525                             int class,
1526                             int type,
1527                             unsigned char *answer,
1528                             int anslen)
1529 {
1530         int rc;
1531         const char *fake_hosts;
1532 #ifndef NDEBUG
1533         int i;
1534 #endif
1535
1536         RWRAP_LOG(RWRAP_LOG_TRACE,
1537                   "Resolve the domain name [%s] - class=%d, type=%d",
1538                   dname, class, type);
1539 #ifndef NDEBUG
1540         for (i = 0; i < state->nscount; i++) {
1541                 char ip[INET6_ADDRSTRLEN];
1542
1543                 inet_ntop(AF_INET, &state->nsaddr_list[i].sin_addr, ip, sizeof(ip));
1544                 RWRAP_LOG(RWRAP_LOG_TRACE,
1545                           "        nameserver: %s",
1546                           ip);
1547         }
1548 #endif
1549
1550         fake_hosts = getenv("RESOLV_WRAPPER_HOSTS");
1551         if (fake_hosts != NULL) {
1552                 rc = rwrap_res_fake_hosts(fake_hosts, dname, type, answer, anslen);
1553         } else {
1554                 rc = libc_res_nquery(state, dname, class, type, answer, anslen);
1555         }
1556
1557
1558         RWRAP_LOG(RWRAP_LOG_TRACE,
1559                   "The returned response length is: %d",
1560                   rc);
1561
1562         return rc;
1563 }
1564
1565 #if !defined(res_nquery) && defined(HAVE_RES_NQUERY)
1566 int res_nquery(struct __res_state *state,
1567                const char *dname,
1568                int class,
1569                int type,
1570                unsigned char *answer,
1571                int anslen)
1572 #elif defined(HAVE___RES_NQUERY)
1573 int __res_nquery(struct __res_state *state,
1574                  const char *dname,
1575                  int class,
1576                  int type,
1577                  unsigned char *answer,
1578                  int anslen)
1579 #endif
1580 {
1581         return rwrap_res_nquery(state, dname, class, type, answer, anslen);
1582 }
1583
1584 /****************************************************************************
1585  *   RES_QUERY
1586  ***************************************************************************/
1587
1588 static int rwrap_res_query(const char *dname,
1589                            int class,
1590                            int type,
1591                            unsigned char *answer,
1592                            int anslen)
1593 {
1594         int rc;
1595
1596         rc = rwrap_res_ninit(&rwrap_res_state);
1597         if (rc != 0) {
1598                 return rc;
1599         }
1600
1601         rc = rwrap_res_nquery(&rwrap_res_state,
1602                               dname,
1603                               class,
1604                               type,
1605                               answer,
1606                               anslen);
1607
1608         return rc;
1609 }
1610
1611 #if !defined(res_query) && defined(HAVE_RES_QUERY)
1612 int res_query(const char *dname,
1613               int class,
1614               int type,
1615               unsigned char *answer,
1616               int anslen)
1617 #elif defined(HAVE___RES_QUERY)
1618 int __res_query(const char *dname,
1619                 int class,
1620                 int type,
1621                 unsigned char *answer,
1622                 int anslen)
1623 #endif
1624 {
1625         return rwrap_res_query(dname, class, type, answer, anslen);
1626 }
1627
1628 /****************************************************************************
1629  *   RES_NSEARCH
1630  ***************************************************************************/
1631
1632 static int rwrap_res_nsearch(struct __res_state *state,
1633                              const char *dname,
1634                              int class,
1635                              int type,
1636                              unsigned char *answer,
1637                              int anslen)
1638 {
1639         int rc;
1640         const char *fake_hosts;
1641 #ifndef NDEBUG
1642         int i;
1643 #endif
1644
1645         RWRAP_LOG(RWRAP_LOG_TRACE,
1646                   "Resolve the domain name [%s] - class=%d, type=%d",
1647                   dname, class, type);
1648 #ifndef NDEBUG
1649         for (i = 0; i < state->nscount; i++) {
1650                 char ip[INET6_ADDRSTRLEN];
1651
1652                 inet_ntop(AF_INET, &state->nsaddr_list[i].sin_addr, ip, sizeof(ip));
1653                 RWRAP_LOG(RWRAP_LOG_TRACE,
1654                           "        nameserver: %s",
1655                           ip);
1656         }
1657 #endif
1658
1659         fake_hosts = getenv("RESOLV_WRAPPER_HOSTS");
1660         if (fake_hosts != NULL) {
1661                 rc = rwrap_res_fake_hosts(fake_hosts, dname, type, answer, anslen);
1662         } else {
1663                 rc = libc_res_nsearch(state, dname, class, type, answer, anslen);
1664         }
1665
1666         RWRAP_LOG(RWRAP_LOG_TRACE,
1667                   "The returned response length is: %d",
1668                   rc);
1669
1670         return rc;
1671 }
1672
1673 #if !defined(res_nsearch) && defined(HAVE_RES_NSEARCH)
1674 int res_nsearch(struct __res_state *state,
1675                 const char *dname,
1676                 int class,
1677                 int type,
1678                 unsigned char *answer,
1679                 int anslen)
1680 #elif defined(HAVE___RES_NSEARCH)
1681 int __res_nsearch(struct __res_state *state,
1682                   const char *dname,
1683                   int class,
1684                   int type,
1685                   unsigned char *answer,
1686                   int anslen)
1687 #endif
1688 {
1689         return rwrap_res_nsearch(state, dname, class, type, answer, anslen);
1690 }
1691
1692 /****************************************************************************
1693  *   RES_QUERY
1694  ***************************************************************************/
1695
1696 static int rwrap_res_search(const char *dname,
1697                             int class,
1698                             int type,
1699                             unsigned char *answer,
1700                             int anslen)
1701 {
1702         int rc;
1703
1704         rc = rwrap_res_ninit(&rwrap_res_state);
1705         if (rc != 0) {
1706                 return rc;
1707         }
1708
1709         rc = rwrap_res_nsearch(&rwrap_res_state,
1710                                dname,
1711                                class,
1712                                type,
1713                                answer,
1714                                anslen);
1715
1716         return rc;
1717 }
1718
1719 #if !defined(res_search) && defined(HAVE_RES_SEARCH)
1720 int res_search(const char *dname,
1721                int class,
1722                int type,
1723                unsigned char *answer,
1724                int anslen)
1725 #elif defined(HAVE___RES_SEARCH)
1726 int __res_search(const char *dname,
1727                  int class,
1728                  int type,
1729                  unsigned char *answer,
1730                  int anslen)
1731 #endif
1732 {
1733         return rwrap_res_search(dname, class, type, answer, anslen);
1734 }