rwrap: Don't dereference NULL when skipping broken records
[resolv_wrapper.git] / src / resolv_wrapper.c
index 8fd672970924b364ada7d6015224e734f88f2b51..7211ad087a4bcb286a4cc162aee465d53748e849 100644 (file)
@@ -74,7 +74,7 @@ enum rwrap_dbglvl_e {
 
 #ifdef NDEBUG
 # define RWRAP_LOG(...)
-#else
+#else /* NDEBUG */
 
 static void rwrap_log(enum rwrap_dbglvl_e dbglvl, const char *func, const char *format, ...) PRINTF_ATTRIBUTE(3, 4);
 # define RWRAP_LOG(dbglvl, ...) rwrap_log((dbglvl), __func__, __VA_ARGS__)
@@ -125,17 +125,204 @@ static void rwrap_log(enum rwrap_dbglvl_e dbglvl,
 }
 #endif /* NDEBUG RWRAP_LOG */
 
+#ifndef SAFE_FREE
+#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); (x)=NULL;} } while(0)
+#endif
+
+#define NEXT_KEY(buf, key) do {                                        \
+       (key) = (buf) ? strpbrk((buf), " \t") : NULL;           \
+       if ((key) != NULL) {                                    \
+               (key)[0] = '\0';                                \
+               (key)++;                                        \
+       }                                                       \
+       while ((key) != NULL                                    \
+              && (isblank((int)(key)[0]))) {                   \
+               (key)++;                                        \
+       }                                                       \
+} while(0);
+
+#define RWRAP_MAX_RECURSION 5
+
+/* Priority and weight can be omitted from the hosts file, but need to be part
+ * of the output
+ */
+#define DFL_SRV_PRIO   1
+#define DFL_SRV_WEIGHT 100
+
+struct rwrap_srv_rrdata {
+       uint16_t port;
+       uint16_t prio;
+       uint16_t weight;
+       char hostname[MAXDNAME];
+};
+
+struct rwrap_soa_rrdata {
+       uint32_t serial;
+       uint32_t refresh;
+       uint32_t retry;
+       uint32_t expire;
+       uint32_t minimum;
+       char nameserver[MAXDNAME];
+       char mailbox[MAXDNAME];
+};
+
+struct rwrap_fake_rr {
+       union fake_rrdata {
+               struct in_addr a_rec;
+               struct in6_addr aaaa_rec;
+               struct rwrap_srv_rrdata srv_rec;
+               struct rwrap_soa_rrdata soa_rec;
+               char cname_rec[MAXDNAME];
+       } rrdata;
+
+       char key[MAXDNAME];
+       int type; /* ns_t_* */
+};
+
+static void rwrap_fake_rr_init(struct rwrap_fake_rr *rr, size_t len)
+{
+       size_t i;
+
+       for (i = 0; i < len; i++) {
+               rr[i].type = ns_t_invalid;
+       }
+}
+
+static int rwrap_create_fake_a_rr(const char *key,
+                                 const char *value,
+                                 struct rwrap_fake_rr *rr)
+{
+       int ok;
+
+       ok = inet_pton(AF_INET, value, &rr->rrdata.a_rec);
+       if (!ok) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Failed to convert [%s] to binary\n", value);
+               return -1;
+       }
+
+       memcpy(rr->key, key, strlen(key) + 1);
+       rr->type = ns_t_a;
+       return 0;
+}
+
+static int rwrap_create_fake_aaaa_rr(const char *key,
+                                    const char *value,
+                                    struct rwrap_fake_rr *rr)
+{
+       int ok;
+
+       ok = inet_pton(AF_INET6, value, &rr->rrdata.aaaa_rec);
+       if (!ok) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Failed to convert [%s] to binary\n", value);
+               return -1;
+       }
+
+       memcpy(rr->key, key, strlen(key) + 1);
+       rr->type = ns_t_aaaa;
+       return 0;
+}
+
+static int rwrap_create_fake_srv_rr(const char *key,
+                                   const char *value,
+                                   struct rwrap_fake_rr *rr)
+{
+       char *str_prio;
+       char *str_weight;
+       char *str_port;
+       const char *hostname;
+
+       /* parse the value into priority, weight, port and hostname
+        * and check the validity */
+       hostname = value;
+       NEXT_KEY(hostname, str_port);
+       NEXT_KEY(str_port, str_prio);
+       NEXT_KEY(str_prio, str_weight);
+       if (str_port == NULL || hostname == NULL) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Malformed SRV entry [%s]\n", value);
+               return -1;
+       }
+
+       if (str_prio) {
+               rr->rrdata.srv_rec.prio = atoi(str_prio);
+       } else {
+               rr->rrdata.srv_rec.prio = DFL_SRV_PRIO;
+       }
+       if (str_weight) {
+               rr->rrdata.srv_rec.weight = atoi(str_weight);
+       } else {
+               rr->rrdata.srv_rec.weight = DFL_SRV_WEIGHT;
+       }
+       rr->rrdata.srv_rec.port = atoi(str_port);
+       memcpy(rr->rrdata.srv_rec.hostname , hostname, strlen(hostname) + 1);
+
+       memcpy(rr->key, key, strlen(key) + 1);
+       rr->type = ns_t_srv;
+       return 0;
+}
+
+static int rwrap_create_fake_soa_rr(const char *key,
+                                   const char *value,
+                                   struct rwrap_fake_rr *rr)
+{
+       const char *nameserver;
+       char *mailbox;
+       char *str_serial;
+       char *str_refresh;
+       char *str_retry;
+       char *str_expire;
+       char *str_minimum;
+
+       /* parse the value into nameserver, mailbox, serial, refresh,
+        * retry, expire, minimum and check the validity
+        */
+       nameserver = value;
+       NEXT_KEY(nameserver, mailbox);
+       NEXT_KEY(mailbox, str_serial);
+       NEXT_KEY(str_serial, str_refresh);
+       NEXT_KEY(str_refresh, str_retry);
+       NEXT_KEY(str_retry, str_expire);
+       NEXT_KEY(str_expire, str_minimum);
+       if (nameserver == NULL || mailbox == NULL || str_serial == NULL ||
+           str_refresh == NULL || str_retry == NULL || str_expire == NULL ||
+           str_minimum == NULL) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Malformed SOA entry [%s]\n", value);
+               return -1;
+       }
+
+       memcpy(rr->rrdata.soa_rec.nameserver, nameserver, strlen(nameserver)+1);
+       memcpy(rr->rrdata.soa_rec.mailbox, mailbox, strlen(mailbox)+1);
+
+       rr->rrdata.soa_rec.serial = atoi(str_serial);
+       rr->rrdata.soa_rec.refresh = atoi(str_refresh);
+       rr->rrdata.soa_rec.retry = atoi(str_retry);
+       rr->rrdata.soa_rec.expire = atoi(str_expire);
+       rr->rrdata.soa_rec.minimum = atoi(str_minimum);
+
+       memcpy(rr->key, key, strlen(key) + 1);
+       rr->type = ns_t_soa;
+       return 0;
+}
+
+static int rwrap_create_fake_cname_rr(const char *key,
+                                     const char *value,
+                                     struct rwrap_fake_rr *rr)
+{
+       memcpy(rr->rrdata.cname_rec , value, strlen(value) + 1);
+       memcpy(rr->key, key, strlen(key) + 1);
+       rr->type = ns_t_cname;
+       return 0;
+}
 
 /* Prepares a fake header with a single response. Advances header_blob */
 static ssize_t rwrap_fake_header(uint8_t **header_blob, size_t remaining,
-                                size_t rdata_size)
+                                size_t ancount, size_t arcount)
 {
        uint8_t *hb;
        HEADER *h;
-       int answers;
-
-       /* If rdata_size is zero, the answer is empty */
-       answers = rdata_size > 0 ? 1 : 0;
 
        if (remaining < NS_HFIXEDSZ) {
                RWRAP_LOG(RWRAP_LOG_ERROR, "Buffer too small!\n");
@@ -147,12 +334,13 @@ static ssize_t rwrap_fake_header(uint8_t **header_blob, size_t remaining,
 
        h = (HEADER *) hb;
        h->id = res_randomid();         /* random query ID */
-       h->qr = htons(1);               /* response flag */
-       h->rd = htons(1);               /* recursion desired */
-       h->ra = htons(1);               /* resursion available */
+       h->qr = 1;                      /* response flag */
+       h->rd = 1;                      /* recursion desired */
+       h->ra = 1;                      /* resursion available */
 
        h->qdcount = htons(1);          /* no. of questions */
-       h->ancount = htons(answers);    /* no. of answers */
+       h->ancount = htons(ancount);    /* no. of answers */
+       h->arcount = htons(arcount);    /* no. of add'tl records */
 
        hb += NS_HFIXEDSZ;              /* move past the header */
        *header_blob = hb;
@@ -224,121 +412,188 @@ static ssize_t rwrap_fake_rdata_common(uint16_t type,
        }
 
        *rdata_ptr = rd;
-       return written + 3 * sizeof(uint16_t) + sizeof(uint32_t);
+       return written + 3 * sizeof(uint16_t) + sizeof(uint32_t) + rdata_size;
 }
 
-static ssize_t rwrap_fake_common(uint16_t type,
-                                const char *question,
-                                size_t rdata_size,
-                                uint8_t **answer_ptr,
-                                size_t anslen)
+static ssize_t rwrap_fake_a(struct rwrap_fake_rr *rr,
+                           uint8_t *answer_ptr,
+                           size_t anslen)
 {
-       uint8_t *a = *answer_ptr;
-       ssize_t written;
-       size_t remaining;
-
-       remaining = anslen;
+       uint8_t *a = answer_ptr;
+       ssize_t resp_size;
 
-       written = rwrap_fake_header(&a, remaining, rdata_size);
-       if (written < 0) {
+       if (rr == NULL || rr->type != ns_t_a) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Malformed record, no or wrong value!\n");
                return -1;
        }
-       remaining -= written;
+       RWRAP_LOG(RWRAP_LOG_TRACE, "Adding A RR");
 
-       written = rwrap_fake_question(question, type, &a, remaining);
-       if (written < 0) {
+       resp_size = rwrap_fake_rdata_common(ns_t_a, sizeof(struct in_addr), rr->key,
+                                           anslen, &a);
+       if (resp_size < 0) {
                return -1;
        }
-       remaining -= written;
 
-       /* rdata_size = 0 denotes an empty answer */
-       if (rdata_size > 0) {
-               written = rwrap_fake_rdata_common(type, rdata_size, question,
-                                               remaining, &a);
-               if (written < 0) {
-                       return -1;
-               }
-       }
+       memcpy(a, &rr->rrdata.a_rec, sizeof(struct in_addr));
 
-       *answer_ptr = a;
-       return written;
+       return resp_size;
 }
 
-static int rwrap_fake_a(const char *key,
-                       const char *value,
-                       uint8_t *answer_ptr,
-                       size_t anslen)
+static ssize_t rwrap_fake_aaaa(struct rwrap_fake_rr *rr,
+                              uint8_t *answer,
+                              size_t anslen)
 {
-       uint8_t *a = answer_ptr;
-       struct in_addr a_rec;
-       int rc;
-       int ok;
+       uint8_t *a = answer;
+       ssize_t resp_size;
 
-       if (value == NULL) {
-               RWRAP_LOG(RWRAP_LOG_ERROR, "Malformed record, no value!\n");
+       if (rr == NULL || rr->type != ns_t_aaaa) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Malformed record, no or wrong value!\n");
                return -1;
        }
+       RWRAP_LOG(RWRAP_LOG_TRACE, "Adding AAAA RR");
 
-       rc = rwrap_fake_common(ns_t_a, key, sizeof(a_rec), &a, anslen);
-       if (rc < 0) {
+       resp_size = rwrap_fake_rdata_common(ns_t_aaaa, sizeof(struct in6_addr),
+                                           rr->key, anslen, &a);
+       if (resp_size < 0) {
                return -1;
        }
 
-       ok = inet_pton(AF_INET, value, &a_rec);
-       if (!ok) {
+       memcpy(a, &rr->rrdata.aaaa_rec, sizeof(struct in6_addr));
+
+       return resp_size;
+}
+
+static ssize_t rwrap_fake_srv(struct rwrap_fake_rr *rr,
+                             uint8_t *answer,
+                             size_t anslen)
+{
+       uint8_t *a = answer;
+       ssize_t resp_size;
+       size_t rdata_size;
+       unsigned char hostname_compressed[MAXDNAME];
+       ssize_t compressed_len;
+
+       if (rr == NULL || rr->type != ns_t_srv) {
                RWRAP_LOG(RWRAP_LOG_ERROR,
-                         "Failed to convert [%s] to binary\n", value);
+                         "Malformed record, no or wrong value!\n");
+               return -1;
+       }
+       RWRAP_LOG(RWRAP_LOG_TRACE, "Adding SRV RR");
+       rdata_size = 3 * sizeof(uint16_t);
+
+       /* Prepare the data to write */
+       compressed_len = ns_name_compress(rr->rrdata.srv_rec.hostname,
+                                         hostname_compressed, MAXDNAME,
+                                         NULL, NULL);
+       if (compressed_len < 0) {
                return -1;
        }
-       memcpy(a, &a_rec, sizeof(struct in_addr));
+       rdata_size += compressed_len;
 
-       return 0;
+       resp_size = rwrap_fake_rdata_common(ns_t_srv, rdata_size,
+                                           rr->key, anslen, &a);
+       if (resp_size < 0) {
+               return -1;
+       }
+
+       NS_PUT16(rr->rrdata.srv_rec.prio, a);
+       NS_PUT16(rr->rrdata.srv_rec.weight, a);
+       NS_PUT16(rr->rrdata.srv_rec.port, a);
+       memcpy(a, hostname_compressed, compressed_len);
+
+       return resp_size;
 }
 
-static int rwrap_fake_aaaa(const char *key,
-                          const char *value,
-                          uint8_t *answer,
-                          size_t anslen)
+static ssize_t rwrap_fake_soa(struct rwrap_fake_rr *rr,
+                             uint8_t *answer,
+                             size_t anslen)
 {
        uint8_t *a = answer;
-       struct in6_addr aaaa_rec;
-       int rc;
-       int ok;
+       ssize_t resp_size;
+       size_t rdata_size;
+       unsigned char nameser_compressed[MAXDNAME];
+       ssize_t compressed_ns_len;
+       unsigned char mailbox_compressed[MAXDNAME];
+       ssize_t compressed_mb_len;
+
+       if (rr == NULL || rr->type != ns_t_soa) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Malformed record, no or wrong value!\n");
+               return -1;
+       }
+       RWRAP_LOG(RWRAP_LOG_TRACE, "Adding SOA RR");
+       rdata_size = 5 * sizeof(uint16_t);
 
-       if (value == NULL) {
-               RWRAP_LOG(RWRAP_LOG_ERROR, "Malformed record, no value!\n");
+       compressed_ns_len = ns_name_compress(rr->rrdata.soa_rec.nameserver,
+                                            nameser_compressed,
+                                            MAXDNAME, NULL, NULL);
+       if (compressed_ns_len < 0) {
                return -1;
        }
+       rdata_size += compressed_ns_len;
 
-       rc = rwrap_fake_common(ns_t_aaaa, key, sizeof(aaaa_rec), &a, anslen);
-       if (rc < 0) {
+       compressed_mb_len = ns_name_compress(rr->rrdata.soa_rec.mailbox,
+                                            mailbox_compressed,
+                                            MAXDNAME, NULL, NULL);
+       if (compressed_mb_len < 0) {
                return -1;
        }
+       rdata_size += compressed_mb_len;
 
-       ok = inet_pton(AF_INET6, value, &aaaa_rec);
-       if (!ok) {
-               RWRAP_LOG(RWRAP_LOG_ERROR,
-                         "Failed to convert [%s] to binary\n", value);
+       resp_size = rwrap_fake_rdata_common(ns_t_soa, rdata_size,
+                                           rr->key, anslen, &a);
+       if (resp_size < 0) {
                return -1;
        }
-       memcpy(a, &aaaa_rec, sizeof(struct in6_addr));
 
-       return 0;
+       memcpy(a, nameser_compressed, compressed_ns_len);
+       a += compressed_ns_len;
+       memcpy(a, mailbox_compressed, compressed_mb_len);
+       a += compressed_mb_len;
+       NS_PUT32(rr->rrdata.soa_rec.serial, a);
+       NS_PUT32(rr->rrdata.soa_rec.refresh, a);
+       NS_PUT32(rr->rrdata.soa_rec.retry, a);
+       NS_PUT32(rr->rrdata.soa_rec.expire, a);
+       NS_PUT32(rr->rrdata.soa_rec.minimum, a);
+
+       return resp_size;
 }
 
-static int rwrap_fake_empty_query(const char *key,
-                                 uint16_t type,
-                                 uint8_t *answer,
-                                 size_t anslen)
+static ssize_t rwrap_fake_cname(struct rwrap_fake_rr *rr,
+                               uint8_t *answer,
+                               size_t anslen)
 {
-       int rc;
+       uint8_t *a = answer;
+       ssize_t resp_size;
+       unsigned char hostname_compressed[MAXDNAME];
+       ssize_t rdata_size;
 
-       rc = rwrap_fake_common(type, key, 0, &answer, anslen);
-       if (rc < 0) {
+       if (rr == NULL || rr->type != ns_t_cname) {
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                         "Malformed record, no or wrong value!\n");
                return -1;
        }
+       RWRAP_LOG(RWRAP_LOG_TRACE, "Adding CNAME RR");
 
-       return 0;
+       /* Prepare the data to write */
+       rdata_size = ns_name_compress(rr->rrdata.cname_rec,
+                                     hostname_compressed, MAXDNAME,
+                                     NULL, NULL);
+       if (rdata_size < 0) {
+               return -1;
+       }
+
+       resp_size = rwrap_fake_rdata_common(ns_t_cname, rdata_size,
+                                           rr->key, anslen, &a);
+       if (resp_size < 0) {
+               return -1;
+       }
+
+       memcpy(a, hostname_compressed, rdata_size);
+
+       return resp_size;
 }
 
 #define RESOLV_MATCH(line, name) \
@@ -346,41 +601,61 @@ static int rwrap_fake_empty_query(const char *key,
        (line[sizeof(name) - 1] == ' ' || \
         line[sizeof(name) - 1] == '\t'))
 
-#define NEXT_KEY(buf, key) do {                        \
-       (key) = strpbrk(buf, " \t");            \
-       if ((key) != NULL) {                    \
-               (key)[0] = '\0';                \
-               (key)++;                        \
-       }                                       \
-       while ((key) != NULL                    \
-              && (isblank((int)(key)[0]))) {   \
-               (key)++;                        \
-       }                                       \
-} while(0);
-
 #define TYPE_MATCH(type, ns_type, rec_type, str_type, key, query) \
        ((type) == (ns_type) && \
         (strncmp((rec_type), (str_type), sizeof(str_type)) == 0) && \
-        (strcmp(key, query)) == 0)
+        (strcasecmp(key, query)) == 0)
 
 
-/* Reads in a file in the following format:
- * TYPE RDATA
- *
- * Malformed entried are silently skipped.
- * Allocates answer buffer of size anslen that has to be freed after use.
- */
-static int rwrap_res_fake_hosts(const char *hostfile,
-                               const char *query,
-                               int type,
-                               unsigned char *answer,
-                               size_t anslen)
+static int rwrap_get_record(const char *hostfile, unsigned recursion,
+                           const char *query, int type,
+                           struct rwrap_fake_rr *rr);
+
+static int rwrap_srv_recurse(const char *hostfile, unsigned recursion,
+                            const char *query, struct rwrap_fake_rr *rr)
+{
+       int rc;
+
+       rc = rwrap_get_record(hostfile, recursion, query, ns_t_a, rr);
+       if (rc == 0) return 0;
+
+       rc = rwrap_get_record(hostfile, recursion, query, ns_t_aaaa, rr);
+       if (rc == ENOENT) rc = 0;
+
+       return rc;
+}
+
+static int rwrap_cname_recurse(const char *hostfile, unsigned recursion,
+                              const char *query, struct rwrap_fake_rr *rr)
+{
+       int rc;
+
+       rc = rwrap_get_record(hostfile, recursion, query, ns_t_a, rr);
+       if (rc == 0) return 0;
+
+       rc = rwrap_get_record(hostfile, recursion, query, ns_t_aaaa, rr);
+       if (rc == 0) return 0;
+
+       rc = rwrap_get_record(hostfile, recursion, query, ns_t_cname, rr);
+       if (rc == ENOENT) rc = 0;
+
+       return rc;
+}
+
+static int rwrap_get_record(const char *hostfile, unsigned recursion,
+                           const char *query, int type,
+                           struct rwrap_fake_rr *rr)
 {
        FILE *fp = NULL;
        char buf[BUFSIZ];
-       int rc = ENOENT;
        char *key = NULL;
        char *value = NULL;
+       int rc = ENOENT;
+
+       if (recursion >= RWRAP_MAX_RECURSION) {
+               RWRAP_LOG(RWRAP_LOG_ERROR, "Recursed too deep!\n");
+               return -1;
+       }
 
        RWRAP_LOG(RWRAP_LOG_TRACE,
                  "Searching in fake hosts file %s\n", hostfile);
@@ -403,12 +678,6 @@ static int rwrap_res_fake_hosts(const char *hostfile,
                NEXT_KEY(rec_type, key);
                NEXT_KEY(key, value);
 
-               q = value;
-               while(q[0] != '\n' && q[0] != '\0') {
-                       q++;
-               }
-               q[0] = '\0';
-
                if (key == NULL || value == NULL) {
                        RWRAP_LOG(RWRAP_LOG_WARN,
                                "Malformed line: not enough parts, use \"rec_type key data\n"
@@ -416,34 +685,290 @@ static int rwrap_res_fake_hosts(const char *hostfile,
                        continue;
                }
 
+               q = value;
+               while(q[0] != '\n' && q[0] != '\0') {
+                       q++;
+               }
+               q[0] = '\0';
+
                if (TYPE_MATCH(type, ns_t_a, rec_type, "A", key, query)) {
-                       rc = rwrap_fake_a(key, value, answer, anslen);
+                       rc = rwrap_create_fake_a_rr(key, value, rr);
                        break;
                } else if (TYPE_MATCH(type, ns_t_aaaa,
                                      rec_type, "AAAA", key, query)) {
-                       rc = rwrap_fake_aaaa(key, value, answer, anslen);
+                       rc = rwrap_create_fake_aaaa_rr(key, value, rr);
+                       break;
+               } else if (TYPE_MATCH(type, ns_t_srv,
+                                     rec_type, "SRV", key, query)) {
+                       rc = rwrap_create_fake_srv_rr(key, value, rr);
+                       if (rc == 0) {
+                               rc = rwrap_srv_recurse(hostfile, recursion+1,
+                                               rr->rrdata.srv_rec.hostname,
+                                               rr + 1);
+                       }
+                       break;
+               } else if (TYPE_MATCH(type, ns_t_soa,
+                                     rec_type, "SOA", key, query)) {
+                       rc = rwrap_create_fake_soa_rr(key, value, rr);
+                       break;
+               } else if (TYPE_MATCH(type, ns_t_cname,
+                                     rec_type, "CNAME", key, query)) {
+                       rc = rwrap_create_fake_cname_rr(key, value, rr);
+                       if (rc == 0) {
+                               rc = rwrap_cname_recurse(hostfile, recursion+1,
+                                                        value, rr + 1);
+                       }
+                       break;
+               } else if (TYPE_MATCH(type, ns_t_a, rec_type, "CNAME", key, query)) {
+                       rc = rwrap_create_fake_cname_rr(key, value, rr);
+                       if (rc == 0) {
+                               rc = rwrap_cname_recurse(hostfile, recursion+1,
+                                                        value, rr + 1);
+                       }
+                       break;
+               }
+       }
+
+       if (rc == ENOENT && recursion == 0) {
+               RWRAP_LOG(RWRAP_LOG_TRACE, "Record for [%s] not found\n", query);
+               memcpy(rr->key, key, strlen(key) + 1);
+       }
+
+       fclose(fp);
+       return rc;
+}
+
+static ssize_t rwrap_fake_empty(int type,
+                               const char *question,
+                               uint8_t *answer,
+                               size_t anslen)
+{
+       ssize_t resp_data;
+       size_t remaining = anslen;
+
+       resp_data = rwrap_fake_header(&answer, remaining, 0, 0);
+       if (resp_data < 0) {
+               return -1;
+       }
+       remaining -= resp_data;
+
+       resp_data += rwrap_fake_question(question, type, &answer, remaining);
+       if (resp_data < 0) {
+               return -1;
+       }
+       remaining -= resp_data;
+
+       resp_data += rwrap_fake_rdata_common(type, 0, question,
+                                           remaining, &answer);
+       if (resp_data < 0) {
+               return -1;
+       }
+
+       return resp_data;
+}
+
+static inline bool rwrap_known_type(int type)
+{
+       switch (type) {
+       case ns_t_a:
+       case ns_t_aaaa:
+       case ns_t_srv:
+       case ns_t_soa:
+       case ns_t_cname:
+               return true;
+       }
+
+       return false;
+}
+
+static int rwrap_ancount(struct rwrap_fake_rr *rrs, int qtype)
+{
+       int i;
+       int ancount = 0;
+
+       /* Include all RRs in the stack until the sought type
+        * in the answer section. This is the case i.e. when looking
+        * up an A record but the name points to a CNAME
+        */
+       for (i = 0; i < RWRAP_MAX_RECURSION; i++) {
+               ancount++;
+
+               if (rwrap_known_type(rrs[i].type) &&
+                   rrs[i].type == qtype) {
                        break;
                }
        }
 
+       /* Return 0 records if the sought type wasn't in the stack */
+       return i < RWRAP_MAX_RECURSION ? ancount : 0;
+}
+
+static int rwrap_arcount(struct rwrap_fake_rr *rrs, int ancount)
+{
+       int i;
+       int arcount = 0;
+
+       /* start from index ancount */
+       for (i = ancount; i < RWRAP_MAX_RECURSION; i++) {
+               if (rwrap_known_type(rrs[i].type)) {
+                       arcount++;
+               }
+       }
+
+       return arcount;
+}
+
+static ssize_t rwrap_add_rr(struct rwrap_fake_rr *rr,
+                           uint8_t *answer,
+                           size_t anslen)
+{
+       ssize_t resp_data;
+
+       switch (rr->type) {
+       case ns_t_a:
+               resp_data = rwrap_fake_a(rr, answer, anslen);
+               break;
+       case ns_t_aaaa:
+               resp_data = rwrap_fake_aaaa(rr, answer, anslen);
+               break;
+       case ns_t_srv:
+               resp_data = rwrap_fake_srv(rr, answer, anslen);
+               break;
+       case ns_t_soa:
+               resp_data = rwrap_fake_soa(rr, answer, anslen);
+               break;
+       case ns_t_cname:
+               resp_data = rwrap_fake_cname(rr, answer, anslen);
+               break;
+       default:
+               return -1;
+       }
+
+       return resp_data;
+}
+
+static ssize_t rwrap_fake_answer(struct rwrap_fake_rr *rrs,
+                                int type,
+                                uint8_t *answer,
+                                size_t anslen)
+
+{
+       ssize_t resp_data;
+       ssize_t rrlen;
+       size_t remaining = anslen;
+       int ancount;
+       int arcount;
+       int i;
+
+       ancount = rwrap_ancount(rrs, type);
+       arcount = rwrap_arcount(rrs, ancount);
+       RWRAP_LOG(RWRAP_LOG_TRACE,
+                 "Got %d answers and %d additional records\n", ancount, arcount);
+
+       resp_data = rwrap_fake_header(&answer, remaining, ancount, arcount);
+       if (resp_data < 0) {
+               return -1;
+       }
+       remaining -= resp_data;
+
+       resp_data += rwrap_fake_question(rrs->key, rrs->type, &answer, remaining);
+       if (resp_data < 0) {
+               return -1;
+       }
+       remaining -= resp_data;
+
+       /* answer */
+       for (i = 0; i < ancount; i++) {
+               rrlen = rwrap_add_rr(&rrs[i], answer, remaining);
+               if (rrlen < 0) {
+                       return -1;
+               }
+               remaining -= rrlen;
+               answer += rrlen;
+               resp_data += rrlen;
+       }
+
+       /* add authoritative NS here? */
+
+       /* additional records */
+       for (i = ancount; i < ancount + arcount; i++) {
+               rrlen = rwrap_add_rr(&rrs[i], answer, remaining);
+               if (rrlen < 0) {
+                       return -1;
+               }
+               remaining -= rrlen;
+               answer += rrlen;
+               resp_data += rrlen;
+       }
+
+       return resp_data;
+}
+
+/* Reads in a file in the following format:
+ * TYPE RDATA
+ *
+ * Malformed entried are silently skipped.
+ * Allocates answer buffer of size anslen that has to be freed after use.
+ */
+static int rwrap_res_fake_hosts(const char *hostfile,
+                               const char *query,
+                               int type,
+                               unsigned char *answer,
+                               size_t anslen)
+{
+       int rc = ENOENT;
+       char *query_name = NULL;
+       size_t qlen = strlen(query);
+       struct rwrap_fake_rr rrs[RWRAP_MAX_RECURSION];
+       ssize_t resp_size;
+
+       RWRAP_LOG(RWRAP_LOG_TRACE,
+                 "Searching in fake hosts file %s\n", hostfile);
+
+       if (qlen > 0 && query[qlen-1] == '.') {
+               qlen--;
+       }
+
+       query_name = strndup(query, qlen);
+       if (query_name == NULL) {
+               return -1;
+       }
+
+       rwrap_fake_rr_init(rrs, RWRAP_MAX_RECURSION);
+
+       rc = rwrap_get_record(hostfile, 0, query_name, type, rrs);
        switch (rc) {
        case 0:
                RWRAP_LOG(RWRAP_LOG_TRACE,
-                               "Successfully faked answer for [%s]\n", query);
+                               "Found record for [%s]\n", query_name);
+               resp_size = rwrap_fake_answer(rrs, type, answer, anslen);
                break;
+       case ENOENT:
+               RWRAP_LOG(RWRAP_LOG_TRACE,
+                               "No record for [%s]\n", query_name);
+               resp_size = rwrap_fake_empty(type, rrs->key, answer, anslen);
+               break;
+       default:
+               RWRAP_LOG(RWRAP_LOG_ERROR,
+                               "Error searching for [%s]\n", query_name);
+               free(query_name);
+               return -1;
+       }
+
+       switch (resp_size) {
        case -1:
                RWRAP_LOG(RWRAP_LOG_ERROR,
-                               "Error faking answer for [%s]\n", query);
+                               "Error faking answer for [%s]\n", query_name);
                break;
-       case ENOENT:
+       default:
                RWRAP_LOG(RWRAP_LOG_TRACE,
-                               "Record for [%s] not found\n", query);
-               rc = rwrap_fake_empty_query(key, type, answer, anslen);
+                               "Successfully faked answer for [%s]\n",
+                               query_name);
                break;
        }
 
-       fclose(fp);
-       return rc;
+       free(query_name);
+       return resp_size;
 }
 
 /*********************************************************
@@ -643,7 +1168,12 @@ static int libc_res_init(void)
 static int libc_res_ninit(struct __res_state *state)
 {
 #if defined(HAVE_RES_NINIT)
+
+#if defined(HAVE_RES_NINIT_IN_LIBRESOLV)
+       rwrap_load_lib_function(RWRAP_LIBRESOLV, res_ninit);
+#else /* HAVE_RES_NINIT_IN_LIBRESOLV */
        rwrap_load_lib_function(RWRAP_LIBC, res_ninit);
+#endif /* HAVE_RES_NINIT_IN_LIBRESOLV */
 
        return rwrap.fns.libc_res_ninit(state);
 #elif defined(HAVE___RES_NINIT)
@@ -658,7 +1188,12 @@ static int libc_res_ninit(struct __res_state *state)
 static void libc_res_nclose(struct __res_state *state)
 {
 #if defined(HAVE_RES_NCLOSE)
+
+#if defined(HAVE_RES_NCLOSE_IN_LIBRESOLV)
+       rwrap_load_lib_function(RWRAP_LIBRESOLV, res_nclose);
+#else /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
        rwrap_load_lib_function(RWRAP_LIBC, res_nclose);
+#endif /* HAVE_RES_NCLOSE_IN_LIBRESOLV */
 
        rwrap.fns.libc_res_nclose(state);
 #elif defined(HAVE___RES_NCLOSE)
@@ -781,6 +1316,7 @@ static int rwrap_parse_resolv_conf(struct __res_state *state,
                                        .sin_family = AF_INET,
                                        .sin_addr = a,
                                        .sin_port = htons(53),
+                                       .sin_zero = { 0 },
                                };
 
                                state->nscount++;
@@ -795,6 +1331,7 @@ static int rwrap_parse_resolv_conf(struct __res_state *state,
 
                                        sa6 = malloc(sizeof(*sa6));
                                        if (sa6 == NULL) {
+                                               fclose(fp);
                                                return -1;
                                        }
 
@@ -834,9 +1371,11 @@ static int rwrap_parse_resolv_conf(struct __res_state *state,
                RWRAP_LOG(RWRAP_LOG_ERROR,
                          "Reading from %s failed",
                          resolv_conf);
+               fclose(fp);
                return -1;
        }
 
+       fclose(fp);
        return 0;
 }
 
@@ -864,8 +1403,7 @@ static int rwrap_res_ninit(struct __res_state *state)
                        state->_u._ext.nscount = 0;
 #ifdef HAVE_RESOLV_IPV6_NSADDRS
                        for (i = 0; i < state->_u._ext.nscount; i++) {
-                               free(state->_u._ext.nsaddrs[i]);
-                               state->_u._ext.nssocks[i] = 0;
+                               SAFE_FREE(state->_u._ext.nsaddrs[i]);
                        }
 #endif
 
@@ -915,7 +1453,19 @@ int __res_init(void)
 
 static void rwrap_res_nclose(struct __res_state *state)
 {
+#ifdef HAVE_RESOLV_IPV6_NSADDRS
+       int i;
+#endif
+
        libc_res_nclose(state);
+
+#ifdef HAVE_RESOLV_IPV6_NSADDRS
+       if (state != NULL) {
+               for (i = 0; i < state->_u._ext.nscount; i++) {
+                       SAFE_FREE(state->_u._ext.nsaddrs[i]);
+               }
+       }
+#endif
 }
 
 #if defined(HAVE_RES_NCLOSE)
@@ -924,7 +1474,7 @@ void res_nclose(struct __res_state *state)
 void __res_nclose(struct __res_state *state)
 #endif
 {
-       libc_res_nclose(state);
+       rwrap_res_nclose(state);
 }
 
 /****************************************************************************