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