10af3606b61be0bcab3cd9e314c2eb3a274ef9b9
[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 struct rwrap_libc_fns {
985         int (*libc_res_init)(void);
986         int (*libc___res_init)(void);
987         int (*libc_res_ninit)(struct __res_state *state);
988         int (*libc___res_ninit)(struct __res_state *state);
989         void (*libc_res_nclose)(struct __res_state *state);
990         void (*libc___res_nclose)(struct __res_state *state);
991         void (*libc_res_close)(void);
992         void (*libc___res_close)(void);
993         int (*libc_res_nquery)(struct __res_state *state,
994                                const char *dname,
995                                int class,
996                                int type,
997                                unsigned char *answer,
998                                int anslen);
999         int (*libc___res_nquery)(struct __res_state *state,
1000                                  const char *dname,
1001                                  int class,
1002                                  int type,
1003                                  unsigned char *answer,
1004                                  int anslen);
1005         int (*libc_res_nsearch)(struct __res_state *state,
1006                                 const char *dname,
1007                                 int class,
1008                                 int type,
1009                                 unsigned char *answer,
1010                                 int anslen);
1011         int (*libc___res_nsearch)(struct __res_state *state,
1012                                   const char *dname,
1013                                   int class,
1014                                   int type,
1015                                   unsigned char *answer,
1016                                   int anslen);
1017 };
1018
1019 struct rwrap {
1020         void *libc_handle;
1021         void *libresolv_handle;
1022
1023         bool initialised;
1024         bool enabled;
1025
1026         char *socket_dir;
1027
1028         struct rwrap_libc_fns fns;
1029 };
1030
1031 static struct rwrap rwrap;
1032
1033 enum rwrap_lib {
1034     RWRAP_LIBC,
1035     RWRAP_LIBRESOLV
1036 };
1037
1038 #ifndef NDEBUG
1039 static const char *rwrap_str_lib(enum rwrap_lib lib)
1040 {
1041         switch (lib) {
1042         case RWRAP_LIBC:
1043                 return "libc";
1044         case RWRAP_LIBRESOLV:
1045                 return "libresolv";
1046         }
1047
1048         /* Compiler would warn us about unhandled enum value if we get here */
1049         return "unknown";
1050 }
1051 #endif
1052
1053 static void *rwrap_load_lib_handle(enum rwrap_lib lib)
1054 {
1055         int flags = RTLD_LAZY;
1056         void *handle = NULL;
1057         int i;
1058
1059 #ifdef RTLD_DEEPBIND
1060         flags |= RTLD_DEEPBIND;
1061 #endif
1062
1063         switch (lib) {
1064         case RWRAP_LIBRESOLV:
1065 #ifdef HAVE_LIBRESOLV
1066                 handle = rwrap.libresolv_handle;
1067                 if (handle == NULL) {
1068                         for (i = 10; i >= 0; i--) {
1069                                 char soname[256] = {0};
1070
1071                                 snprintf(soname, sizeof(soname), "libresolv.so.%d", i);
1072                                 handle = dlopen(soname, flags);
1073                                 if (handle != NULL) {
1074                                         break;
1075                                 }
1076                         }
1077
1078                         rwrap.libresolv_handle = handle;
1079                 }
1080                 break;
1081 #endif
1082                 /* FALL TROUGH */
1083         case RWRAP_LIBC:
1084                 handle = rwrap.libc_handle;
1085 #ifdef LIBC_SO
1086                 if (handle == NULL) {
1087                         handle = dlopen(LIBC_SO, flags);
1088
1089                         rwrap.libc_handle = handle;
1090                 }
1091 #endif
1092                 if (handle == NULL) {
1093                         for (i = 10; i >= 0; i--) {
1094                                 char soname[256] = {0};
1095
1096                                 snprintf(soname, sizeof(soname), "libc.so.%d", i);
1097                                 handle = dlopen(soname, flags);
1098                                 if (handle != NULL) {
1099                                         break;
1100                                 }
1101                         }
1102
1103                         rwrap.libc_handle = handle;
1104                 }
1105                 break;
1106         }
1107
1108         if (handle == NULL) {
1109 #ifdef RTLD_NEXT
1110                 handle = rwrap.libc_handle = rwrap.libresolv_handle = RTLD_NEXT;
1111 #else
1112                 RWRAP_LOG(RWRAP_LOG_ERROR,
1113                           "Failed to dlopen library: %s\n",
1114                           dlerror());
1115                 exit(-1);
1116 #endif
1117         }
1118
1119         return handle;
1120 }
1121
1122 static void *_rwrap_load_lib_function(enum rwrap_lib lib, const char *fn_name)
1123 {
1124         void *handle;
1125         void *func;
1126
1127         handle = rwrap_load_lib_handle(lib);
1128
1129         func = dlsym(handle, fn_name);
1130         if (func == NULL) {
1131                 RWRAP_LOG(RWRAP_LOG_ERROR,
1132                                 "Failed to find %s: %s\n",
1133                                 fn_name, dlerror());
1134                 exit(-1);
1135         }
1136
1137         RWRAP_LOG(RWRAP_LOG_TRACE,
1138                         "Loaded %s from %s",
1139                         fn_name, rwrap_str_lib(lib));
1140         return func;
1141 }
1142
1143 #define rwrap_load_lib_function(lib, fn_name) \
1144         if (rwrap.fns.libc_##fn_name == NULL) { \
1145                 *(void **) (&rwrap.fns.libc_##fn_name) = \
1146                         _rwrap_load_lib_function(lib, #fn_name); \
1147         }
1148
1149 /*
1150  * IMPORTANT
1151  *
1152  * Functions especially from libc need to be loaded individually, you can't load
1153  * all at once or gdb will segfault at startup. The same applies to valgrind and
1154  * has probably something todo with with the linker.
1155  * So we need load each function at the point it is called the first time.
1156  */
1157 #if 0
1158 static int libc_res_init(void)
1159 {
1160 #if defined(HAVE_RES_INIT)
1161         rwrap_load_lib_function(RWRAP_LIBRESOLV, res_init);
1162
1163         return rwrap.fns.libc_res_init();
1164 #elif defined(HAVE___RES_INIT)
1165         rwrap_load_lib_function(RWRAP_LIBRESOLV, __res_init);
1166
1167         return rwrap.fns.libc___res_init();
1168 #endif
1169 }
1170 #endif
1171
1172 static int libc_res_ninit(struct __res_state *state)
1173 {
1174 #if defined(HAVE_RES_NINIT)
1175
1176 #if defined(HAVE_RES_NINIT_IN_LIBRESOLV)
1177         rwrap_load_lib_function(RWRAP_LIBRESOLV, res_ninit);
1178 #else /* HAVE_RES_NINIT_IN_LIBRESOLV */
1179         rwrap_load_lib_function(RWRAP_LIBC, res_ninit);
1180 #endif /* HAVE_RES_NINIT_IN_LIBRESOLV */
1181
1182         return rwrap.fns.libc_res_ninit(state);
1183 #elif defined(HAVE___RES_NINIT)
1184         rwrap_load_lib_function(RWRAP_LIBC, __res_ninit);
1185
1186         return rwrap.fns.libc___res_ninit(state);
1187 #else
1188 #error "No res_ninit function"
1189 #endif
1190 }
1191
1192 static void libc_res_nclose(struct __res_state *state)
1193 {
1194 #if defined(HAVE_RES_NCLOSE)
1195
1196 #if defined(HAVE_RES_NCLOSE_IN_LIBRESOLV)
1197         rwrap_load_lib_function(RWRAP_LIBRESOLV, res_nclose);
1198 #else /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
1199         rwrap_load_lib_function(RWRAP_LIBC, res_nclose);
1200 #endif /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
1201
1202         rwrap.fns.libc_res_nclose(state);
1203 #elif defined(HAVE___RES_NCLOSE)
1204         rwrap_load_lib_function(RWRAP_LIBC, __res_nclose);
1205
1206         rwrap.fns.libc___res_nclose(state);
1207 #else
1208 #error "No res_nclose function"
1209 #endif
1210 }
1211
1212 static int libc_res_nquery(struct __res_state *state,
1213                            const char *dname,
1214                            int class,
1215                            int type,
1216                            unsigned char *answer,
1217                            int anslen)
1218 {
1219 #if defined(HAVE_RES_NQUERY)
1220         rwrap_load_lib_function(RWRAP_LIBRESOLV, res_nquery);
1221
1222         return rwrap.fns.libc_res_nquery(state,
1223                                          dname,
1224                                          class,
1225                                          type,
1226                                          answer,
1227                                          anslen);
1228 #elif defined(HAVE___RES_NQUERY)
1229         rwrap_load_lib_function(RWRAP_LIBRESOLV, __res_nquery);
1230
1231         return rwrap.fns.libc___res_nquery(state,
1232                                            dname,
1233                                            class,
1234                                            type,
1235                                            answer,
1236                                            anslen);
1237 #else
1238 #error "No res_nquery function"
1239 #endif
1240 }
1241
1242 static int libc_res_nsearch(struct __res_state *state,
1243                             const char *dname,
1244                             int class,
1245                             int type,
1246                             unsigned char *answer,
1247                             int anslen)
1248 {
1249 #if defined(HAVE_RES_NSEARCH)
1250         rwrap_load_lib_function(RWRAP_LIBRESOLV, res_nsearch);
1251
1252         return rwrap.fns.libc_res_nsearch(state,
1253                                           dname,
1254                                           class,
1255                                           type,
1256                                           answer,
1257                                           anslen);
1258 #elif defined(HAVE___RES_NSEARCH)
1259         rwrap_load_lib_function(RWRAP_LIBRESOLV, __res_nsearch);
1260
1261         return rwrap.fns.libc___res_nsearch(state,
1262                                             dname,
1263                                             class,
1264                                             type,
1265                                             answer,
1266                                             anslen);
1267 #else
1268 #error "No res_nsearch function"
1269 #endif
1270 }
1271
1272 /****************************************************************************
1273  *   RES_HELPER
1274  ***************************************************************************/
1275
1276 static int rwrap_parse_resolv_conf(struct __res_state *state,
1277                                    const char *resolv_conf)
1278 {
1279         FILE *fp;
1280         char buf[BUFSIZ];
1281         int nserv = 0;
1282
1283         fp = fopen(resolv_conf, "r");
1284         if (fp == NULL) {
1285                 RWRAP_LOG(RWRAP_LOG_ERROR,
1286                           "Opening %s failed: %s",
1287                           resolv_conf, strerror(errno));
1288                 return -1;
1289         }
1290
1291         while(fgets(buf, sizeof(buf), fp) != NULL) {
1292                 char *p;
1293
1294                 /* Ignore comments */
1295                 if (buf[0] == '#' || buf[0] == ';') {
1296                         continue;
1297                 }
1298
1299                 if (RESOLV_MATCH(buf, "nameserver") && nserv < MAXNS) {
1300                         struct in_addr a;
1301                         char *q;
1302                         int ok;
1303
1304                         p = buf + strlen("nameserver");
1305
1306                         /* Skip spaces and tabs */
1307                         while(isblank((int)p[0])) {
1308                                 p++;
1309                         }
1310
1311                         q = p;
1312                         while(q[0] != '\n' && q[0] != '\0') {
1313                                 q++;
1314                         }
1315                         q[0] = '\0';
1316
1317                         ok = inet_pton(AF_INET, p, &a);
1318                         if (ok) {
1319                                 state->nsaddr_list[state->nscount] = (struct sockaddr_in) {
1320                                         .sin_family = AF_INET,
1321                                         .sin_addr = a,
1322                                         .sin_port = htons(53),
1323                                         .sin_zero = { 0 },
1324                                 };
1325
1326                                 state->nscount++;
1327                                 nserv++;
1328                         } else {
1329 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1330                                 /* IPv6 */
1331                                 struct in6_addr a6;
1332                                 ok = inet_pton(AF_INET6, p, &a6);
1333                                 if (ok) {
1334                                         struct sockaddr_in6 *sa6;
1335
1336                                         sa6 = malloc(sizeof(*sa6));
1337                                         if (sa6 == NULL) {
1338                                                 fclose(fp);
1339                                                 return -1;
1340                                         }
1341
1342                                         sa6->sin6_family = AF_INET6;
1343                                         sa6->sin6_port = htons(53);
1344                                         sa6->sin6_flowinfo = 0;
1345                                         sa6->sin6_addr = a6;
1346
1347                                         state->_u._ext.nsaddrs[state->_u._ext.nscount] = sa6;
1348                                         state->_u._ext.nssocks[state->_u._ext.nscount] = -1;
1349                                         state->_u._ext.nsmap[state->_u._ext.nscount] = MAXNS + 1;
1350
1351                                         state->_u._ext.nscount++;
1352                                         nserv++;
1353                                 } else {
1354                                         RWRAP_LOG(RWRAP_LOG_ERROR,
1355                                                 "Malformed DNS server");
1356                                         continue;
1357                                 }
1358 #else /* !HAVE_RESOLV_IPV6_NSADDRS */
1359                                 /*
1360                                  * BSD uses an opaque structure to store the
1361                                  * IPv6 addresses. So we can not simply store
1362                                  * these addresses the same way as above.
1363                                  */
1364                                 RWRAP_LOG(RWRAP_LOG_WARN,
1365                                           "resolve_wrapper does not support "
1366                                           "IPv6 on this platform");
1367                                         continue;
1368 #endif
1369                         }
1370                         continue;
1371                 } /* TODO: match other keywords */
1372         }
1373
1374         if (ferror(fp)) {
1375                 RWRAP_LOG(RWRAP_LOG_ERROR,
1376                           "Reading from %s failed",
1377                           resolv_conf);
1378                 fclose(fp);
1379                 return -1;
1380         }
1381
1382         fclose(fp);
1383         return 0;
1384 }
1385
1386 /****************************************************************************
1387  *   RES_NINIT
1388  ***************************************************************************/
1389
1390 static int rwrap_res_ninit(struct __res_state *state)
1391 {
1392         int rc;
1393
1394         rc = libc_res_ninit(state);
1395         if (rc == 0) {
1396                 const char *resolv_conf = getenv("RESOLV_WRAPPER_CONF");
1397
1398                 if (resolv_conf != NULL) {
1399                         uint16_t i;
1400
1401                         (void)i; /* maybe unused */
1402
1403                         /* Delete name servers */
1404                         state->nscount = 0;
1405                         memset(state->nsaddr_list, 0, sizeof(state->nsaddr_list));
1406
1407                         state->_u._ext.nscount = 0;
1408 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1409                         for (i = 0; i < state->_u._ext.nscount; i++) {
1410                                 SAFE_FREE(state->_u._ext.nsaddrs[i]);
1411                         }
1412 #endif
1413
1414                         rc = rwrap_parse_resolv_conf(state, resolv_conf);
1415                 }
1416         }
1417
1418         return rc;
1419 }
1420
1421 #if defined(HAVE_RES_NINIT)
1422 int res_ninit(struct __res_state *state)
1423 #elif defined(HAVE___RES_NINIT)
1424 int __res_ninit(struct __res_state *state)
1425 #endif
1426 {
1427         return rwrap_res_ninit(state);
1428 }
1429
1430 /****************************************************************************
1431  *   RES_INIT
1432  ***************************************************************************/
1433
1434 static struct __res_state rwrap_res_state;
1435
1436 static int rwrap_res_init(void)
1437 {
1438         int rc;
1439
1440         rc = rwrap_res_ninit(&rwrap_res_state);
1441
1442         return rc;
1443 }
1444
1445 #if defined(HAVE_RES_INIT)
1446 int res_init(void)
1447 #elif defined(HAVE___RES_INIT)
1448 int __res_init(void)
1449 #endif
1450 {
1451         return rwrap_res_init();
1452 }
1453
1454 /****************************************************************************
1455  *   RES_NCLOSE
1456  ***************************************************************************/
1457
1458 static void rwrap_res_nclose(struct __res_state *state)
1459 {
1460 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1461         int i;
1462 #endif
1463
1464         libc_res_nclose(state);
1465
1466 #ifdef HAVE_RESOLV_IPV6_NSADDRS
1467         if (state != NULL) {
1468                 for (i = 0; i < state->_u._ext.nscount; i++) {
1469                         SAFE_FREE(state->_u._ext.nsaddrs[i]);
1470                 }
1471         }
1472 #endif
1473 }
1474
1475 #if defined(HAVE_RES_NCLOSE)
1476 void res_nclose(struct __res_state *state)
1477 #elif defined(HAVE___RES_NCLOSE)
1478 void __res_nclose(struct __res_state *state)
1479 #endif
1480 {
1481         rwrap_res_nclose(state);
1482 }
1483
1484 /****************************************************************************
1485  *   RES_CLOSE
1486  ***************************************************************************/
1487
1488 static void rwrap_res_close(void)
1489 {
1490         rwrap_res_nclose(&rwrap_res_state);
1491 }
1492
1493 #if defined(HAVE_RES_CLOSE)
1494 void res_close(void)
1495 #elif defined(HAVE___RES_CLOSE)
1496 void __res_close(void)
1497 #endif
1498 {
1499         rwrap_res_close();
1500 }
1501
1502 /****************************************************************************
1503  *   RES_NQUERY
1504  ***************************************************************************/
1505
1506 static int rwrap_res_nquery(struct __res_state *state,
1507                             const char *dname,
1508                             int class,
1509                             int type,
1510                             unsigned char *answer,
1511                             int anslen)
1512 {
1513         int rc;
1514         const char *fake_hosts;
1515 #ifndef NDEBUG
1516         int i;
1517 #endif
1518
1519         RWRAP_LOG(RWRAP_LOG_TRACE,
1520                   "Resolve the domain name [%s] - class=%d, type=%d",
1521                   dname, class, type);
1522 #ifndef NDEBUG
1523         for (i = 0; i < state->nscount; i++) {
1524                 char ip[INET6_ADDRSTRLEN];
1525
1526                 inet_ntop(AF_INET, &state->nsaddr_list[i].sin_addr, ip, sizeof(ip));
1527                 RWRAP_LOG(RWRAP_LOG_TRACE,
1528                           "        nameserver: %s",
1529                           ip);
1530         }
1531 #endif
1532
1533         fake_hosts = getenv("RESOLV_WRAPPER_HOSTS");
1534         if (fake_hosts != NULL) {
1535                 rc = rwrap_res_fake_hosts(fake_hosts, dname, type, answer, anslen);
1536         } else {
1537                 rc = libc_res_nquery(state, dname, class, type, answer, anslen);
1538         }
1539
1540
1541         RWRAP_LOG(RWRAP_LOG_TRACE,
1542                   "The returned response length is: %d",
1543                   rc);
1544
1545         return rc;
1546 }
1547
1548 #if defined(HAVE_RES_NQUERY)
1549 int res_nquery(struct __res_state *state,
1550                const char *dname,
1551                int class,
1552                int type,
1553                unsigned char *answer,
1554                int anslen)
1555 #elif defined(HAVE___RES_NQUERY)
1556 int __res_nquery(struct __res_state *state,
1557                  const char *dname,
1558                  int class,
1559                  int type,
1560                  unsigned char *answer,
1561                  int anslen)
1562 #endif
1563 {
1564         return rwrap_res_nquery(state, dname, class, type, answer, anslen);
1565 }
1566
1567 /****************************************************************************
1568  *   RES_QUERY
1569  ***************************************************************************/
1570
1571 static int rwrap_res_query(const char *dname,
1572                            int class,
1573                            int type,
1574                            unsigned char *answer,
1575                            int anslen)
1576 {
1577         int rc;
1578
1579         rc = rwrap_res_ninit(&rwrap_res_state);
1580         if (rc != 0) {
1581                 return rc;
1582         }
1583
1584         rc = rwrap_res_nquery(&rwrap_res_state,
1585                               dname,
1586                               class,
1587                               type,
1588                               answer,
1589                               anslen);
1590
1591         return rc;
1592 }
1593
1594 #if defined(HAVE_RES_QUERY)
1595 int res_query(const char *dname,
1596               int class,
1597               int type,
1598               unsigned char *answer,
1599               int anslen)
1600 #elif defined(HAVE___RES_QUERY)
1601 int __res_query(const char *dname,
1602                 int class,
1603                 int type,
1604                 unsigned char *answer,
1605                 int anslen)
1606 #endif
1607 {
1608         return rwrap_res_query(dname, class, type, answer, anslen);
1609 }
1610
1611 /****************************************************************************
1612  *   RES_NSEARCH
1613  ***************************************************************************/
1614
1615 static int rwrap_res_nsearch(struct __res_state *state,
1616                              const char *dname,
1617                              int class,
1618                              int type,
1619                              unsigned char *answer,
1620                              int anslen)
1621 {
1622         int rc;
1623         const char *fake_hosts;
1624 #ifndef NDEBUG
1625         int i;
1626 #endif
1627
1628         RWRAP_LOG(RWRAP_LOG_TRACE,
1629                   "Resolve the domain name [%s] - class=%d, type=%d",
1630                   dname, class, type);
1631 #ifndef NDEBUG
1632         for (i = 0; i < state->nscount; i++) {
1633                 char ip[INET6_ADDRSTRLEN];
1634
1635                 inet_ntop(AF_INET, &state->nsaddr_list[i].sin_addr, ip, sizeof(ip));
1636                 RWRAP_LOG(RWRAP_LOG_TRACE,
1637                           "        nameserver: %s",
1638                           ip);
1639         }
1640 #endif
1641
1642         fake_hosts = getenv("RESOLV_WRAPPER_HOSTS");
1643         if (fake_hosts != NULL) {
1644                 rc = rwrap_res_fake_hosts(fake_hosts, dname, type, answer, anslen);
1645         } else {
1646                 rc = libc_res_nsearch(state, dname, class, type, answer, anslen);
1647         }
1648
1649         RWRAP_LOG(RWRAP_LOG_TRACE,
1650                   "The returned response length is: %d",
1651                   rc);
1652
1653         return rc;
1654 }
1655
1656 #if defined(HAVE_RES_NSEARCH)
1657 int res_nsearch(struct __res_state *state,
1658                 const char *dname,
1659                 int class,
1660                 int type,
1661                 unsigned char *answer,
1662                 int anslen)
1663 #elif defined(HAVE___RES_NSEARCH)
1664 int __res_nsearch(struct __res_state *state,
1665                   const char *dname,
1666                   int class,
1667                   int type,
1668                   unsigned char *answer,
1669                   int anslen)
1670 #endif
1671 {
1672         return rwrap_res_nsearch(state, dname, class, type, answer, anslen);
1673 }
1674
1675 /****************************************************************************
1676  *   RES_QUERY
1677  ***************************************************************************/
1678
1679 static int rwrap_res_search(const char *dname,
1680                             int class,
1681                             int type,
1682                             unsigned char *answer,
1683                             int anslen)
1684 {
1685         int rc;
1686
1687         rc = rwrap_res_ninit(&rwrap_res_state);
1688         if (rc != 0) {
1689                 return rc;
1690         }
1691
1692         rc = rwrap_res_nsearch(&rwrap_res_state,
1693                                dname,
1694                                class,
1695                                type,
1696                                answer,
1697                                anslen);
1698
1699         return rc;
1700 }
1701
1702 #if defined(HAVE_RES_SEARCH)
1703 int res_search(const char *dname,
1704                int class,
1705                int type,
1706                unsigned char *answer,
1707                int anslen)
1708 #elif defined(HAVE___RES_SEARCH)
1709 int __res_search(const char *dname,
1710                  int class,
1711                  int type,
1712                  unsigned char *answer,
1713                  int anslen)
1714 #endif
1715 {
1716         return rwrap_res_search(dname, class, type, answer, anslen);
1717 }