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