]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - src/resolve/resolved-dns-cache.c
Add SPDX license identifiers to source files under the LGPL
[thirdparty/systemd.git] / src / resolve / resolved-dns-cache.c
index 1ac8a223d82c2b70a07323f58730221a62d5dacb..942956dd718770bd600398e22d989210d45b8daa 100644 (file)
@@ -1,5 +1,4 @@
-/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
-
+/* SPDX-License-Identifier: LGPL-2.1+ */
 /***
   This file is part of systemd.
 
@@ -19,6 +18,9 @@
   along with systemd; If not, see <http://www.gnu.org/licenses/>.
 ***/
 
+#include <net/if.h>
+
+#include "af-list.h"
 #include "alloc-util.h"
 #include "dns-domain.h"
 #include "resolved-dns-answer.h"
 /* We never keep any item longer than 2h in our cache */
 #define CACHE_TTL_MAX_USEC (2 * USEC_PER_HOUR)
 
+/* How long to cache strange rcodes, i.e. rcodes != SUCCESS and != NXDOMAIN (specifically: that's only SERVFAIL for
+ * now) */
+#define CACHE_TTL_STRANGE_RCODE_USEC (30 * USEC_PER_SEC)
+
 typedef enum DnsCacheItemType DnsCacheItemType;
 typedef struct DnsCacheItem DnsCacheItem;
 
@@ -40,12 +46,14 @@ enum DnsCacheItemType {
         DNS_CACHE_POSITIVE,
         DNS_CACHE_NODATA,
         DNS_CACHE_NXDOMAIN,
+        DNS_CACHE_RCODE,      /* "strange" RCODE (effective only SERVFAIL for now) */
 };
 
 struct DnsCacheItem {
         DnsCacheItemType type;
         DnsResourceKey *key;
         DnsResourceRecord *rr;
+        int rcode;
 
         usec_t until;
         bool authenticated:1;
@@ -59,6 +67,27 @@ struct DnsCacheItem {
         LIST_FIELDS(DnsCacheItem, by_key);
 };
 
+static const char *dns_cache_item_type_to_string(DnsCacheItem *item) {
+        assert(item);
+
+        switch (item->type) {
+
+        case DNS_CACHE_POSITIVE:
+                return "POSITIVE";
+
+        case DNS_CACHE_NODATA:
+                return "NODATA";
+
+        case DNS_CACHE_NXDOMAIN:
+                return "NXDOMAIN";
+
+        case DNS_CACHE_RCODE:
+                return dns_rcode_to_string(item->rcode);
+        }
+
+        return NULL;
+}
+
 static void dns_cache_item_free(DnsCacheItem *i) {
         if (!i)
                 return;
@@ -182,6 +211,7 @@ void dns_cache_prune(DnsCache *c) {
 
         for (;;) {
                 DnsCacheItem *i;
+                char key_str[DNS_RESOURCE_KEY_STRING_MAX];
 
                 i = prioq_peek(c->by_expiry);
                 if (!i)
@@ -194,8 +224,12 @@ void dns_cache_prune(DnsCache *c) {
                         break;
 
                 /* Depending whether this is an mDNS shared entry
-                 * either remove only this one RR or the whole
-                 * RRset */
+                 * either remove only this one RR or the whole RRset */
+                log_debug("Removing %scache entry for %s (expired "USEC_FMT"s ago)",
+                          i->shared_owner ? "shared " : "",
+                          dns_resource_key_to_string(i->key, key_str, sizeof key_str),
+                          (t - i->until) / USEC_PER_SEC);
+
                 if (i->shared_owner)
                         dns_cache_item_unlink_and_free(c, i);
                 else {
@@ -377,8 +411,8 @@ static int dns_cache_put_positive(
                 const union in_addr_union *owner_address) {
 
         _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
-        _cleanup_free_ char *key_str = NULL;
         DnsCacheItem *existing;
+        char key_str[DNS_RESOURCE_KEY_STRING_MAX], ifname[IF_NAMESIZE];
         int r, k;
 
         assert(c);
@@ -394,22 +428,13 @@ static int dns_cache_put_positive(
         /* New TTL is 0? Delete this specific entry... */
         if (rr->ttl <= 0) {
                 k = dns_cache_remove_by_rr(c, rr);
-
-                if (log_get_max_level() >= LOG_DEBUG) {
-                        r = dns_resource_key_to_string(rr->key, &key_str);
-                        if (r < 0)
-                                return r;
-
-                        if (k > 0)
-                                log_debug("Removed zero TTL entry from cache: %s", key_str);
-                        else
-                                log_debug("Not caching zero TTL cache entry: %s", key_str);
-                }
-
+                log_debug("%s: %s",
+                          k > 0 ? "Removed zero TTL entry from cache" : "Not caching zero TTL cache entry",
+                          dns_resource_key_to_string(rr->key, key_str, sizeof key_str));
                 return 0;
         }
 
-        /* Entry exists already? Update TTL, timestamp and owner*/
+        /* Entry exists already? Update TTL, timestamp and owner */
         existing = dns_cache_get(c, rr);
         if (existing) {
                 dns_cache_item_update_positive(
@@ -452,11 +477,18 @@ static int dns_cache_put_positive(
                 return r;
 
         if (log_get_max_level() >= LOG_DEBUG) {
-                r = dns_resource_key_to_string(i->key, &key_str);
-                if (r < 0)
-                        return r;
-
-                log_debug("Added positive cache entry for %s", key_str);
+                _cleanup_free_ char *t = NULL;
+
+                (void) in_addr_to_string(i->owner_family, &i->owner_address, &t);
+
+                log_debug("Added positive %s%s cache entry for %s "USEC_FMT"s on %s/%s/%s",
+                          i->authenticated ? "authenticated" : "unauthenticated",
+                          i->shared_owner ? " shared" : "",
+                          dns_resource_key_to_string(i->key, key_str, sizeof key_str),
+                          (i->until - timestamp) / USEC_PER_SEC,
+                          i->ifindex == 0 ? "*" : strna(if_indextoname(i->ifindex, ifname)),
+                          af_to_name_short(i->owner_family),
+                          strna(t));
         }
 
         i = NULL;
@@ -475,12 +507,11 @@ static int dns_cache_put_negative(
                 const union in_addr_union *owner_address) {
 
         _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
-        _cleanup_free_ char *key_str = NULL;
+        char key_str[DNS_RESOURCE_KEY_STRING_MAX];
         int r;
 
         assert(c);
         assert(key);
-        assert(soa);
         assert(owner_address);
 
         /* Never cache pseudo RR keys. DNS_TYPE_ANY is particularly
@@ -491,19 +522,17 @@ static int dns_cache_put_negative(
         if (dns_type_is_pseudo(key->type))
                 return 0;
 
-        if (nsec_ttl <= 0 || soa->soa.minimum <= 0 || soa->ttl <= 0) {
-                if (log_get_max_level() >= LOG_DEBUG) {
-                        r = dns_resource_key_to_string(key, &key_str);
-                        if (r < 0)
-                                return r;
+        if (IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN)) {
+                if (!soa)
+                        return 0;
 
-                        log_debug("Not caching negative entry with zero SOA/NSEC/NSEC3 TTL: %s", key_str);
+                /* For negative replies, check if we have a TTL of a SOA */
+                if (nsec_ttl <= 0 || soa->soa.minimum <= 0 || soa->ttl <= 0) {
+                        log_debug("Not caching negative entry with zero SOA/NSEC/NSEC3 TTL: %s",
+                                  dns_resource_key_to_string(key, key_str, sizeof key_str));
+                        return 0;
                 }
-
-                return 0;
-        }
-
-        if (!IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
+        } else if (rcode != DNS_RCODE_SERVFAIL)
                 return 0;
 
         r = dns_cache_init(c);
@@ -516,17 +545,22 @@ static int dns_cache_put_negative(
         if (!i)
                 return -ENOMEM;
 
-        i->type = rcode == DNS_RCODE_SUCCESS ? DNS_CACHE_NODATA : DNS_CACHE_NXDOMAIN;
-        i->until = calculate_until(soa, nsec_ttl, timestamp, true);
+        i->type =
+                rcode == DNS_RCODE_SUCCESS ? DNS_CACHE_NODATA :
+                rcode == DNS_RCODE_NXDOMAIN ? DNS_CACHE_NXDOMAIN : DNS_CACHE_RCODE;
+        i->until =
+                i->type == DNS_CACHE_RCODE ? timestamp + CACHE_TTL_STRANGE_RCODE_USEC :
+                calculate_until(soa, nsec_ttl, timestamp, true);
         i->authenticated = authenticated;
         i->owner_family = owner_family;
         i->owner_address = *owner_address;
         i->prioq_idx = PRIOQ_IDX_NULL;
+        i->rcode = rcode;
 
         if (i->type == DNS_CACHE_NXDOMAIN) {
                 /* NXDOMAIN entries should apply equally to all types, so we use ANY as
                  * a pseudo type for this purpose here. */
-                i->key = dns_resource_key_new(key->class, DNS_TYPE_ANY, DNS_RESOURCE_KEY_NAME(key));
+                i->key = dns_resource_key_new(key->class, DNS_TYPE_ANY, dns_resource_key_name(key));
                 if (!i->key)
                         return -ENOMEM;
 
@@ -544,13 +578,10 @@ static int dns_cache_put_negative(
         if (r < 0)
                 return r;
 
-        if (log_get_max_level() >= LOG_DEBUG) {
-                r = dns_resource_key_to_string(i->key, &key_str);
-                if (r < 0)
-                        return r;
-
-                log_debug("Added %s cache entry for %s", i->type == DNS_CACHE_NODATA ? "NODATA" : "NXDOMAIN", key_str);
-        }
+        log_debug("Added %s cache entry for %s "USEC_FMT"s",
+                  dns_cache_item_type_to_string(i),
+                  dns_resource_key_to_string(i->key, key_str, sizeof key_str),
+                  (i->until - timestamp) / USEC_PER_SEC);
 
         i = NULL;
         return 0;
@@ -620,6 +651,7 @@ int dns_cache_put(
                 const union in_addr_union *owner_address) {
 
         DnsResourceRecord *soa = NULL, *rr;
+        bool weird_rcode = false;
         DnsAnswerFlags flags;
         unsigned cache_keys;
         int r, ifindex;
@@ -629,29 +661,33 @@ int dns_cache_put(
 
         dns_cache_remove_previous(c, key, answer);
 
-        if (dns_answer_size(answer) <= 0) {
-                if (log_get_max_level() >= LOG_DEBUG) {
-                        _cleanup_free_ char *key_str = NULL;
+        /* We only care for positive replies and NXDOMAINs, on all other replies we will simply flush the respective
+         * entries, and that's it. (Well, with one further exception: since some DNS zones (akamai!) return SERVFAIL
+         * consistently for some lookups, and forwarders tend to propagate that we'll cache that too, but only for a
+         * short time.) */
 
-                        r = dns_resource_key_to_string(key, &key_str);
-                        if (r < 0)
-                                return r;
+        if (IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN)) {
+
+                if (dns_answer_size(answer) <= 0) {
+                        char key_str[DNS_RESOURCE_KEY_STRING_MAX];
 
-                        log_debug("Not caching negative entry without a SOA record: %s", key_str);
+                        log_debug("Not caching negative entry without a SOA record: %s",
+                                  dns_resource_key_to_string(key, key_str, sizeof key_str));
+                        return 0;
                 }
 
-                return 0;
-        }
+        } else {
+                /* Only cache SERVFAIL as "weird" rcode for now. We can add more later, should that turn out to be
+                 * beneficial. */
+                if (rcode != DNS_RCODE_SERVFAIL)
+                        return 0;
 
-        /* We only care for positive replies and NXDOMAINs, on all
-         * other replies we will simply flush the respective entries,
-         * and that's it */
-        if (!IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
-                return 0;
+                weird_rcode = true;
+        }
 
         cache_keys = dns_answer_size(answer);
         if (key)
-                cache_keys ++;
+                cache_keys++;
 
         /* Make some space for our new entries */
         dns_cache_make_space(c, cache_keys);
@@ -701,19 +737,20 @@ int dns_cache_put(
         if (r > 0)
                 return 0;
 
-        /* See https://tools.ietf.org/html/rfc2308, which say that a
-         * matching SOA record in the packet is used to to enable
-         * negative caching. */
+        /* See https://tools.ietf.org/html/rfc2308, which say that a matching SOA record in the packet is used to
+         * enable negative caching. We apply one exception though: if we are about to cache a weird rcode we do so
+         * regardless of a SOA. */
         r = dns_answer_find_soa(answer, key, &soa, &flags);
         if (r < 0)
                 goto fail;
-        if (r == 0)
-                return 0;
-
-        /* Refuse using the SOA data if it is unsigned, but the key is
-         * signed */
-        if (authenticated && (flags & DNS_ANSWER_AUTHENTICATED) == 0)
+        if (r == 0 && !weird_rcode)
                 return 0;
+        if (r > 0) {
+                /* Refuse using the SOA data if it is unsigned, but the key is
+                 * signed */
+                if (authenticated && (flags & DNS_ANSWER_AUTHENTICATED) == 0)
+                        return 0;
+        }
 
         r = dns_cache_put_negative(
                         c,
@@ -761,7 +798,7 @@ static DnsCacheItem *dns_cache_get_by_key_follow_cname_dname_nsec(DnsCache *c, D
         if (i)
                 return i;
 
-        n = DNS_RESOURCE_KEY_NAME(k);
+        n = dns_resource_key_name(k);
 
         /* Check if we have an NXDOMAIN cache item for the name, notice that we use
          * the pseudo-type ANY for NXDOMAIN cache items. */
@@ -801,14 +838,16 @@ static DnsCacheItem *dns_cache_get_by_key_follow_cname_dname_nsec(DnsCache *c, D
         return NULL;
 }
 
-int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **ret, bool *authenticated) {
+int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, bool clamp_ttl, int *rcode, DnsAnswer **ret, bool *authenticated) {
         _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
+        char key_str[DNS_RESOURCE_KEY_STRING_MAX];
         unsigned n = 0;
         int r;
         bool nxdomain = false;
-        _cleanup_free_ char *key_str = NULL;
         DnsCacheItem *j, *first, *nsec = NULL;
         bool have_authenticated = false, have_non_authenticated = false;
+        usec_t current;
+        int found_rcode = -1;
 
         assert(c);
         assert(key);
@@ -816,24 +855,19 @@ int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **r
         assert(ret);
         assert(authenticated);
 
-        if (key->type == DNS_TYPE_ANY ||
-            key->class == DNS_CLASS_ANY) {
-
+        if (key->type == DNS_TYPE_ANY || key->class == DNS_CLASS_ANY) {
                 /* If we have ANY lookups we don't use the cache, so
                  * that the caller refreshes via the network. */
 
-                if (log_get_max_level() >= LOG_DEBUG) {
-                        r = dns_resource_key_to_string(key, &key_str);
-                        if (r < 0)
-                                return r;
-
-                        log_debug("Ignoring cache for ANY lookup: %s", key_str);
-                }
+                log_debug("Ignoring cache for ANY lookup: %s",
+                          dns_resource_key_to_string(key, key_str, sizeof key_str));
 
                 c->n_miss++;
 
                 *ret = NULL;
                 *rcode = DNS_RCODE_SUCCESS;
+                *authenticated = false;
+
                 return 0;
         }
 
@@ -841,18 +875,15 @@ int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **r
         if (!first) {
                 /* If one question cannot be answered we need to refresh */
 
-                if (log_get_max_level() >= LOG_DEBUG) {
-                        r = dns_resource_key_to_string(key, &key_str);
-                        if (r < 0)
-                                return r;
-
-                        log_debug("Cache miss for %s", key_str);
-                }
+                log_debug("Cache miss for %s",
+                          dns_resource_key_to_string(key, key_str, sizeof key_str));
 
                 c->n_miss++;
 
                 *ret = NULL;
                 *rcode = DNS_RCODE_SUCCESS;
+                *authenticated = false;
+
                 return 0;
         }
 
@@ -864,6 +895,8 @@ int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **r
                         n++;
                 } else if (j->type == DNS_CACHE_NXDOMAIN)
                         nxdomain = true;
+                else if (j->type == DNS_CACHE_RCODE)
+                        found_rcode = j->rcode;
 
                 if (j->authenticated)
                         have_authenticated = true;
@@ -871,17 +904,25 @@ int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **r
                         have_non_authenticated = true;
         }
 
+        if (found_rcode >= 0) {
+                log_debug("RCODE %s cache hit for %s",
+                          dns_rcode_to_string(found_rcode),
+                          dns_resource_key_to_string(key, key_str, sizeof(key_str)));
+
+                *ret = NULL;
+                *rcode = found_rcode;
+                *authenticated = false;
+
+                c->n_hit++;
+                return 1;
+        }
+
         if (nsec && !IN_SET(key->type, DNS_TYPE_NSEC, DNS_TYPE_DS)) {
                 /* Note that we won't derive information for DS RRs from an NSEC, because we only cache NSEC RRs from
                  * the lower-zone of a zone cut, but the DS RRs are on the upper zone. */
 
-                if (log_get_max_level() >= LOG_DEBUG) {
-                        r = dns_resource_key_to_string(key, &key_str);
-                        if (r < 0)
-                                return r;
-
-                        log_debug("NSEC NODATA cache hit for %s", key_str);
-                }
+                log_debug("NSEC NODATA cache hit for %s",
+                          dns_resource_key_to_string(key, key_str, sizeof key_str));
 
                 /* We only found an NSEC record that matches our name.
                  * If it says the type doesn't exist report
@@ -902,16 +943,10 @@ int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **r
                 return 0;
         }
 
-        if (log_get_max_level() >= LOG_DEBUG) {
-                r = dns_resource_key_to_string(key, &key_str);
-                if (r < 0)
-                        return r;
-
-                log_debug("%s cache hit for %s",
-                          n > 0    ? "Positive" :
-                          nxdomain ? "NXDOMAIN" : "NODATA",
-                          key_str);
-        }
+        log_debug("%s cache hit for %s",
+                  n > 0    ? "Positive" :
+                  nxdomain ? "NXDOMAIN" : "NODATA",
+                  dns_resource_key_to_string(key, key_str, sizeof key_str));
 
         if (n <= 0) {
                 c->n_hit++;
@@ -926,11 +961,24 @@ int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **r
         if (!answer)
                 return -ENOMEM;
 
+        if (clamp_ttl)
+                current = now(clock_boottime_or_monotonic());
+
         LIST_FOREACH(by_key, j, first) {
+                _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
+
                 if (!j->rr)
                         continue;
 
-                r = dns_answer_add(answer, j->rr, j->ifindex, j->authenticated ? DNS_ANSWER_AUTHENTICATED : 0);
+                if (clamp_ttl) {
+                        rr = dns_resource_record_ref(j->rr);
+
+                        r = dns_resource_record_clamp_ttl(&rr, LESS_BY(j->until, current) / USEC_PER_SEC);
+                        if (r < 0)
+                                return r;
+                }
+
+                r = dns_answer_add(answer, rr ?: j->rr, j->ifindex, j->authenticated ? DNS_ANSWER_AUTHENTICATED : 0);
                 if (r < 0)
                         return r;
         }
@@ -1000,7 +1048,7 @@ int dns_cache_export_shared_to_packet(DnsCache *cache, DnsPacket *p) {
                         if (!j->shared_owner)
                                 continue;
 
-                        r = dns_packet_append_rr(p, j->rr, NULL, NULL);
+                        r = dns_packet_append_rr(p, j->rr, 0, NULL, NULL);
                         if (r == -EMSGSIZE && p->protocol == DNS_PROTOCOL_MDNS) {
                                 /* For mDNS, if we're unable to stuff all known answers into the given packet,
                                  * allocate a new one, push the RR into that one and link it to the current one.
@@ -1015,13 +1063,13 @@ int dns_cache_export_shared_to_packet(DnsCache *cache, DnsPacket *p) {
 
                                 /* continue with new packet */
                                 p = p->more;
-                                r = dns_packet_append_rr(p, j->rr, NULL, NULL);
+                                r = dns_packet_append_rr(p, j->rr, 0, NULL, NULL);
                         }
 
                         if (r < 0)
                                 return r;
 
-                        ancount ++;
+                        ancount++;
                 }
         }
 
@@ -1033,7 +1081,6 @@ int dns_cache_export_shared_to_packet(DnsCache *cache, DnsPacket *p) {
 void dns_cache_dump(DnsCache *cache, FILE *f) {
         Iterator iterator;
         DnsCacheItem *i;
-        int r;
 
         if (!cache)
                 return;
@@ -1059,16 +1106,11 @@ void dns_cache_dump(DnsCache *cache, FILE *f) {
                                 fputs(t, f);
                                 fputc('\n', f);
                         } else {
-                                _cleanup_free_ char *z = NULL;
-                                r = dns_resource_key_to_string(j->key, &z);
-                                if (r < 0) {
-                                        log_oom();
-                                        continue;
-                                }
+                                char key_str[DNS_RESOURCE_KEY_STRING_MAX];
 
-                                fputs(z, f);
+                                fputs(dns_resource_key_to_string(j->key, key_str, sizeof key_str), f);
                                 fputs(" -- ", f);
-                                fputs(j->type == DNS_CACHE_NODATA ? "NODATA" : "NXDOMAIN", f);
+                                fputs(dns_cache_item_type_to_string(j), f);
                                 fputc('\n', f);
                         }
                 }