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 unless StaleRetentionSec is greater than zero. */
19 #define CACHE_TTL_MAX_USEC (2 * USEC_PER_HOUR)
21 /* The max TTL for stale data is set to 30 seconds. See RFC 8767, Section 6. */
22 #define CACHE_STALE_TTL_MAX_USEC (30 * USEC_PER_SEC)
24 /* How long to cache strange rcodes, i.e. rcodes != SUCCESS and != NXDOMAIN (specifically: that's only SERVFAIL for
26 #define CACHE_TTL_STRANGE_RCODE_USEC (10 * USEC_PER_SEC)
28 #define CACHEABLE_QUERY_FLAGS (SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL)
30 typedef enum DnsCacheItemType DnsCacheItemType
;
31 typedef struct DnsCacheItem DnsCacheItem
;
33 enum DnsCacheItemType
{
37 DNS_CACHE_RCODE
, /* "strange" RCODE (effective only SERVFAIL for now) */
41 DnsCacheItemType type
;
43 DnsResourceKey
*key
; /* The key for this item, i.e. the lookup key */
44 DnsResourceRecord
*rr
; /* The RR for this item, i.e. the lookup value for positive queries */
45 DnsAnswer
*answer
; /* The full validated answer, if this is an RRset acquired via a "primary" lookup */
46 DnsPacket
*full_packet
; /* The full packet this information was acquired with */
48 usec_t until
; /* If StaleRetentionSec is greater than zero, until is set to a duration of StaleRetentionSec from the time of TTL expiry. If StaleRetentionSec is zero, both until and until_valid will be set to ttl. */
49 usec_t until_valid
; /* The key is for storing the time when the TTL set to expire. */
50 uint64_t query_flags
; /* SD_RESOLVED_AUTHENTICATED and/or SD_RESOLVED_CONFIDENTIAL */
51 DnssecResult dnssec_result
;
55 union in_addr_union owner_address
;
58 LIST_FIELDS(DnsCacheItem
, by_key
);
63 /* Returns true if this is a cache item created as result of an explicit lookup, or created as "side-effect"
64 * of another request. "Primary" entries will carry the full answer data (with NSEC, …) that can aso prove
65 * wildcard expansion, non-existence and such, while entries that were created as "side-effect" just contain
66 * immediate RR data for the specified RR key, but nothing else. */
67 #define DNS_CACHE_ITEM_IS_PRIMARY(item) (!!(item)->answer)
69 static const char *dns_cache_item_type_to_string(DnsCacheItem
*item
) {
74 case DNS_CACHE_POSITIVE
:
77 case DNS_CACHE_NODATA
:
80 case DNS_CACHE_NXDOMAIN
:
84 return dns_rcode_to_string(item
->rcode
);
90 static DnsCacheItem
* dns_cache_item_free(DnsCacheItem
*i
) {
94 dns_resource_record_unref(i
->rr
);
95 dns_resource_key_unref(i
->key
);
96 dns_answer_unref(i
->answer
);
97 dns_packet_unref(i
->full_packet
);
100 DEFINE_TRIVIAL_CLEANUP_FUNC(DnsCacheItem
*, dns_cache_item_free
);
102 static void dns_cache_item_unlink_and_free(DnsCache
*c
, DnsCacheItem
*i
) {
110 first
= hashmap_get(c
->by_key
, i
->key
);
111 LIST_REMOVE(by_key
, first
, i
);
114 assert_se(hashmap_replace(c
->by_key
, first
->key
, first
) >= 0);
116 hashmap_remove(c
->by_key
, i
->key
);
118 prioq_remove(c
->by_expiry
, i
, &i
->prioq_idx
);
120 dns_cache_item_free(i
);
123 static bool dns_cache_remove_by_rr(DnsCache
*c
, DnsResourceRecord
*rr
) {
127 first
= hashmap_get(c
->by_key
, rr
->key
);
128 LIST_FOREACH(by_key
, i
, first
) {
129 r
= dns_resource_record_equal(i
->rr
, rr
);
133 dns_cache_item_unlink_and_free(c
, i
);
141 static bool dns_cache_remove_by_key(DnsCache
*c
, DnsResourceKey
*key
) {
147 first
= hashmap_remove(c
->by_key
, key
);
151 LIST_FOREACH(by_key
, i
, first
) {
152 prioq_remove(c
->by_expiry
, i
, &i
->prioq_idx
);
153 dns_cache_item_free(i
);
159 void dns_cache_flush(DnsCache
*c
) {
164 while ((key
= hashmap_first_key(c
->by_key
)))
165 dns_cache_remove_by_key(c
, key
);
167 assert(hashmap_size(c
->by_key
) == 0);
168 assert(prioq_size(c
->by_expiry
) == 0);
170 c
->by_key
= hashmap_free(c
->by_key
);
171 c
->by_expiry
= prioq_free(c
->by_expiry
);
174 static void dns_cache_make_space(DnsCache
*c
, unsigned add
) {
180 /* Makes space for n new entries. Note that we actually allow
181 * the cache to grow beyond CACHE_MAX, but only when we shall
182 * add more RRs to the cache than CACHE_MAX at once. In that
183 * case the cache will be emptied completely otherwise. */
186 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*key
= NULL
;
189 if (prioq_size(c
->by_expiry
) <= 0)
192 if (prioq_size(c
->by_expiry
) + add
< CACHE_MAX
)
195 i
= prioq_peek(c
->by_expiry
);
198 /* Take an extra reference to the key so that it
199 * doesn't go away in the middle of the remove call */
200 key
= dns_resource_key_ref(i
->key
);
201 dns_cache_remove_by_key(c
, key
);
205 void dns_cache_prune(DnsCache
*c
) {
210 /* Remove all entries that are past their TTL */
214 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
216 i
= prioq_peek(c
->by_expiry
);
221 t
= now(CLOCK_BOOTTIME
);
226 /* Depending whether this is an mDNS shared entry
227 * either remove only this one RR or the whole RRset */
228 log_debug("Removing %scache entry for %s (expired "USEC_FMT
"s ago)",
229 i
->shared_owner
? "shared " : "",
230 dns_resource_key_to_string(i
->key
, key_str
, sizeof key_str
),
231 (t
- i
->until
) / USEC_PER_SEC
);
234 dns_cache_item_unlink_and_free(c
, i
);
236 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*key
= NULL
;
238 /* Take an extra reference to the key so that it
239 * doesn't go away in the middle of the remove call */
240 key
= dns_resource_key_ref(i
->key
);
241 dns_cache_remove_by_key(c
, key
);
246 static int dns_cache_item_prioq_compare_func(const void *a
, const void *b
) {
247 const DnsCacheItem
*x
= a
, *y
= b
;
249 return CMP(x
->until
, y
->until
);
252 static int dns_cache_init(DnsCache
*c
) {
257 r
= prioq_ensure_allocated(&c
->by_expiry
, dns_cache_item_prioq_compare_func
);
261 r
= hashmap_ensure_allocated(&c
->by_key
, &dns_resource_key_hash_ops
);
268 static int dns_cache_link_item(DnsCache
*c
, DnsCacheItem
*i
) {
275 r
= prioq_put(c
->by_expiry
, i
, &i
->prioq_idx
);
279 first
= hashmap_get(c
->by_key
, i
->key
);
281 _unused_
_cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*k
= NULL
;
283 /* Keep a reference to the original key, while we manipulate the list. */
284 k
= dns_resource_key_ref(first
->key
);
286 /* Now, try to reduce the number of keys we keep */
287 dns_resource_key_reduce(&first
->key
, &i
->key
);
290 dns_resource_key_reduce(&first
->rr
->key
, &i
->key
);
292 dns_resource_key_reduce(&i
->rr
->key
, &i
->key
);
294 LIST_PREPEND(by_key
, first
, i
);
295 assert_se(hashmap_replace(c
->by_key
, first
->key
, first
) >= 0);
297 r
= hashmap_put(c
->by_key
, i
->key
, i
);
299 prioq_remove(c
->by_expiry
, i
, &i
->prioq_idx
);
307 static DnsCacheItem
* dns_cache_get(DnsCache
*c
, DnsResourceRecord
*rr
) {
311 LIST_FOREACH(by_key
, i
, (DnsCacheItem
*) hashmap_get(c
->by_key
, rr
->key
))
312 if (i
->rr
&& dns_resource_record_equal(i
->rr
, rr
) > 0)
318 static usec_t
calculate_until_valid(
319 DnsResourceRecord
*rr
,
323 bool use_soa_minimum
) {
330 ttl
= MIN(min_ttl
, nsec_ttl
);
331 if (rr
->key
->type
== DNS_TYPE_SOA
&& use_soa_minimum
) {
332 /* If this is a SOA RR, and it is requested, clamp to the SOA's minimum field. This is used
333 * when we do negative caching, to determine the TTL for the negative caching entry. See RFC
334 * 2308, Section 5. */
336 if (ttl
> rr
->soa
.minimum
)
337 ttl
= rr
->soa
.minimum
;
340 u
= ttl
* USEC_PER_SEC
;
341 if (u
> CACHE_TTL_MAX_USEC
)
342 u
= CACHE_TTL_MAX_USEC
;
344 if (rr
->expiry
!= USEC_INFINITY
) {
347 /* Make use of the DNSSEC RRSIG expiry info, if we have it */
349 left
= LESS_BY(rr
->expiry
, now(CLOCK_REALTIME
));
354 return timestamp
+ u
;
357 static usec_t
calculate_until(
359 usec_t stale_retention_usec
) {
361 return stale_retention_usec
> 0 ? usec_add(until_valid
, stale_retention_usec
) : until_valid
;
364 static void dns_cache_item_update_positive(
367 DnsResourceRecord
*rr
,
369 DnsPacket
*full_packet
,
371 uint64_t query_flags
,
373 DnssecResult dnssec_result
,
377 const union in_addr_union
*owner_address
,
378 usec_t stale_retention_usec
) {
383 assert(owner_address
);
385 i
->type
= DNS_CACHE_POSITIVE
;
388 /* We are the first item in the list, we need to
389 * update the key used in the hashmap */
391 assert_se(hashmap_replace(c
->by_key
, rr
->key
, i
) >= 0);
393 DNS_RR_REPLACE(i
->rr
, dns_resource_record_ref(rr
));
395 DNS_RESOURCE_KEY_REPLACE(i
->key
, dns_resource_key_ref(rr
->key
));
397 DNS_ANSWER_REPLACE(i
->answer
, dns_answer_ref(answer
));
399 DNS_PACKET_REPLACE(i
->full_packet
, dns_packet_ref(full_packet
));
401 i
->until_valid
= calculate_until_valid(rr
, min_ttl
, UINT32_MAX
, timestamp
, false);
402 i
->until
= calculate_until(i
->until_valid
, stale_retention_usec
);
403 i
->query_flags
= query_flags
& CACHEABLE_QUERY_FLAGS
;
404 i
->shared_owner
= shared_owner
;
405 i
->dnssec_result
= dnssec_result
;
407 i
->ifindex
= ifindex
;
409 i
->owner_family
= owner_family
;
410 i
->owner_address
= *owner_address
;
412 prioq_reshuffle(c
->by_expiry
, i
, &i
->prioq_idx
);
415 static int dns_cache_put_positive(
417 DnsProtocol protocol
,
418 DnsResourceRecord
*rr
,
420 DnsPacket
*full_packet
,
421 uint64_t query_flags
,
423 DnssecResult dnssec_result
,
427 const union in_addr_union
*owner_address
,
428 usec_t stale_retention_usec
) {
430 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
431 DnsCacheItem
*existing
;
437 assert(owner_address
);
439 /* Never cache pseudo RRs */
440 if (dns_class_is_pseudo(rr
->key
->class))
442 if (dns_type_is_pseudo(rr
->key
->type
))
445 /* Determine the minimal TTL of all RRs in the answer plus the one by the main RR we are supposed to
446 * cache. Since we cache whole answers to questions we should never return answers where only some
447 * RRs are still valid, hence find the lowest here */
448 min_ttl
= MIN(dns_answer_min_ttl(answer
), rr
->ttl
);
450 /* New TTL is 0? Delete this specific entry... */
452 r
= dns_cache_remove_by_rr(c
, rr
);
454 r
> 0 ? "Removed zero TTL entry from cache" : "Not caching zero TTL cache entry",
455 dns_resource_key_to_string(rr
->key
, key_str
, sizeof key_str
));
459 /* Entry exists already? Update TTL, timestamp and owner */
460 existing
= dns_cache_get(c
, rr
);
462 dns_cache_item_update_positive(
476 stale_retention_usec
);
480 /* Do not cache mDNS goodbye packet. */
481 if (protocol
== DNS_PROTOCOL_MDNS
&& rr
->ttl
<= 1)
484 /* Otherwise, add the new RR */
485 r
= dns_cache_init(c
);
489 dns_cache_make_space(c
, 1);
491 _cleanup_(dns_cache_item_freep
) DnsCacheItem
*i
= new(DnsCacheItem
, 1);
495 /* If StaleRetentionSec is greater than zero, the 'until' property is set to a duration
496 * of StaleRetentionSec from the time of TTL expiry.
497 * If StaleRetentionSec is zero, both the 'until' and 'until_valid' are set to the TTL duration,
498 * leading to the eviction of the record once the TTL expires.*/
499 usec_t until_valid
= calculate_until_valid(rr
, min_ttl
, UINT32_MAX
, timestamp
, false);
500 *i
= (DnsCacheItem
) {
501 .type
= DNS_CACHE_POSITIVE
,
502 .key
= dns_resource_key_ref(rr
->key
),
503 .rr
= dns_resource_record_ref(rr
),
504 .answer
= dns_answer_ref(answer
),
505 .full_packet
= dns_packet_ref(full_packet
),
506 .until
= calculate_until(until_valid
, stale_retention_usec
),
507 .until_valid
= until_valid
,
508 .query_flags
= query_flags
& CACHEABLE_QUERY_FLAGS
,
509 .shared_owner
= shared_owner
,
510 .dnssec_result
= dnssec_result
,
512 .owner_family
= owner_family
,
513 .owner_address
= *owner_address
,
514 .prioq_idx
= PRIOQ_IDX_NULL
,
517 r
= dns_cache_link_item(c
, i
);
521 log_debug("Added positive %s %s%s cache entry for %s "USEC_FMT
"s on %s/%s/%s",
522 FLAGS_SET(i
->query_flags
, SD_RESOLVED_AUTHENTICATED
) ? "authenticated" : "unauthenticated",
523 FLAGS_SET(i
->query_flags
, SD_RESOLVED_CONFIDENTIAL
) ? "confidential" : "non-confidential",
524 i
->shared_owner
? " shared" : "",
525 dns_resource_key_to_string(i
->key
, key_str
, sizeof key_str
),
526 (i
->until
- timestamp
) / USEC_PER_SEC
,
527 i
->ifindex
== 0 ? "*" : FORMAT_IFNAME(i
->ifindex
),
528 af_to_name_short(i
->owner_family
),
529 IN_ADDR_TO_STRING(i
->owner_family
, &i
->owner_address
));
534 /* https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml */
535 /* https://www.iana.org/assignments/locally-served-dns-zones/locally-served-dns-zones.xhtml#transport-independent */
536 static bool dns_special_use_domain_invalid_answer(DnsResourceKey
*key
, int rcode
) {
537 /* Sometimes we know a domain exists, even if broken nameservers say otherwise. Make sure not to
538 * cache any answers we know are wrong. */
540 /* RFC9462 § 6.4: resolvers SHOULD respond to queries of any type other than SVCB for
541 * _dns.resolver.arpa. with NODATA and queries of any type for any domain name under resolver.arpa
543 if (dns_name_endswith(dns_resource_key_name(key
), "resolver.arpa") > 0 && rcode
== DNS_RCODE_NXDOMAIN
)
549 static int dns_cache_put_negative(
554 DnsPacket
*full_packet
,
555 uint64_t query_flags
,
556 DnssecResult dnssec_result
,
559 DnsResourceRecord
*soa
,
561 const union in_addr_union
*owner_address
) {
563 _cleanup_(dns_cache_item_freep
) DnsCacheItem
*i
= NULL
;
564 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
569 assert(owner_address
);
571 /* Never cache pseudo RR keys. DNS_TYPE_ANY is particularly
572 * important to filter out as we use this as a pseudo-type for
573 * NXDOMAIN entries */
574 if (dns_class_is_pseudo(key
->class))
576 if (dns_type_is_pseudo(key
->type
))
578 if (dns_special_use_domain_invalid_answer(key
, rcode
))
581 if (IN_SET(rcode
, DNS_RCODE_SUCCESS
, DNS_RCODE_NXDOMAIN
)) {
585 /* For negative replies, check if we have a TTL of a SOA */
586 if (nsec_ttl
<= 0 || soa
->soa
.minimum
<= 0 || soa
->ttl
<= 0) {
587 log_debug("Not caching negative entry with zero SOA/NSEC/NSEC3 TTL: %s",
588 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
591 } else if (rcode
!= DNS_RCODE_SERVFAIL
)
594 r
= dns_cache_init(c
);
598 dns_cache_make_space(c
, 1);
600 i
= new(DnsCacheItem
, 1);
604 *i
= (DnsCacheItem
) {
606 rcode
== DNS_RCODE_SUCCESS
? DNS_CACHE_NODATA
:
607 rcode
== DNS_RCODE_NXDOMAIN
? DNS_CACHE_NXDOMAIN
: DNS_CACHE_RCODE
,
608 .query_flags
= query_flags
& CACHEABLE_QUERY_FLAGS
,
609 .dnssec_result
= dnssec_result
,
610 .owner_family
= owner_family
,
611 .owner_address
= *owner_address
,
612 .prioq_idx
= PRIOQ_IDX_NULL
,
614 .answer
= dns_answer_ref(answer
),
615 .full_packet
= dns_packet_ref(full_packet
),
618 /* Determine how long to cache this entry. In case we have some RRs in the answer use the lowest TTL
619 * of any of them. Typically that's the SOA's TTL, which is OK, but could possibly be lower because
620 * of some other RR. Let's better take the lowest option here than a needlessly high one */
621 i
->until
= i
->until_valid
=
622 i
->type
== DNS_CACHE_RCODE
? timestamp
+ CACHE_TTL_STRANGE_RCODE_USEC
:
623 calculate_until_valid(soa
, dns_answer_min_ttl(answer
), nsec_ttl
, timestamp
, true);
625 if (i
->type
== DNS_CACHE_NXDOMAIN
) {
626 /* NXDOMAIN entries should apply equally to all types, so we use ANY as
627 * a pseudo type for this purpose here. */
628 i
->key
= dns_resource_key_new(key
->class, DNS_TYPE_ANY
, dns_resource_key_name(key
));
632 /* Make sure to remove any previous entry for this
633 * specific ANY key. (For non-ANY keys the cache data
634 * is already cleared by the caller.) Note that we
635 * don't bother removing positive or NODATA cache
636 * items in this case, because it would either be slow
637 * or require explicit indexing by name */
638 dns_cache_remove_by_key(c
, key
);
640 i
->key
= dns_resource_key_ref(key
);
642 r
= dns_cache_link_item(c
, i
);
646 log_debug("Added %s cache entry for %s "USEC_FMT
"s",
647 dns_cache_item_type_to_string(i
),
648 dns_resource_key_to_string(i
->key
, key_str
, sizeof key_str
),
649 (i
->until
- timestamp
) / USEC_PER_SEC
);
655 static void dns_cache_remove_previous(
660 DnsResourceRecord
*rr
;
661 DnsAnswerFlags flags
;
665 /* First, if we were passed a key (i.e. on LLMNR/DNS, but
666 * not on mDNS), delete all matching old RRs, so that we only
667 * keep complete by_key in place. */
669 dns_cache_remove_by_key(c
, key
);
671 /* Second, flush all entries matching the answer, unless this
672 * is an RR that is explicitly marked to be "shared" between
673 * peers (i.e. mDNS RRs without the flush-cache bit set). */
674 DNS_ANSWER_FOREACH_FLAGS(rr
, flags
, answer
) {
675 if ((flags
& DNS_ANSWER_CACHEABLE
) == 0)
678 if (flags
& DNS_ANSWER_SHARED_OWNER
)
681 dns_cache_remove_by_key(c
, rr
->key
);
685 static bool rr_eligible(DnsResourceRecord
*rr
) {
688 /* When we see an NSEC/NSEC3 RR, we'll only cache it if it is from the lower zone, not the upper zone, since
689 * that's where the interesting bits are (with exception of DS RRs). Of course, this way we cannot derive DS
690 * existence from any cached NSEC/NSEC3, but that should be fine. */
692 switch (rr
->key
->type
) {
695 return !bitmap_isset(rr
->nsec
.types
, DNS_TYPE_NS
) ||
696 bitmap_isset(rr
->nsec
.types
, DNS_TYPE_SOA
);
699 return !bitmap_isset(rr
->nsec3
.types
, DNS_TYPE_NS
) ||
700 bitmap_isset(rr
->nsec3
.types
, DNS_TYPE_SOA
);
709 DnsCacheMode cache_mode
,
710 DnsProtocol protocol
,
714 DnsPacket
*full_packet
,
715 uint64_t query_flags
,
716 DnssecResult dnssec_result
,
719 const union in_addr_union
*owner_address
,
720 usec_t stale_retention_usec
) {
722 DnsResourceRecord
*soa
= NULL
;
723 bool weird_rcode
= false;
725 DnsAnswerFlags flags
;
731 assert(owner_address
);
733 dns_cache_remove_previous(c
, key
, answer
);
735 /* We only care for positive replies and NXDOMAINs, on all other replies we will simply flush the respective
736 * entries, and that's it. (Well, with one further exception: since some DNS zones (akamai!) return SERVFAIL
737 * consistently for some lookups, and forwarders tend to propagate that we'll cache that too, but only for a
740 if (IN_SET(rcode
, DNS_RCODE_SUCCESS
, DNS_RCODE_NXDOMAIN
)) {
741 if (dns_answer_isempty(answer
)) {
743 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
745 log_debug("Not caching negative entry without a SOA record: %s",
746 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
753 /* Only cache SERVFAIL as "weird" rcode for now. We can add more later, should that turn out to be
755 if (rcode
!= DNS_RCODE_SERVFAIL
)
761 cache_keys
= dns_answer_size(answer
);
765 /* Make some space for our new entries */
766 dns_cache_make_space(c
, cache_keys
);
768 timestamp
= now(CLOCK_BOOTTIME
);
770 /* Second, add in positive entries for all contained RRs */
771 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
774 if (!FLAGS_SET(item
->flags
, DNS_ANSWER_CACHEABLE
) ||
775 !rr_eligible(item
->rr
))
779 /* We store the auxiliary RRs and packet data in the cache only if they were in
780 * direct response to the original query. If we cache an RR we also received, and
781 * that is just auxiliary information we can't use the data, hence don't. */
783 primary
= dns_resource_key_match_rr(key
, item
->rr
, NULL
);
787 primary
= dns_resource_key_match_cname_or_dname(key
, item
->rr
->key
, NULL
);
796 /* Do not replace existing cache items for primary lookups with non-primary
797 * data. After all the primary lookup data is a lot more useful. */
798 first
= hashmap_get(c
->by_key
, item
->rr
->key
);
799 if (first
&& DNS_CACHE_ITEM_IS_PRIMARY(first
))
803 r
= dns_cache_put_positive(
807 primary
? answer
: NULL
,
808 primary
? full_packet
: NULL
,
809 ((item
->flags
& DNS_ANSWER_AUTHENTICATED
) ? SD_RESOLVED_AUTHENTICATED
: 0) |
810 (query_flags
& SD_RESOLVED_CONFIDENTIAL
),
811 item
->flags
& DNS_ANSWER_SHARED_OWNER
,
817 stale_retention_usec
);
822 if (!key
) /* mDNS doesn't know negative caching, really */
825 /* Third, add in negative entries if the key has no RR */
826 r
= dns_answer_match_key(answer
, key
, NULL
);
832 /* But not if it has a matching CNAME/DNAME (the negative caching will be done on the canonical name,
833 * not on the alias) */
834 r
= dns_answer_find_cname_or_dname(answer
, key
, NULL
, NULL
);
840 /* See https://tools.ietf.org/html/rfc2308, which say that a matching SOA record in the packet is used to
841 * enable negative caching. We apply one exception though: if we are about to cache a weird rcode we do so
842 * regardless of a SOA. */
843 r
= dns_answer_find_soa(answer
, key
, &soa
, &flags
);
846 if (r
== 0 && !weird_rcode
)
849 /* Refuse using the SOA data if it is unsigned, but the key is signed */
850 if (FLAGS_SET(query_flags
, SD_RESOLVED_AUTHENTICATED
) &&
851 (flags
& DNS_ANSWER_AUTHENTICATED
) == 0)
855 if (cache_mode
== DNS_CACHE_MODE_NO_NEGATIVE
) {
856 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
857 log_debug("Not caching negative entry for: %s, cache mode set to no-negative",
858 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
862 r
= dns_cache_put_negative(
881 /* Adding all RRs failed. Let's clean up what we already
882 * added, just in case */
885 dns_cache_remove_by_key(c
, key
);
887 DNS_ANSWER_FOREACH_ITEM(item
, answer
) {
888 if ((item
->flags
& DNS_ANSWER_CACHEABLE
) == 0)
891 dns_cache_remove_by_key(c
, item
->rr
->key
);
897 static DnsCacheItem
*dns_cache_get_by_key_follow_cname_dname_nsec(DnsCache
*c
, DnsResourceKey
*k
) {
905 /* If we hit some OOM error, or suchlike, we don't care too
906 * much, after all this is just a cache */
908 i
= hashmap_get(c
->by_key
, k
);
912 n
= dns_resource_key_name(k
);
914 /* Check if we have an NXDOMAIN cache item for the name, notice that we use
915 * the pseudo-type ANY for NXDOMAIN cache items. */
916 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_ANY
, n
));
917 if (i
&& i
->type
== DNS_CACHE_NXDOMAIN
)
920 if (dns_type_may_redirect(k
->type
)) {
921 /* Check if we have a CNAME record instead */
922 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_CNAME
, n
));
923 if (i
&& i
->type
!= DNS_CACHE_NODATA
)
926 /* OK, let's look for cached DNAME records. */
931 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_DNAME
, n
));
932 if (i
&& i
->type
!= DNS_CACHE_NODATA
)
935 /* Jump one label ahead */
936 r
= dns_name_parent(&n
);
942 if (k
->type
!= DNS_TYPE_NSEC
) {
943 /* Check if we have an NSEC record instead for the name. */
944 i
= hashmap_get(c
->by_key
, &DNS_RESOURCE_KEY_CONST(k
->class, DNS_TYPE_NSEC
, n
));
952 static int answer_add_clamp_ttl(
954 DnsResourceRecord
*rr
,
956 DnsAnswerFlags answer_flags
,
957 DnsResourceRecord
*rrsig
,
958 uint64_t query_flags
,
962 _cleanup_(dns_resource_record_unrefp
) DnsResourceRecord
*patched
= NULL
, *patched_rrsig
= NULL
;
968 if (FLAGS_SET(query_flags
, SD_RESOLVED_CLAMP_TTL
)) {
973 /* Let's determine how much time is left for this cache entry. Note that we round down, but
974 * clamp this to be 1s at minimum, since we usually want records to remain cached better too
975 * short a time than too long a time, but otoh don't want to return 0 ever, since that has
976 * special semantics in various contexts — in particular in mDNS */
978 left_ttl
= MAX(1U, LESS_BY(until
, current
) / USEC_PER_SEC
);
980 patched
= dns_resource_record_ref(rr
);
982 r
= dns_resource_record_clamp_ttl(&patched
, left_ttl
);
989 patched_rrsig
= dns_resource_record_ref(rrsig
);
990 r
= dns_resource_record_clamp_ttl(&patched_rrsig
, left_ttl
);
994 rrsig
= patched_rrsig
;
998 r
= dns_answer_add_extend(answer
, rr
, ifindex
, answer_flags
, rrsig
);
1005 int dns_cache_lookup(
1007 DnsResourceKey
*key
,
1008 uint64_t query_flags
,
1010 DnsAnswer
**ret_answer
,
1011 DnsPacket
**ret_full_packet
,
1012 uint64_t *ret_query_flags
,
1013 DnssecResult
*ret_dnssec_result
) {
1015 _cleanup_(dns_packet_unrefp
) DnsPacket
*full_packet
= NULL
;
1016 _cleanup_(dns_answer_unrefp
) DnsAnswer
*answer
= NULL
;
1017 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
1020 bool nxdomain
= false;
1021 DnsCacheItem
*first
, *nsec
= NULL
;
1022 bool have_authenticated
= false, have_non_authenticated
= false, have_confidential
= false, have_non_confidential
= false;
1024 int found_rcode
= -1;
1025 DnssecResult dnssec_result
= -1;
1026 int have_dnssec_result
= -1;
1031 if (key
->type
== DNS_TYPE_ANY
|| key
->class == DNS_CLASS_ANY
) {
1032 /* If we have ANY lookups we don't use the cache, so that the caller refreshes via the
1035 log_debug("Ignoring cache for ANY lookup: %s",
1036 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1040 first
= dns_cache_get_by_key_follow_cname_dname_nsec(c
, key
);
1042 /* If one question cannot be answered we need to refresh */
1044 log_debug("Cache miss for %s",
1045 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1049 if ((query_flags
& (SD_RESOLVED_CLAMP_TTL
| SD_RESOLVED_NO_STALE
)) != 0) {
1050 /* 'current' is always passed to answer_add_clamp_ttl(), but is only used conditionally.
1051 * We'll do the same assert there to make sure that it was initialized properly.
1052 * 'current' is also used below when SD_RESOLVED_NO_STALE is set. */
1053 current
= now(CLOCK_BOOTTIME
);
1054 assert(current
> 0);
1057 LIST_FOREACH(by_key
, j
, first
) {
1058 /* If the caller doesn't allow us to answer questions from cache data learned from
1059 * "side-effect", skip this entry. */
1060 if (FLAGS_SET(query_flags
, SD_RESOLVED_REQUIRE_PRIMARY
) &&
1061 !DNS_CACHE_ITEM_IS_PRIMARY(j
)) {
1062 log_debug("Primary answer was requested for cache lookup for %s, which we don't have.",
1063 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1068 /* Skip the next part if ttl is expired and requested with no stale flag. */
1069 if (FLAGS_SET(query_flags
, SD_RESOLVED_NO_STALE
) && j
->until_valid
< current
) {
1070 log_debug("Requested with no stale and TTL expired for %s",
1071 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1076 if (j
->type
== DNS_CACHE_NXDOMAIN
)
1078 else if (j
->type
== DNS_CACHE_RCODE
)
1079 found_rcode
= j
->rcode
;
1081 if (j
->rr
->key
->type
== DNS_TYPE_NSEC
)
1087 if (FLAGS_SET(j
->query_flags
, SD_RESOLVED_AUTHENTICATED
))
1088 have_authenticated
= true;
1090 have_non_authenticated
= true;
1092 if (FLAGS_SET(j
->query_flags
, SD_RESOLVED_CONFIDENTIAL
))
1093 have_confidential
= true;
1095 have_non_confidential
= true;
1097 if (j
->dnssec_result
< 0) {
1098 have_dnssec_result
= false; /* an entry without dnssec result? then invalidate things for good */
1099 dnssec_result
= _DNSSEC_RESULT_INVALID
;
1100 } else if (have_dnssec_result
< 0) {
1101 have_dnssec_result
= true; /* So far no result seen, let's pick this one up */
1102 dnssec_result
= j
->dnssec_result
;
1103 } else if (have_dnssec_result
> 0 && j
->dnssec_result
!= dnssec_result
) {
1104 have_dnssec_result
= false; /* conflicting result seen? then invalidate for good */
1105 dnssec_result
= _DNSSEC_RESULT_INVALID
;
1108 /* If the question is being resolved using stale data, the clamp TTL will be set to CACHE_STALE_TTL_MAX_USEC. */
1109 usec_t until
= FLAGS_SET(query_flags
, SD_RESOLVED_NO_STALE
) ? j
->until_valid
1110 : usec_add(current
, CACHE_STALE_TTL_MAX_USEC
);
1112 /* Append the answer RRs to our answer. Ideally we have the answer object, which we
1113 * preferably use. But if the cached entry was generated as "side-effect" of a reply,
1114 * i.e. from validated auxiliary records rather than from the main reply, then we use the
1115 * individual RRs only instead. */
1118 /* Minor optimization, if the full answer object of this and the previous RR is the
1119 * same, don't bother adding it again. Typically we store a full RRset here, hence
1120 * that should be the case. */
1121 if (!j
->by_key_prev
|| j
->answer
!= j
->by_key_prev
->answer
) {
1122 DnsAnswerItem
*item
;
1124 DNS_ANSWER_FOREACH_ITEM(item
, j
->answer
) {
1125 r
= answer_add_clamp_ttl(
1140 r
= answer_add_clamp_ttl(
1144 FLAGS_SET(j
->query_flags
, SD_RESOLVED_AUTHENTICATED
) ? DNS_ANSWER_AUTHENTICATED
: 0,
1153 /* We'll return any packet we have for this. Typically all cache entries for the same key
1154 * should come from the same packet anyway, hence it doesn't really matter which packet we
1155 * return here, they should all resolve to the same anyway. */
1156 if (!full_packet
&& j
->full_packet
)
1157 full_packet
= dns_packet_ref(j
->full_packet
);
1160 if (found_rcode
>= 0) {
1161 log_debug("RCODE %s cache hit for %s",
1162 FORMAT_DNS_RCODE(found_rcode
),
1163 dns_resource_key_to_string(key
, key_str
, sizeof(key_str
)));
1166 *ret_rcode
= found_rcode
;
1168 *ret_answer
= TAKE_PTR(answer
);
1169 if (ret_full_packet
)
1170 *ret_full_packet
= TAKE_PTR(full_packet
);
1171 if (ret_query_flags
)
1172 *ret_query_flags
= 0;
1173 if (ret_dnssec_result
)
1174 *ret_dnssec_result
= dnssec_result
;
1180 if (nsec
&& !IN_SET(key
->type
, DNS_TYPE_NSEC
, DNS_TYPE_DS
)) {
1181 /* Note that we won't derive information for DS RRs from an NSEC, because we only cache NSEC
1182 * RRs from the lower-zone of a zone cut, but the DS RRs are on the upper zone. */
1184 log_debug("NSEC NODATA cache hit for %s",
1185 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1187 /* We only found an NSEC record that matches our name. If it says the type doesn't exist
1188 * report NODATA. Otherwise report a cache miss. */
1191 *ret_rcode
= DNS_RCODE_SUCCESS
;
1193 *ret_answer
= TAKE_PTR(answer
);
1194 if (ret_full_packet
)
1195 *ret_full_packet
= TAKE_PTR(full_packet
);
1196 if (ret_query_flags
)
1197 *ret_query_flags
= nsec
->query_flags
;
1198 if (ret_dnssec_result
)
1199 *ret_dnssec_result
= nsec
->dnssec_result
;
1201 if (!bitmap_isset(nsec
->rr
->nsec
.types
, key
->type
) &&
1202 !bitmap_isset(nsec
->rr
->nsec
.types
, DNS_TYPE_CNAME
) &&
1203 !bitmap_isset(nsec
->rr
->nsec
.types
, DNS_TYPE_DNAME
)) {
1212 log_debug("%s cache hit for %s",
1213 n
> 0 ? "Positive" :
1214 nxdomain
? "NXDOMAIN" : "NODATA",
1215 dns_resource_key_to_string(key
, key_str
, sizeof key_str
));
1221 *ret_rcode
= nxdomain
? DNS_RCODE_NXDOMAIN
: DNS_RCODE_SUCCESS
;
1223 *ret_answer
= TAKE_PTR(answer
);
1224 if (ret_full_packet
)
1225 *ret_full_packet
= TAKE_PTR(full_packet
);
1226 if (ret_query_flags
)
1228 ((have_authenticated
&& !have_non_authenticated
) ? SD_RESOLVED_AUTHENTICATED
: 0) |
1229 ((have_confidential
&& !have_non_confidential
) ? SD_RESOLVED_CONFIDENTIAL
: 0);
1230 if (ret_dnssec_result
)
1231 *ret_dnssec_result
= dnssec_result
;
1239 *ret_rcode
= DNS_RCODE_SUCCESS
;
1241 *ret_answer
= TAKE_PTR(answer
);
1242 if (ret_full_packet
)
1243 *ret_full_packet
= TAKE_PTR(full_packet
);
1244 if (ret_query_flags
)
1246 ((have_authenticated
&& !have_non_authenticated
) ? SD_RESOLVED_AUTHENTICATED
: 0) |
1247 ((have_confidential
&& !have_non_confidential
) ? SD_RESOLVED_CONFIDENTIAL
: 0);
1248 if (ret_dnssec_result
)
1249 *ret_dnssec_result
= dnssec_result
;
1255 *ret_rcode
= DNS_RCODE_SUCCESS
;
1258 if (ret_full_packet
)
1259 *ret_full_packet
= NULL
;
1260 if (ret_query_flags
)
1261 *ret_query_flags
= 0;
1262 if (ret_dnssec_result
)
1263 *ret_dnssec_result
= _DNSSEC_RESULT_INVALID
;
1269 int dns_cache_check_conflicts(DnsCache
*cache
, DnsResourceRecord
*rr
, int owner_family
, const union in_addr_union
*owner_address
) {
1270 DnsCacheItem
*first
;
1271 bool same_owner
= true;
1276 dns_cache_prune(cache
);
1278 /* See if there's a cache entry for the same key. If there
1279 * isn't there's no conflict */
1280 first
= hashmap_get(cache
->by_key
, rr
->key
);
1284 /* See if the RR key is owned by the same owner, if so, there
1285 * isn't a conflict either */
1286 LIST_FOREACH(by_key
, i
, first
) {
1287 if (i
->owner_family
!= owner_family
||
1288 !in_addr_equal(owner_family
, &i
->owner_address
, owner_address
)) {
1296 /* See if there's the exact same RR in the cache. If yes, then
1297 * there's no conflict. */
1298 if (dns_cache_get(cache
, rr
))
1301 /* There's a conflict */
1305 int dns_cache_export_shared_to_packet(DnsCache
*cache
, DnsPacket
*p
, usec_t ts
, unsigned max_rr
) {
1306 unsigned ancount
= 0;
1312 assert(p
->protocol
== DNS_PROTOCOL_MDNS
);
1314 HASHMAP_FOREACH(i
, cache
->by_key
)
1315 LIST_FOREACH(by_key
, j
, i
) {
1319 if (!j
->shared_owner
)
1322 /* Ignore cached goodby packet. See on_mdns_packet() and RFC 6762 section 10.1. */
1323 if (j
->rr
->ttl
<= 1)
1326 /* RFC6762 7.1: Don't append records with less than half the TTL remaining
1327 * as known answers. */
1328 if (usec_sub_unsigned(j
->until
, ts
) < j
->rr
->ttl
* USEC_PER_SEC
/ 2)
1331 if (max_rr
> 0 && ancount
>= max_rr
) {
1332 DNS_PACKET_HEADER(p
)->ancount
= htobe16(ancount
);
1335 r
= dns_packet_new_query(&p
->more
, p
->protocol
, 0, true);
1344 r
= dns_packet_append_rr(p
, j
->rr
, 0, NULL
, NULL
);
1345 if (r
== -EMSGSIZE
) {
1347 /* If max_rr == 0, do not allocate more packets. */
1350 /* If we're unable to stuff all known answers into the given packet, allocate
1351 * a new one, push the RR into that one and link it to the current one. */
1353 DNS_PACKET_HEADER(p
)->ancount
= htobe16(ancount
);
1356 r
= dns_packet_new_query(&p
->more
, p
->protocol
, 0, true);
1360 /* continue with new packet */
1362 r
= dns_packet_append_rr(p
, j
->rr
, 0, NULL
, NULL
);
1372 DNS_PACKET_HEADER(p
)->ancount
= htobe16(ancount
);
1377 void dns_cache_dump(DnsCache
*cache
, FILE *f
) {
1386 HASHMAP_FOREACH(i
, cache
->by_key
)
1387 LIST_FOREACH(by_key
, j
, i
) {
1393 t
= dns_resource_record_to_string(j
->rr
);
1402 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
1404 fputs(dns_resource_key_to_string(j
->key
, key_str
, sizeof key_str
), f
);
1406 fputs(dns_cache_item_type_to_string(j
), f
);
1412 int dns_cache_dump_to_json(DnsCache
*cache
, JsonVariant
**ret
) {
1413 _cleanup_(json_variant_unrefp
) JsonVariant
*c
= NULL
;
1420 HASHMAP_FOREACH(i
, cache
->by_key
) {
1421 _cleanup_(json_variant_unrefp
) JsonVariant
*d
= NULL
, *k
= NULL
;
1423 r
= dns_resource_key_to_json(i
->key
, &k
);
1428 _cleanup_(json_variant_unrefp
) JsonVariant
*l
= NULL
;
1430 LIST_FOREACH(by_key
, j
, i
) {
1431 _cleanup_(json_variant_unrefp
) JsonVariant
*rj
= NULL
;
1435 r
= dns_resource_record_to_json(j
->rr
, &rj
);
1439 r
= dns_resource_record_to_wire_format(j
->rr
, /* canonical= */ false); /* don't use DNSSEC canonical format, since it removes casing, but we want that for DNS_SD compat */
1443 r
= json_variant_append_arrayb(
1446 JSON_BUILD_PAIR_VARIANT("rr", rj
),
1447 JSON_BUILD_PAIR_BASE64("raw", j
->rr
->wire_format
, j
->rr
->wire_format_size
)));
1453 r
= json_variant_new_array(&l
, NULL
, 0);
1460 JSON_BUILD_PAIR_VARIANT("key", k
),
1461 JSON_BUILD_PAIR_VARIANT("rrs", l
),
1462 JSON_BUILD_PAIR_UNSIGNED("until", i
->until
)));
1463 } else if (i
->type
== DNS_CACHE_NODATA
) {
1466 JSON_BUILD_PAIR_VARIANT("key", k
),
1467 JSON_BUILD_PAIR_EMPTY_ARRAY("rrs"),
1468 JSON_BUILD_PAIR_UNSIGNED("until", i
->until
)));
1472 JSON_BUILD_PAIR_VARIANT("key", k
),
1473 JSON_BUILD_PAIR_STRING("type", dns_cache_item_type_to_string(i
)),
1474 JSON_BUILD_PAIR_UNSIGNED("until", i
->until
)));
1478 r
= json_variant_append_array(&c
, d
);
1484 return json_variant_new_array(ret
, NULL
, 0);
1490 bool dns_cache_is_empty(DnsCache
*cache
) {
1494 return hashmap_isempty(cache
->by_key
);
1497 unsigned dns_cache_size(DnsCache
*cache
) {
1501 return hashmap_size(cache
->by_key
);