1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
7 #include "dns-domain.h"
8 #include "format-util.h"
9 #include "resolved-dns-answer.h"
10 #include "resolved-dns-cache.h"
11 #include "resolved-dns-packet.h"
12 #include "string-util.h"
14 /* Never cache more than 4K entries. RFC 1536, Section 5 suggests to
15 * leave DNS caches unbounded, but that's crazy. */
16 #define CACHE_MAX 4096
18 /* We never keep any item longer than 2h in our cache */
19 #define CACHE_TTL_MAX_USEC (2 * USEC_PER_HOUR)
21 /* How long to cache strange rcodes, i.e. rcodes != SUCCESS and != NXDOMAIN (specifically: that's only SERVFAIL for
23 #define CACHE_TTL_STRANGE_RCODE_USEC (10 * USEC_PER_SEC)
25 #define CACHEABLE_QUERY_FLAGS (SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL)
27 typedef enum DnsCacheItemType DnsCacheItemType
;
28 typedef struct DnsCacheItem DnsCacheItem
;
30 enum DnsCacheItemType
{
34 DNS_CACHE_RCODE
, /* "strange" RCODE (effective only SERVFAIL for now) */
38 DnsCacheItemType type
;
40 DnsResourceKey
*key
; /* The key for this item, i.e. the lookup key */
41 DnsResourceRecord
*rr
; /* The RR for this item, i.e. the lookup value for positive queries */
42 DnsAnswer
*answer
; /* The full validated answer, if this is an RRset acquired via a "primary" lookup */
43 DnsPacket
*full_packet
; /* The full packet this information was acquired with */
46 uint64_t query_flags
; /* SD_RESOLVED_AUTHENTICATED and/or SD_RESOLVED_CONFIDENTIAL */
47 DnssecResult dnssec_result
;
51 union in_addr_union owner_address
;
54 LIST_FIELDS(DnsCacheItem
, by_key
);
59 /* Returns true if this is a cache item created as result of an explicit lookup, or created as "side-effect"
60 * of another request. "Primary" entries will carry the full answer data (with NSEC, …) that can aso prove
61 * wildcard expansion, non-existance and such, while entries that were created as "side-effect" just contain
62 * immediate RR data for the specified RR key, but nothing else. */
63 #define DNS_CACHE_ITEM_IS_PRIMARY(item) (!!(item)->answer)
65 static const char *dns_cache_item_type_to_string(DnsCacheItem
*item
) {
70 case DNS_CACHE_POSITIVE
:
73 case DNS_CACHE_NODATA
:
76 case DNS_CACHE_NXDOMAIN
:
80 return dns_rcode_to_string(item
->rcode
);
86 static DnsCacheItem
* dns_cache_item_free(DnsCacheItem
*i
) {
90 dns_resource_record_unref(i
->rr
);
91 dns_resource_key_unref(i
->key
);
92 dns_answer_unref(i
->answer
);
93 dns_packet_unref(i
->full_packet
);
96 DEFINE_TRIVIAL_CLEANUP_FUNC(DnsCacheItem
*, dns_cache_item_free
);
98 static void dns_cache_item_unlink_and_free(DnsCache
*c
, DnsCacheItem
*i
) {
106 first
= hashmap_get(c
->by_key
, i
->key
);
107 LIST_REMOVE(by_key
, first
, i
);
110 assert_se(hashmap_replace(c
->by_key
, first
->key
, first
) >= 0);
112 hashmap_remove(c
->by_key
, i
->key
);
114 prioq_remove(c
->by_expiry
, i
, &i
->prioq_idx
);
116 dns_cache_item_free(i
);
119 static bool dns_cache_remove_by_rr(DnsCache
*c
, DnsResourceRecord
*rr
) {
120 DnsCacheItem
*first
, *i
;
123 first
= hashmap_get(c
->by_key
, rr
->key
);
124 LIST_FOREACH(by_key
, i
, first
) {
125 r
= dns_resource_record_equal(i
->rr
, rr
);
129 dns_cache_item_unlink_and_free(c
, i
);
137 static bool dns_cache_remove_by_key(DnsCache
*c
, DnsResourceKey
*key
) {
138 DnsCacheItem
*first
, *i
, *n
;
143 first
= hashmap_remove(c
->by_key
, key
);
147 LIST_FOREACH_SAFE(by_key
, i
, n
, first
) {
148 prioq_remove(c
->by_expiry
, i
, &i
->prioq_idx
);
149 dns_cache_item_free(i
);
155 void dns_cache_flush(DnsCache
*c
) {
160 while ((key
= hashmap_first_key(c
->by_key
)))
161 dns_cache_remove_by_key(c
, key
);
163 assert(hashmap_size(c
->by_key
) == 0);
164 assert(prioq_size(c
->by_expiry
) == 0);
166 c
->by_key
= hashmap_free(c
->by_key
);
167 c
->by_expiry
= prioq_free(c
->by_expiry
);
170 static void dns_cache_make_space(DnsCache
*c
, unsigned add
) {
176 /* Makes space for n new entries. Note that we actually allow
177 * the cache to grow beyond CACHE_MAX, but only when we shall
178 * add more RRs to the cache than CACHE_MAX at once. In that
179 * case the cache will be emptied completely otherwise. */
182 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*key
= NULL
;
185 if (prioq_size(c
->by_expiry
) <= 0)
188 if (prioq_size(c
->by_expiry
) + add
< CACHE_MAX
)
191 i
= prioq_peek(c
->by_expiry
);
194 /* Take an extra reference to the key so that it
195 * doesn't go away in the middle of the remove call */
196 key
= dns_resource_key_ref(i
->key
);
197 dns_cache_remove_by_key(c
, key
);
201 void dns_cache_prune(DnsCache
*c
) {
206 /* Remove all entries that are past their TTL */
210 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
212 i
= prioq_peek(c
->by_expiry
);
217 t
= now(clock_boottime_or_monotonic());
222 /* Depending whether this is an mDNS shared entry
223 * either remove only this one RR or the whole RRset */
224 log_debug("Removing %scache entry for %s (expired "USEC_FMT
"s ago)",
225 i
->shared_owner
? "shared " : "",
226 dns_resource_key_to_string(i
->key
, key_str
, sizeof key_str
),
227 (t
- i
->until
) / USEC_PER_SEC
);
230 dns_cache_item_unlink_and_free(c
, i
);
232 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*key
= NULL
;
234 /* Take an extra reference to the key so that it
235 * doesn't go away in the middle of the remove call */
236 key
= dns_resource_key_ref(i
->key
);
237 dns_cache_remove_by_key(c
, key
);
242 static int dns_cache_item_prioq_compare_func(const void *a
, const void *b
) {
243 const DnsCacheItem
*x
= a
, *y
= b
;
245 return CMP(x
->until
, y
->until
);
248 static int dns_cache_init(DnsCache
*c
) {
253 r
= prioq_ensure_allocated(&c
->by_expiry
, dns_cache_item_prioq_compare_func
);
257 r
= hashmap_ensure_allocated(&c
->by_key
, &dns_resource_key_hash_ops
);
264 static int dns_cache_link_item(DnsCache
*c
, DnsCacheItem
*i
) {
271 r
= prioq_put(c
->by_expiry
, i
, &i
->prioq_idx
);
275 first
= hashmap_get(c
->by_key
, i
->key
);
277 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*k
= NULL
;
279 /* Keep a reference to the original key, while we manipulate the list. */
280 k
= dns_resource_key_ref(first
->key
);
282 /* Now, try to reduce the number of keys we keep */
283 dns_resource_key_reduce(&first
->key
, &i
->key
);
286 dns_resource_key_reduce(&first
->rr
->key
, &i
->key
);
288 dns_resource_key_reduce(&i
->rr
->key
, &i
->key
);
290 LIST_PREPEND(by_key
, first
, i
);
291 assert_se(hashmap_replace(c
->by_key
, first
->key
, first
) >= 0);
293 r
= hashmap_put(c
->by_key
, i
->key
, i
);
295 prioq_remove(c
->by_expiry
, i
, &i
->prioq_idx
);
303 static DnsCacheItem
* dns_cache_get(DnsCache
*c
, DnsResourceRecord
*rr
) {
309 LIST_FOREACH(by_key
, i
, hashmap_get(c
->by_key
, rr
->key
))
310 if (i
->rr
&& dns_resource_record_equal(i
->rr
, rr
) > 0)
316 static usec_t
calculate_until(
317 DnsResourceRecord
*rr
,
321 bool use_soa_minimum
) {
328 ttl
= MIN(min_ttl
, nsec_ttl
);
329 if (rr
->key
->type
== DNS_TYPE_SOA
&& use_soa_minimum
) {
330 /* If this is a SOA RR, and it is requested, clamp to the SOA's minimum field. This is used
331 * when we do negative caching, to determine the TTL for the negative caching entry. See RFC
332 * 2308, Section 5. */
334 if (ttl
> rr
->soa
.minimum
)
335 ttl
= rr
->soa
.minimum
;
338 u
= ttl
* USEC_PER_SEC
;
339 if (u
> CACHE_TTL_MAX_USEC
)
340 u
= CACHE_TTL_MAX_USEC
;
342 if (rr
->expiry
!= USEC_INFINITY
) {
345 /* Make use of the DNSSEC RRSIG expiry info, if we have it */
347 left
= LESS_BY(rr
->expiry
, now(CLOCK_REALTIME
));
352 return timestamp
+ u
;
355 static void dns_cache_item_update_positive(
358 DnsResourceRecord
*rr
,
360 DnsPacket
*full_packet
,
362 uint64_t query_flags
,
364 DnssecResult dnssec_result
,
368 const union in_addr_union
*owner_address
) {
373 assert(owner_address
);
375 i
->type
= DNS_CACHE_POSITIVE
;
378 /* We are the first item in the list, we need to
379 * update the key used in the hashmap */
381 assert_se(hashmap_replace(c
->by_key
, rr
->key
, i
) >= 0);
383 dns_resource_record_ref(rr
);
384 dns_resource_record_unref(i
->rr
);
387 dns_resource_key_unref(i
->key
);
388 i
->key
= dns_resource_key_ref(rr
->key
);
390 dns_answer_ref(answer
);
391 dns_answer_unref(i
->answer
);
394 dns_packet_ref(full_packet
);
395 dns_packet_unref(i
->full_packet
);
396 i
->full_packet
= full_packet
;
398 i
->until
= calculate_until(rr
, min_ttl
, UINT32_MAX
, timestamp
, false);
399 i
->query_flags
= query_flags
& CACHEABLE_QUERY_FLAGS
;
400 i
->shared_owner
= shared_owner
;
401 i
->dnssec_result
= dnssec_result
;
403 i
->ifindex
= ifindex
;
405 i
->owner_family
= owner_family
;
406 i
->owner_address
= *owner_address
;
408 prioq_reshuffle(c
->by_expiry
, i
, &i
->prioq_idx
);
411 static int dns_cache_put_positive(
413 DnsResourceRecord
*rr
,
415 DnsPacket
*full_packet
,
416 uint64_t query_flags
,
418 DnssecResult dnssec_result
,
422 const union in_addr_union
*owner_address
) {
424 _cleanup_(dns_cache_item_freep
) DnsCacheItem
*i
= NULL
;
425 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
426 DnsCacheItem
*existing
;
432 assert(owner_address
);
434 /* Never cache pseudo RRs */
435 if (dns_class_is_pseudo(rr
->key
->class))
437 if (dns_type_is_pseudo(rr
->key
->type
))
440 /* Determine the minimal TTL of all RRs in the answer plus the one by the main RR we are supposed to
441 * cache. Since we cache whole answers to questions we should never return answers where only some
442 * RRs are still valid, hence find the lowest here */
443 min_ttl
= MIN(dns_answer_min_ttl(answer
), rr
->ttl
);
445 /* New TTL is 0? Delete this specific entry... */
447 r
= dns_cache_remove_by_rr(c
, rr
);
449 r
> 0 ? "Removed zero TTL entry from cache" : "Not caching zero TTL cache entry",
450 dns_resource_key_to_string(rr
->key
, key_str
, sizeof key_str
));
454 /* Entry exists already? Update TTL, timestamp and owner */
455 existing
= dns_cache_get(c
, rr
);
457 dns_cache_item_update_positive(
474 /* Otherwise, add the new RR */
475 r
= dns_cache_init(c
);
479 dns_cache_make_space(c
, 1);
481 i
= new(DnsCacheItem
, 1);
485 *i
= (DnsCacheItem
) {
486 .type
= DNS_CACHE_POSITIVE
,
487 .key
= dns_resource_key_ref(rr
->key
),
488 .rr
= dns_resource_record_ref(rr
),
489 .answer
= dns_answer_ref(answer
),
490 .full_packet
= dns_packet_ref(full_packet
),
491 .until
= calculate_until(rr
, min_ttl
, UINT32_MAX
, timestamp
, false),
492 .query_flags
= query_flags
& CACHEABLE_QUERY_FLAGS
,
493 .shared_owner
= shared_owner
,
494 .dnssec_result
= dnssec_result
,
496 .owner_family
= owner_family
,
497 .owner_address
= *owner_address
,
498 .prioq_idx
= PRIOQ_IDX_NULL
,
501 r
= dns_cache_link_item(c
, i
);
506 _cleanup_free_
char *t
= NULL
;
507 char ifname
[IF_NAMESIZE
+ 1];
509 (void) in_addr_to_string(i
->owner_family
, &i
->owner_address
, &t
);
511 log_debug("Added positive %s %s%s cache entry for %s "USEC_FMT
"s on %s/%s/%s",
512 FLAGS_SET(i
->query_flags
, SD_RESOLVED_AUTHENTICATED
) ? "authenticated" : "unauthenticated",
513 FLAGS_SET(i
->query_flags
, SD_RESOLVED_CONFIDENTIAL
) ? "confidential" : "non-confidential",
514 i
->shared_owner
? " shared" : "",
515 dns_resource_key_to_string(i
->key
, key_str
, sizeof key_str
),
516 (i
->until
- timestamp
) / USEC_PER_SEC
,
517 i
->ifindex
== 0 ? "*" : strna(format_ifname(i
->ifindex
, ifname
)),
518 af_to_name_short(i
->owner_family
),
526 static int dns_cache_put_negative(
531 DnsPacket
*full_packet
,
532 uint64_t query_flags
,
533 DnssecResult dnssec_result
,
536 DnsResourceRecord
*soa
,
538 const union in_addr_union
*owner_address
) {
540 _cleanup_(dns_cache_item_freep
) DnsCacheItem
*i
= NULL
;
541 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
546 assert(owner_address
);
548 /* Never cache pseudo RR keys. DNS_TYPE_ANY is particularly
549 * important to filter out as we use this as a pseudo-type for
550 * NXDOMAIN entries */
551 if (dns_class_is_pseudo(key
->class))
553 if (dns_type_is_pseudo(key
->type
))
556 if (IN_SET(rcode
, DNS_RCODE_SUCCESS
, DNS_RCODE_NXDOMAIN
)) {
560 /* For negative replies, check if we have a TTL of a SOA */
561 if (nsec_ttl
<= 0 || soa
->soa
.minimum
<= 0 || soa
->ttl
<= 0) {
562 log_debug("Not caching negative entry with zero SOA/NSEC/NSEC3 TTL: %s",
563 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
566 } else if (rcode
!= DNS_RCODE_SERVFAIL
)
569 r
= dns_cache_init(c
);
573 dns_cache_make_space(c
, 1);
575 i
= new(DnsCacheItem
, 1);
579 *i
= (DnsCacheItem
) {
581 rcode
== DNS_RCODE_SUCCESS
? DNS_CACHE_NODATA
:
582 rcode
== DNS_RCODE_NXDOMAIN
? DNS_CACHE_NXDOMAIN
: DNS_CACHE_RCODE
,
583 .query_flags
= query_flags
& CACHEABLE_QUERY_FLAGS
,
584 .dnssec_result
= dnssec_result
,
585 .owner_family
= owner_family
,
586 .owner_address
= *owner_address
,
587 .prioq_idx
= PRIOQ_IDX_NULL
,
589 .answer
= dns_answer_ref(answer
),
590 .full_packet
= dns_packet_ref(full_packet
),
593 /* Determine how long to cache this entry. In case we have some RRs in the answer use the lowest TTL
594 * of any of them. Typically that's the SOA's TTL, which is OK, but could possibly be lower because
595 * of some other RR. Let's better take the lowest option here than a needlessly high one */
597 i
->type
== DNS_CACHE_RCODE
? timestamp
+ CACHE_TTL_STRANGE_RCODE_USEC
:
598 calculate_until(soa
, dns_answer_min_ttl(answer
), nsec_ttl
, timestamp
, true);
600 if (i
->type
== DNS_CACHE_NXDOMAIN
) {
601 /* NXDOMAIN entries should apply equally to all types, so we use ANY as
602 * a pseudo type for this purpose here. */
603 i
->key
= dns_resource_key_new(key
->class, DNS_TYPE_ANY
, dns_resource_key_name(key
));
607 /* Make sure to remove any previous entry for this
608 * specific ANY key. (For non-ANY keys the cache data
609 * is already cleared by the caller.) Note that we
610 * don't bother removing positive or NODATA cache
611 * items in this case, because it would either be slow
612 * or require explicit indexing by name */
613 dns_cache_remove_by_key(c
, key
);
615 i
->key
= dns_resource_key_ref(key
);
617 r
= dns_cache_link_item(c
, i
);
621 log_debug("Added %s cache entry for %s "USEC_FMT
"s",
622 dns_cache_item_type_to_string(i
),
623 dns_resource_key_to_string(i
->key
, key_str
, sizeof key_str
),
624 (i
->until
- timestamp
) / USEC_PER_SEC
);
630 static void dns_cache_remove_previous(
635 DnsResourceRecord
*rr
;
636 DnsAnswerFlags flags
;
640 /* First, if we were passed a key (i.e. on LLMNR/DNS, but
641 * not on mDNS), delete all matching old RRs, so that we only
642 * keep complete by_key in place. */
644 dns_cache_remove_by_key(c
, key
);
646 /* Second, flush all entries matching the answer, unless this
647 * is an RR that is explicitly marked to be "shared" between
648 * peers (i.e. mDNS RRs without the flush-cache bit set). */
649 DNS_ANSWER_FOREACH_FLAGS(rr
, flags
, answer
) {
650 if ((flags
& DNS_ANSWER_CACHEABLE
) == 0)
653 if (flags
& DNS_ANSWER_SHARED_OWNER
)
656 dns_cache_remove_by_key(c
, rr
->key
);
660 static bool rr_eligible(DnsResourceRecord
*rr
) {
663 /* When we see an NSEC/NSEC3 RR, we'll only cache it if it is from the lower zone, not the upper zone, since
664 * that's where the interesting bits are (with exception of DS RRs). Of course, this way we cannot derive DS
665 * existence from any cached NSEC/NSEC3, but that should be fine. */
667 switch (rr
->key
->type
) {
670 return !bitmap_isset(rr
->nsec
.types
, DNS_TYPE_NS
) ||
671 bitmap_isset(rr
->nsec
.types
, DNS_TYPE_SOA
);
674 return !bitmap_isset(rr
->nsec3
.types
, DNS_TYPE_NS
) ||
675 bitmap_isset(rr
->nsec3
.types
, DNS_TYPE_SOA
);
684 DnsCacheMode cache_mode
,
688 DnsPacket
*full_packet
,
689 uint64_t query_flags
,
690 DnssecResult dnssec_result
,
693 const union in_addr_union
*owner_address
) {
695 DnsResourceRecord
*soa
= NULL
;
696 bool weird_rcode
= false;
698 DnsAnswerFlags flags
;
704 assert(owner_address
);
706 dns_cache_remove_previous(c
, key
, answer
);
708 /* We only care for positive replies and NXDOMAINs, on all other replies we will simply flush the respective
709 * entries, and that's it. (Well, with one further exception: since some DNS zones (akamai!) return SERVFAIL
710 * consistently for some lookups, and forwarders tend to propagate that we'll cache that too, but only for a
713 if (IN_SET(rcode
, DNS_RCODE_SUCCESS
, DNS_RCODE_NXDOMAIN
)) {
714 if (dns_answer_isempty(answer
)) {
716 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
718 log_debug("Not caching negative entry without a SOA record: %s",
719 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
726 /* Only cache SERVFAIL as "weird" rcode for now. We can add more later, should that turn out to be
728 if (rcode
!= DNS_RCODE_SERVFAIL
)
734 cache_keys
= dns_answer_size(answer
);
738 /* Make some space for our new entries */
739 dns_cache_make_space(c
, cache_keys
);
741 timestamp
= now(clock_boottime_or_monotonic());
743 /* Second, add in positive entries for all contained RRs */
744 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
747 if (!FLAGS_SET(item
->flags
, DNS_ANSWER_CACHEABLE
) ||
748 !rr_eligible(item
->rr
))
752 /* We store the auxiliary RRs and packet data in the cache only if they were in
753 * direct response to the original query. If we cache an RR we also received, and
754 * that is just auxiliary information we can't use the data, hence don't. */
756 primary
= dns_resource_key_match_rr(key
, item
->rr
, NULL
);
760 primary
= dns_resource_key_match_cname_or_dname(key
, item
->rr
->key
, NULL
);
769 /* Do not replace existing cache items for primary lookups with non-primary
770 * data. After all the primary lookup data is a lot more useful. */
771 first
= hashmap_get(c
->by_key
, item
->rr
->key
);
772 if (first
&& DNS_CACHE_ITEM_IS_PRIMARY(first
))
776 r
= dns_cache_put_positive(
779 primary
? answer
: NULL
,
780 primary
? full_packet
: NULL
,
781 ((item
->flags
& DNS_ANSWER_AUTHENTICATED
) ? SD_RESOLVED_AUTHENTICATED
: 0) |
782 (query_flags
& SD_RESOLVED_CONFIDENTIAL
),
783 item
->flags
& DNS_ANSWER_SHARED_OWNER
,
793 if (!key
) /* mDNS doesn't know negative caching, really */
796 /* Third, add in negative entries if the key has no RR */
797 r
= dns_answer_match_key(answer
, key
, NULL
);
803 /* But not if it has a matching CNAME/DNAME (the negative caching will be done on the canonical name,
804 * not on the alias) */
805 r
= dns_answer_find_cname_or_dname(answer
, key
, NULL
, NULL
);
811 /* See https://tools.ietf.org/html/rfc2308, which say that a matching SOA record in the packet is used to
812 * enable negative caching. We apply one exception though: if we are about to cache a weird rcode we do so
813 * regardless of a SOA. */
814 r
= dns_answer_find_soa(answer
, key
, &soa
, &flags
);
817 if (r
== 0 && !weird_rcode
)
820 /* Refuse using the SOA data if it is unsigned, but the key is signed */
821 if (FLAGS_SET(query_flags
, SD_RESOLVED_AUTHENTICATED
) &&
822 (flags
& DNS_ANSWER_AUTHENTICATED
) == 0)
826 if (cache_mode
== DNS_CACHE_MODE_NO_NEGATIVE
) {
827 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
828 log_debug("Not caching negative entry for: %s, cache mode set to no-negative",
829 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
833 r
= dns_cache_put_negative(
844 owner_family
, owner_address
);
851 /* Adding all RRs failed. Let's clean up what we already
852 * added, just in case */
855 dns_cache_remove_by_key(c
, key
);
857 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
858 if ((item
->flags
& DNS_ANSWER_CACHEABLE
) == 0)
861 dns_cache_remove_by_key(c
, item
->rr
->key
);
867 static DnsCacheItem
*dns_cache_get_by_key_follow_cname_dname_nsec(DnsCache
*c
, DnsResourceKey
*k
) {
875 /* If we hit some OOM error, or suchlike, we don't care too
876 * much, after all this is just a cache */
878 i
= hashmap_get(c
->by_key
, k
);
882 n
= dns_resource_key_name(k
);
884 /* Check if we have an NXDOMAIN cache item for the name, notice that we use
885 * the pseudo-type ANY for NXDOMAIN cache items. */
886 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_ANY
, n
));
887 if (i
&& i
->type
== DNS_CACHE_NXDOMAIN
)
890 if (dns_type_may_redirect(k
->type
)) {
891 /* Check if we have a CNAME record instead */
892 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_CNAME
, n
));
893 if (i
&& i
->type
!= DNS_CACHE_NODATA
)
896 /* OK, let's look for cached DNAME records. */
901 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_DNAME
, n
));
902 if (i
&& i
->type
!= DNS_CACHE_NODATA
)
905 /* Jump one label ahead */
906 r
= dns_name_parent(&n
);
912 if (k
->type
!= DNS_TYPE_NSEC
) {
913 /* Check if we have an NSEC record instead for the name. */
914 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_NSEC
, n
));
922 static int answer_add_clamp_ttl(
924 DnsResourceRecord
*rr
,
926 DnsAnswerFlags answer_flags
,
927 DnsResourceRecord
*rrsig
,
928 uint64_t query_flags
,
932 _cleanup_(dns_resource_record_unrefp
) DnsResourceRecord
*patched
= NULL
, *patched_rrsig
= NULL
;
938 if (FLAGS_SET(query_flags
, SD_RESOLVED_CLAMP_TTL
)) {
941 /* Let's determine how much time is left for this cache entry. Note that we round down, but
942 * clamp this to be 1s at minimum, since we usually want records to remain cached better too
943 * short a time than too long a time, but otoh don't want to return 0 ever, since that has
944 * special semantics in various contexts — in particular in mDNS */
946 left_ttl
= MAX(1U, LESS_BY(until
, current
) / USEC_PER_SEC
);
948 patched
= dns_resource_record_ref(rr
);
950 r
= dns_resource_record_clamp_ttl(&patched
, left_ttl
);
957 patched_rrsig
= dns_resource_record_ref(rrsig
);
958 r
= dns_resource_record_clamp_ttl(&patched_rrsig
, left_ttl
);
962 rrsig
= patched_rrsig
;
966 r
= dns_answer_add_extend(answer
, rr
, ifindex
, answer_flags
, rrsig
);
973 int dns_cache_lookup(
976 uint64_t query_flags
,
978 DnsAnswer
**ret_answer
,
979 DnsPacket
**ret_full_packet
,
980 uint64_t *ret_query_flags
,
981 DnssecResult
*ret_dnssec_result
) {
983 _cleanup_(dns_packet_unrefp
) DnsPacket
*full_packet
= NULL
;
984 _cleanup_(dns_answer_unrefp
) DnsAnswer
*answer
= NULL
;
985 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
988 bool nxdomain
= false;
989 DnsCacheItem
*j
, *first
, *nsec
= NULL
;
990 bool have_authenticated
= false, have_non_authenticated
= false, have_confidential
= false, have_non_confidential
= false;
992 int found_rcode
= -1;
993 DnssecResult dnssec_result
= -1;
994 int have_dnssec_result
= -1;
999 if (key
->type
== DNS_TYPE_ANY
|| key
->class == DNS_CLASS_ANY
) {
1000 /* If we have ANY lookups we don't use the cache, so that the caller refreshes via the
1003 log_debug("Ignoring cache for ANY lookup: %s",
1004 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1008 first
= dns_cache_get_by_key_follow_cname_dname_nsec(c
, key
);
1010 /* If one question cannot be answered we need to refresh */
1012 log_debug("Cache miss for %s",
1013 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1017 if (FLAGS_SET(query_flags
, SD_RESOLVED_CLAMP_TTL
))
1018 current
= now(clock_boottime_or_monotonic());
1020 LIST_FOREACH(by_key
, j
, first
) {
1021 /* If the caller doesn't allow us to answer questions from cache data learned from
1022 * "side-effect", skip this entry. */
1023 if (FLAGS_SET(query_flags
, SD_RESOLVED_REQUIRE_PRIMARY
) &&
1024 !DNS_CACHE_ITEM_IS_PRIMARY(j
)) {
1025 log_debug("Primary answer was requested for cache lookup for %s, which we don't have.",
1026 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1031 if (j
->type
== DNS_CACHE_NXDOMAIN
)
1033 else if (j
->type
== DNS_CACHE_RCODE
)
1034 found_rcode
= j
->rcode
;
1036 if (j
->rr
->key
->type
== DNS_TYPE_NSEC
)
1042 if (FLAGS_SET(j
->query_flags
, SD_RESOLVED_AUTHENTICATED
))
1043 have_authenticated
= true;
1045 have_non_authenticated
= true;
1047 if (FLAGS_SET(j
->query_flags
, SD_RESOLVED_CONFIDENTIAL
))
1048 have_confidential
= true;
1050 have_non_confidential
= true;
1052 if (j
->dnssec_result
< 0) {
1053 have_dnssec_result
= false; /* an entry without dnssec result? then invalidate things for good */
1054 dnssec_result
= _DNSSEC_RESULT_INVALID
;
1055 } else if (have_dnssec_result
< 0) {
1056 have_dnssec_result
= true; /* So far no result seen, let's pick this one up */
1057 dnssec_result
= j
->dnssec_result
;
1058 } else if (have_dnssec_result
> 0 && j
->dnssec_result
!= dnssec_result
) {
1059 have_dnssec_result
= false; /* conflicting result seen? then invalidate for good */
1060 dnssec_result
= _DNSSEC_RESULT_INVALID
;
1063 /* Append the answer RRs to our answer. Ideally we have the answer object, which we
1064 * preferably use. But if the cached entry was generated as "side-effect" of a reply,
1065 * i.e. from validated auxiliary records rather than from the main reply, then we use the
1066 * individual RRs only instead. */
1069 /* Minor optimization, if the full answer object of this and the previous RR is the
1070 * same, don't bother adding it again. Typically we store a full RRset here, hence
1071 * that should be the case. */
1072 if (!j
->by_key_prev
|| j
->answer
!= j
->by_key_prev
->answer
) {
1073 DnsAnswerItem
*item
;
1075 DNS_ANSWER_FOREACH_ITEM(item
, j
->answer
) {
1076 r
= answer_add_clamp_ttl(
1091 r
= answer_add_clamp_ttl(
1095 FLAGS_SET(j
->query_flags
, SD_RESOLVED_AUTHENTICATED
) ? DNS_ANSWER_AUTHENTICATED
: 0,
1104 /* We'll return any packet we have for this. Typically all cache entries for the same key
1105 * should come from the same packet anyway, hence it doesn't really matter which packet we
1106 * return here, they should all resolve to the same anyway. */
1107 if (!full_packet
&& j
->full_packet
)
1108 full_packet
= dns_packet_ref(j
->full_packet
);
1111 if (found_rcode
>= 0) {
1112 log_debug("RCODE %s cache hit for %s",
1113 dns_rcode_to_string(found_rcode
),
1114 dns_resource_key_to_string(key
, key_str
, sizeof(key_str
)));
1117 *ret_rcode
= found_rcode
;
1119 *ret_answer
= TAKE_PTR(answer
);
1120 if (ret_full_packet
)
1121 *ret_full_packet
= TAKE_PTR(full_packet
);
1122 if (ret_query_flags
)
1123 *ret_query_flags
= 0;
1124 if (ret_dnssec_result
)
1125 *ret_dnssec_result
= dnssec_result
;
1131 if (nsec
&& !IN_SET(key
->type
, DNS_TYPE_NSEC
, DNS_TYPE_DS
)) {
1132 /* Note that we won't derive information for DS RRs from an NSEC, because we only cache NSEC
1133 * RRs from the lower-zone of a zone cut, but the DS RRs are on the upper zone. */
1135 log_debug("NSEC NODATA cache hit for %s",
1136 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1138 /* We only found an NSEC record that matches our name. If it says the type doesn't exist
1139 * report NODATA. Otherwise report a cache miss. */
1142 *ret_rcode
= DNS_RCODE_SUCCESS
;
1144 *ret_answer
= TAKE_PTR(answer
);
1145 if (ret_full_packet
)
1146 *ret_full_packet
= TAKE_PTR(full_packet
);
1147 if (ret_query_flags
)
1148 *ret_query_flags
= nsec
->query_flags
;
1149 if (ret_dnssec_result
)
1150 *ret_dnssec_result
= nsec
->dnssec_result
;
1152 if (!bitmap_isset(nsec
->rr
->nsec
.types
, key
->type
) &&
1153 !bitmap_isset(nsec
->rr
->nsec
.types
, DNS_TYPE_CNAME
) &&
1154 !bitmap_isset(nsec
->rr
->nsec
.types
, DNS_TYPE_DNAME
)) {
1163 log_debug("%s cache hit for %s",
1164 n
> 0 ? "Positive" :
1165 nxdomain
? "NXDOMAIN" : "NODATA",
1166 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1172 *ret_rcode
= nxdomain
? DNS_RCODE_NXDOMAIN
: DNS_RCODE_SUCCESS
;
1174 *ret_answer
= TAKE_PTR(answer
);
1175 if (ret_full_packet
)
1176 *ret_full_packet
= TAKE_PTR(full_packet
);
1177 if (ret_query_flags
)
1179 ((have_authenticated
&& !have_non_authenticated
) ? SD_RESOLVED_AUTHENTICATED
: 0) |
1180 ((have_confidential
&& !have_non_confidential
) ? SD_RESOLVED_CONFIDENTIAL
: 0);
1181 if (ret_dnssec_result
)
1182 *ret_dnssec_result
= dnssec_result
;
1190 *ret_rcode
= DNS_RCODE_SUCCESS
;
1192 *ret_answer
= TAKE_PTR(answer
);
1193 if (ret_full_packet
)
1194 *ret_full_packet
= TAKE_PTR(full_packet
);
1195 if (ret_query_flags
)
1197 ((have_authenticated
&& !have_non_authenticated
) ? SD_RESOLVED_AUTHENTICATED
: 0) |
1198 ((have_confidential
&& !have_non_confidential
) ? SD_RESOLVED_CONFIDENTIAL
: 0);
1199 if (ret_dnssec_result
)
1200 *ret_dnssec_result
= dnssec_result
;
1206 *ret_rcode
= DNS_RCODE_SUCCESS
;
1209 if (ret_full_packet
)
1210 *ret_full_packet
= NULL
;
1211 if (ret_query_flags
)
1212 *ret_query_flags
= 0;
1213 if (ret_dnssec_result
)
1214 *ret_dnssec_result
= _DNSSEC_RESULT_INVALID
;
1220 int dns_cache_check_conflicts(DnsCache
*cache
, DnsResourceRecord
*rr
, int owner_family
, const union in_addr_union
*owner_address
) {
1221 DnsCacheItem
*i
, *first
;
1222 bool same_owner
= true;
1227 dns_cache_prune(cache
);
1229 /* See if there's a cache entry for the same key. If there
1230 * isn't there's no conflict */
1231 first
= hashmap_get(cache
->by_key
, rr
->key
);
1235 /* See if the RR key is owned by the same owner, if so, there
1236 * isn't a conflict either */
1237 LIST_FOREACH(by_key
, i
, first
) {
1238 if (i
->owner_family
!= owner_family
||
1239 !in_addr_equal(owner_family
, &i
->owner_address
, owner_address
)) {
1247 /* See if there's the exact same RR in the cache. If yes, then
1248 * there's no conflict. */
1249 if (dns_cache_get(cache
, rr
))
1252 /* There's a conflict */
1256 int dns_cache_export_shared_to_packet(DnsCache
*cache
, DnsPacket
*p
) {
1257 unsigned ancount
= 0;
1264 HASHMAP_FOREACH(i
, cache
->by_key
) {
1267 LIST_FOREACH(by_key
, j
, i
) {
1271 if (!j
->shared_owner
)
1274 r
= dns_packet_append_rr(p
, j
->rr
, 0, NULL
, NULL
);
1275 if (r
== -EMSGSIZE
&& p
->protocol
== DNS_PROTOCOL_MDNS
) {
1276 /* For mDNS, if we're unable to stuff all known answers into the given packet,
1277 * allocate a new one, push the RR into that one and link it to the current one.
1280 DNS_PACKET_HEADER(p
)->ancount
= htobe16(ancount
);
1283 r
= dns_packet_new_query(&p
->more
, p
->protocol
, 0, true);
1287 /* continue with new packet */
1289 r
= dns_packet_append_rr(p
, j
->rr
, 0, NULL
, NULL
);
1299 DNS_PACKET_HEADER(p
)->ancount
= htobe16(ancount
);
1304 void dns_cache_dump(DnsCache
*cache
, FILE *f
) {
1313 HASHMAP_FOREACH(i
, cache
->by_key
) {
1316 LIST_FOREACH(by_key
, j
, i
) {
1322 t
= dns_resource_record_to_string(j
->rr
);
1331 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
1333 fputs(dns_resource_key_to_string(j
->key
, key_str
, sizeof key_str
), f
);
1335 fputs(dns_cache_item_type_to_string(j
), f
);
1342 bool dns_cache_is_empty(DnsCache
*cache
) {
1346 return hashmap_isempty(cache
->by_key
);
1349 unsigned dns_cache_size(DnsCache
*cache
) {
1353 return hashmap_size(cache
->by_key
);