1:255.13-alt1
[systemd_ALT.git] / src / resolve / resolved-dns-cache.c
blobe90915e64d5918c0163540debdca194c787435b7
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <net/if.h>
5 #include "af-list.h"
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
25 * now) */
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 {
34 DNS_CACHE_POSITIVE,
35 DNS_CACHE_NODATA,
36 DNS_CACHE_NXDOMAIN,
37 DNS_CACHE_RCODE, /* "strange" RCODE (effective only SERVFAIL for now) */
40 struct DnsCacheItem {
41 DnsCacheItemType type;
42 int rcode;
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;
53 int ifindex;
54 int owner_family;
55 union in_addr_union owner_address;
57 unsigned prioq_idx;
58 LIST_FIELDS(DnsCacheItem, by_key);
60 bool shared_owner;
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) {
70 assert(item);
72 switch (item->type) {
74 case DNS_CACHE_POSITIVE:
75 return "POSITIVE";
77 case DNS_CACHE_NODATA:
78 return "NODATA";
80 case DNS_CACHE_NXDOMAIN:
81 return "NXDOMAIN";
83 case DNS_CACHE_RCODE:
84 return dns_rcode_to_string(item->rcode);
87 return NULL;
90 static DnsCacheItem* dns_cache_item_free(DnsCacheItem *i) {
91 if (!i)
92 return NULL;
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);
98 return mfree(i);
100 DEFINE_TRIVIAL_CLEANUP_FUNC(DnsCacheItem*, dns_cache_item_free);
102 static void dns_cache_item_unlink_and_free(DnsCache *c, DnsCacheItem *i) {
103 DnsCacheItem *first;
105 assert(c);
107 if (!i)
108 return;
110 first = hashmap_get(c->by_key, i->key);
111 LIST_REMOVE(by_key, first, i);
113 if (first)
114 assert_se(hashmap_replace(c->by_key, first->key, first) >= 0);
115 else
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) {
124 DnsCacheItem *first;
125 int r;
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);
130 if (r < 0)
131 return r;
132 if (r > 0) {
133 dns_cache_item_unlink_and_free(c, i);
134 return true;
138 return false;
141 static bool dns_cache_remove_by_key(DnsCache *c, DnsResourceKey *key) {
142 DnsCacheItem *first;
144 assert(c);
145 assert(key);
147 first = hashmap_remove(c->by_key, key);
148 if (!first)
149 return false;
151 LIST_FOREACH(by_key, i, first) {
152 prioq_remove(c->by_expiry, i, &i->prioq_idx);
153 dns_cache_item_free(i);
156 return true;
159 void dns_cache_flush(DnsCache *c) {
160 DnsResourceKey *key;
162 assert(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) {
175 assert(c);
177 if (add <= 0)
178 return;
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. */
185 for (;;) {
186 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
187 DnsCacheItem *i;
189 if (prioq_size(c->by_expiry) <= 0)
190 break;
192 if (prioq_size(c->by_expiry) + add < CACHE_MAX)
193 break;
195 i = prioq_peek(c->by_expiry);
196 assert(i);
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) {
206 usec_t t = 0;
208 assert(c);
210 /* Remove all entries that are past their TTL */
212 for (;;) {
213 DnsCacheItem *i;
214 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
216 i = prioq_peek(c->by_expiry);
217 if (!i)
218 break;
220 if (t <= 0)
221 t = now(CLOCK_BOOTTIME);
223 if (i->until > t)
224 break;
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);
233 if (i->shared_owner)
234 dns_cache_item_unlink_and_free(c, i);
235 else {
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) {
253 int r;
255 assert(c);
257 r = prioq_ensure_allocated(&c->by_expiry, dns_cache_item_prioq_compare_func);
258 if (r < 0)
259 return r;
261 r = hashmap_ensure_allocated(&c->by_key, &dns_resource_key_hash_ops);
262 if (r < 0)
263 return r;
265 return r;
268 static int dns_cache_link_item(DnsCache *c, DnsCacheItem *i) {
269 DnsCacheItem *first;
270 int r;
272 assert(c);
273 assert(i);
275 r = prioq_put(c->by_expiry, i, &i->prioq_idx);
276 if (r < 0)
277 return r;
279 first = hashmap_get(c->by_key, i->key);
280 if (first) {
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);
289 if (first->rr)
290 dns_resource_key_reduce(&first->rr->key, &i->key);
291 if (i->rr)
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);
296 } else {
297 r = hashmap_put(c->by_key, i->key, i);
298 if (r < 0) {
299 prioq_remove(c->by_expiry, i, &i->prioq_idx);
300 return r;
304 return 0;
307 static DnsCacheItem* dns_cache_get(DnsCache *c, DnsResourceRecord *rr) {
308 assert(c);
309 assert(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)
313 return i;
315 return NULL;
318 static usec_t calculate_until_valid(
319 DnsResourceRecord *rr,
320 uint32_t min_ttl,
321 uint32_t nsec_ttl,
322 usec_t timestamp,
323 bool use_soa_minimum) {
325 uint32_t ttl;
326 usec_t u;
328 assert(rr);
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) {
345 usec_t left;
347 /* Make use of the DNSSEC RRSIG expiry info, if we have it */
349 left = LESS_BY(rr->expiry, now(CLOCK_REALTIME));
350 if (u > left)
351 u = left;
354 return timestamp + u;
357 static usec_t calculate_until(
358 usec_t until_valid,
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(
365 DnsCache *c,
366 DnsCacheItem *i,
367 DnsResourceRecord *rr,
368 DnsAnswer *answer,
369 DnsPacket *full_packet,
370 uint32_t min_ttl,
371 uint64_t query_flags,
372 bool shared_owner,
373 DnssecResult dnssec_result,
374 usec_t timestamp,
375 int ifindex,
376 int owner_family,
377 const union in_addr_union *owner_address,
378 usec_t stale_retention_usec) {
380 assert(c);
381 assert(i);
382 assert(rr);
383 assert(owner_address);
385 i->type = DNS_CACHE_POSITIVE;
387 if (!i->by_key_prev)
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(
416 DnsCache *c,
417 DnsProtocol protocol,
418 DnsResourceRecord *rr,
419 DnsAnswer *answer,
420 DnsPacket *full_packet,
421 uint64_t query_flags,
422 bool shared_owner,
423 DnssecResult dnssec_result,
424 usec_t timestamp,
425 int ifindex,
426 int owner_family,
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;
432 uint32_t min_ttl;
433 int r;
435 assert(c);
436 assert(rr);
437 assert(owner_address);
439 /* Never cache pseudo RRs */
440 if (dns_class_is_pseudo(rr->key->class))
441 return 0;
442 if (dns_type_is_pseudo(rr->key->type))
443 return 0;
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... */
451 if (min_ttl <= 0) {
452 r = dns_cache_remove_by_rr(c, rr);
453 log_debug("%s: %s",
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));
456 return 0;
459 /* Entry exists already? Update TTL, timestamp and owner */
460 existing = dns_cache_get(c, rr);
461 if (existing) {
462 dns_cache_item_update_positive(
464 existing,
466 answer,
467 full_packet,
468 min_ttl,
469 query_flags,
470 shared_owner,
471 dnssec_result,
472 timestamp,
473 ifindex,
474 owner_family,
475 owner_address,
476 stale_retention_usec);
477 return 0;
480 /* Do not cache mDNS goodbye packet. */
481 if (protocol == DNS_PROTOCOL_MDNS && rr->ttl <= 1)
482 return 0;
484 /* Otherwise, add the new RR */
485 r = dns_cache_init(c);
486 if (r < 0)
487 return r;
489 dns_cache_make_space(c, 1);
491 _cleanup_(dns_cache_item_freep) DnsCacheItem *i = new(DnsCacheItem, 1);
492 if (!i)
493 return -ENOMEM;
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,
511 .ifindex = ifindex,
512 .owner_family = owner_family,
513 .owner_address = *owner_address,
514 .prioq_idx = PRIOQ_IDX_NULL,
517 r = dns_cache_link_item(c, i);
518 if (r < 0)
519 return r;
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));
531 TAKE_PTR(i);
532 return 0;
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
542 * with NODATA. */
543 if (dns_name_endswith(dns_resource_key_name(key), "resolver.arpa") > 0 && rcode == DNS_RCODE_NXDOMAIN)
544 return true;
546 return false;
549 static int dns_cache_put_negative(
550 DnsCache *c,
551 DnsResourceKey *key,
552 int rcode,
553 DnsAnswer *answer,
554 DnsPacket *full_packet,
555 uint64_t query_flags,
556 DnssecResult dnssec_result,
557 uint32_t nsec_ttl,
558 usec_t timestamp,
559 DnsResourceRecord *soa,
560 int owner_family,
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];
565 int r;
567 assert(c);
568 assert(key);
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))
575 return 0;
576 if (dns_type_is_pseudo(key->type))
577 return 0;
578 if (dns_special_use_domain_invalid_answer(key, rcode))
579 return 0;
581 if (IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN)) {
582 if (!soa)
583 return 0;
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));
589 return 0;
591 } else if (rcode != DNS_RCODE_SERVFAIL)
592 return 0;
594 r = dns_cache_init(c);
595 if (r < 0)
596 return r;
598 dns_cache_make_space(c, 1);
600 i = new(DnsCacheItem, 1);
601 if (!i)
602 return -ENOMEM;
604 *i = (DnsCacheItem) {
605 .type =
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,
613 .rcode = rcode,
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));
629 if (!i->key)
630 return -ENOMEM;
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);
639 } else
640 i->key = dns_resource_key_ref(key);
642 r = dns_cache_link_item(c, i);
643 if (r < 0)
644 return r;
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);
651 i = NULL;
652 return 0;
655 static void dns_cache_remove_previous(
656 DnsCache *c,
657 DnsResourceKey *key,
658 DnsAnswer *answer) {
660 DnsResourceRecord *rr;
661 DnsAnswerFlags flags;
663 assert(c);
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. */
668 if (key)
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)
676 continue;
678 if (flags & DNS_ANSWER_SHARED_OWNER)
679 continue;
681 dns_cache_remove_by_key(c, rr->key);
685 static bool rr_eligible(DnsResourceRecord *rr) {
686 assert(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) {
694 case DNS_TYPE_NSEC:
695 return !bitmap_isset(rr->nsec.types, DNS_TYPE_NS) ||
696 bitmap_isset(rr->nsec.types, DNS_TYPE_SOA);
698 case DNS_TYPE_NSEC3:
699 return !bitmap_isset(rr->nsec3.types, DNS_TYPE_NS) ||
700 bitmap_isset(rr->nsec3.types, DNS_TYPE_SOA);
702 default:
703 return true;
707 int dns_cache_put(
708 DnsCache *c,
709 DnsCacheMode cache_mode,
710 DnsProtocol protocol,
711 DnsResourceKey *key,
712 int rcode,
713 DnsAnswer *answer,
714 DnsPacket *full_packet,
715 uint64_t query_flags,
716 DnssecResult dnssec_result,
717 uint32_t nsec_ttl,
718 int owner_family,
719 const union in_addr_union *owner_address,
720 usec_t stale_retention_usec) {
722 DnsResourceRecord *soa = NULL;
723 bool weird_rcode = false;
724 DnsAnswerItem *item;
725 DnsAnswerFlags flags;
726 unsigned cache_keys;
727 usec_t timestamp;
728 int r;
730 assert(c);
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
738 * short time.) */
740 if (IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN)) {
741 if (dns_answer_isempty(answer)) {
742 if (key) {
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));
749 return 0;
752 } else {
753 /* Only cache SERVFAIL as "weird" rcode for now. We can add more later, should that turn out to be
754 * beneficial. */
755 if (rcode != DNS_RCODE_SERVFAIL)
756 return 0;
758 weird_rcode = true;
761 cache_keys = dns_answer_size(answer);
762 if (key)
763 cache_keys++;
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) {
772 int primary = false;
774 if (!FLAGS_SET(item->flags, DNS_ANSWER_CACHEABLE) ||
775 !rr_eligible(item->rr))
776 continue;
778 if (key) {
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);
784 if (primary < 0)
785 return primary;
786 if (primary == 0) {
787 primary = dns_resource_key_match_cname_or_dname(key, item->rr->key, NULL);
788 if (primary < 0)
789 return primary;
793 if (!primary) {
794 DnsCacheItem *first;
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))
800 return 0;
803 r = dns_cache_put_positive(
805 protocol,
806 item->rr,
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,
812 dnssec_result,
813 timestamp,
814 item->ifindex,
815 owner_family,
816 owner_address,
817 stale_retention_usec);
818 if (r < 0)
819 goto fail;
822 if (!key) /* mDNS doesn't know negative caching, really */
823 return 0;
825 /* Third, add in negative entries if the key has no RR */
826 r = dns_answer_match_key(answer, key, NULL);
827 if (r < 0)
828 goto fail;
829 if (r > 0)
830 return 0;
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);
835 if (r < 0)
836 goto fail;
837 if (r > 0)
838 return 0;
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);
844 if (r < 0)
845 goto fail;
846 if (r == 0 && !weird_rcode)
847 return 0;
848 if (r > 0) {
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)
852 return 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));
859 return 0;
862 r = dns_cache_put_negative(
864 key,
865 rcode,
866 answer,
867 full_packet,
868 query_flags,
869 dnssec_result,
870 nsec_ttl,
871 timestamp,
872 soa,
873 owner_family,
874 owner_address);
875 if (r < 0)
876 goto fail;
878 return 0;
880 fail:
881 /* Adding all RRs failed. Let's clean up what we already
882 * added, just in case */
884 if (key)
885 dns_cache_remove_by_key(c, key);
887 DNS_ANSWER_FOREACH_ITEM(item, answer) {
888 if ((item->flags & DNS_ANSWER_CACHEABLE) == 0)
889 continue;
891 dns_cache_remove_by_key(c, item->rr->key);
894 return r;
897 static DnsCacheItem *dns_cache_get_by_key_follow_cname_dname_nsec(DnsCache *c, DnsResourceKey *k) {
898 DnsCacheItem *i;
899 const char *n;
900 int r;
902 assert(c);
903 assert(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);
909 if (i)
910 return i;
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)
918 return i;
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)
924 return i;
926 /* OK, let's look for cached DNAME records. */
927 for (;;) {
928 if (isempty(n))
929 return NULL;
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)
933 return i;
935 /* Jump one label ahead */
936 r = dns_name_parent(&n);
937 if (r <= 0)
938 return NULL;
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));
945 if (i)
946 return i;
949 return NULL;
952 static int answer_add_clamp_ttl(
953 DnsAnswer **answer,
954 DnsResourceRecord *rr,
955 int ifindex,
956 DnsAnswerFlags answer_flags,
957 DnsResourceRecord *rrsig,
958 uint64_t query_flags,
959 usec_t until,
960 usec_t current) {
962 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *patched = NULL, *patched_rrsig = NULL;
963 int r;
965 assert(answer);
966 assert(rr);
968 if (FLAGS_SET(query_flags, SD_RESOLVED_CLAMP_TTL)) {
969 uint32_t left_ttl;
971 assert(current > 0);
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);
983 if (r < 0)
984 return r;
986 rr = patched;
988 if (rrsig) {
989 patched_rrsig = dns_resource_record_ref(rrsig);
990 r = dns_resource_record_clamp_ttl(&patched_rrsig, left_ttl);
991 if (r < 0)
992 return r;
994 rrsig = patched_rrsig;
998 r = dns_answer_add_extend(answer, rr, ifindex, answer_flags, rrsig);
999 if (r < 0)
1000 return r;
1002 return 0;
1005 int dns_cache_lookup(
1006 DnsCache *c,
1007 DnsResourceKey *key,
1008 uint64_t query_flags,
1009 int *ret_rcode,
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];
1018 unsigned n = 0;
1019 int r;
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;
1023 usec_t current = 0;
1024 int found_rcode = -1;
1025 DnssecResult dnssec_result = -1;
1026 int have_dnssec_result = -1;
1028 assert(c);
1029 assert(key);
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
1033 * network. */
1035 log_debug("Ignoring cache for ANY lookup: %s",
1036 dns_resource_key_to_string(key, key_str, sizeof key_str));
1037 goto miss;
1040 first = dns_cache_get_by_key_follow_cname_dname_nsec(c, key);
1041 if (!first) {
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));
1046 goto miss;
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));
1065 goto miss;
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));
1073 goto miss;
1076 if (j->type == DNS_CACHE_NXDOMAIN)
1077 nxdomain = true;
1078 else if (j->type == DNS_CACHE_RCODE)
1079 found_rcode = j->rcode;
1080 else if (j->rr) {
1081 if (j->rr->key->type == DNS_TYPE_NSEC)
1082 nsec = j;
1084 n++;
1087 if (FLAGS_SET(j->query_flags, SD_RESOLVED_AUTHENTICATED))
1088 have_authenticated = true;
1089 else
1090 have_non_authenticated = true;
1092 if (FLAGS_SET(j->query_flags, SD_RESOLVED_CONFIDENTIAL))
1093 have_confidential = true;
1094 else
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. */
1116 if (j->answer) {
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(
1126 &answer,
1127 item->rr,
1128 item->ifindex,
1129 item->flags,
1130 item->rrsig,
1131 query_flags,
1132 until,
1133 current);
1134 if (r < 0)
1135 return r;
1139 } else if (j->rr) {
1140 r = answer_add_clamp_ttl(
1141 &answer,
1142 j->rr,
1143 j->ifindex,
1144 FLAGS_SET(j->query_flags, SD_RESOLVED_AUTHENTICATED) ? DNS_ANSWER_AUTHENTICATED : 0,
1145 NULL,
1146 query_flags,
1147 until,
1148 current);
1149 if (r < 0)
1150 return r;
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)));
1165 if (ret_rcode)
1166 *ret_rcode = found_rcode;
1167 if (ret_answer)
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;
1176 c->n_hit++;
1177 return 1;
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. */
1190 if (ret_rcode)
1191 *ret_rcode = DNS_RCODE_SUCCESS;
1192 if (ret_answer)
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)) {
1204 c->n_hit++;
1205 return 1;
1208 c->n_miss++;
1209 return 0;
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));
1217 if (n <= 0) {
1218 c->n_hit++;
1220 if (ret_rcode)
1221 *ret_rcode = nxdomain ? DNS_RCODE_NXDOMAIN : DNS_RCODE_SUCCESS;
1222 if (ret_answer)
1223 *ret_answer = TAKE_PTR(answer);
1224 if (ret_full_packet)
1225 *ret_full_packet = TAKE_PTR(full_packet);
1226 if (ret_query_flags)
1227 *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;
1233 return 1;
1236 c->n_hit++;
1238 if (ret_rcode)
1239 *ret_rcode = DNS_RCODE_SUCCESS;
1240 if (ret_answer)
1241 *ret_answer = TAKE_PTR(answer);
1242 if (ret_full_packet)
1243 *ret_full_packet = TAKE_PTR(full_packet);
1244 if (ret_query_flags)
1245 *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;
1251 return n;
1253 miss:
1254 if (ret_rcode)
1255 *ret_rcode = DNS_RCODE_SUCCESS;
1256 if (ret_answer)
1257 *ret_answer = NULL;
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;
1265 c->n_miss++;
1266 return 0;
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;
1273 assert(cache);
1274 assert(rr);
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);
1281 if (!first)
1282 return 0;
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)) {
1289 same_owner = false;
1290 break;
1293 if (same_owner)
1294 return 0;
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))
1299 return 0;
1301 /* There's a conflict */
1302 return 1;
1305 int dns_cache_export_shared_to_packet(DnsCache *cache, DnsPacket *p, usec_t ts, unsigned max_rr) {
1306 unsigned ancount = 0;
1307 DnsCacheItem *i;
1308 int r;
1310 assert(cache);
1311 assert(p);
1312 assert(p->protocol == DNS_PROTOCOL_MDNS);
1314 HASHMAP_FOREACH(i, cache->by_key)
1315 LIST_FOREACH(by_key, j, i) {
1316 if (!j->rr)
1317 continue;
1319 if (!j->shared_owner)
1320 continue;
1322 /* Ignore cached goodby packet. See on_mdns_packet() and RFC 6762 section 10.1. */
1323 if (j->rr->ttl <= 1)
1324 continue;
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)
1329 continue;
1331 if (max_rr > 0 && ancount >= max_rr) {
1332 DNS_PACKET_HEADER(p)->ancount = htobe16(ancount);
1333 ancount = 0;
1335 r = dns_packet_new_query(&p->more, p->protocol, 0, true);
1336 if (r < 0)
1337 return r;
1339 p = p->more;
1341 max_rr = UINT_MAX;
1344 r = dns_packet_append_rr(p, j->rr, 0, NULL, NULL);
1345 if (r == -EMSGSIZE) {
1346 if (max_rr == 0)
1347 /* If max_rr == 0, do not allocate more packets. */
1348 goto finalize;
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);
1354 ancount = 0;
1356 r = dns_packet_new_query(&p->more, p->protocol, 0, true);
1357 if (r < 0)
1358 return r;
1360 /* continue with new packet */
1361 p = p->more;
1362 r = dns_packet_append_rr(p, j->rr, 0, NULL, NULL);
1365 if (r < 0)
1366 return r;
1368 ancount++;
1371 finalize:
1372 DNS_PACKET_HEADER(p)->ancount = htobe16(ancount);
1374 return 0;
1377 void dns_cache_dump(DnsCache *cache, FILE *f) {
1378 DnsCacheItem *i;
1380 if (!cache)
1381 return;
1383 if (!f)
1384 f = stdout;
1386 HASHMAP_FOREACH(i, cache->by_key)
1387 LIST_FOREACH(by_key, j, i) {
1389 fputc('\t', f);
1391 if (j->rr) {
1392 const char *t;
1393 t = dns_resource_record_to_string(j->rr);
1394 if (!t) {
1395 log_oom();
1396 continue;
1399 fputs(t, f);
1400 fputc('\n', f);
1401 } else {
1402 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
1404 fputs(dns_resource_key_to_string(j->key, key_str, sizeof key_str), f);
1405 fputs(" -- ", f);
1406 fputs(dns_cache_item_type_to_string(j), f);
1407 fputc('\n', f);
1412 int dns_cache_dump_to_json(DnsCache *cache, JsonVariant **ret) {
1413 _cleanup_(json_variant_unrefp) JsonVariant *c = NULL;
1414 DnsCacheItem *i;
1415 int r;
1417 assert(cache);
1418 assert(ret);
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);
1424 if (r < 0)
1425 return r;
1427 if (i->rr) {
1428 _cleanup_(json_variant_unrefp) JsonVariant *l = NULL;
1430 LIST_FOREACH(by_key, j, i) {
1431 _cleanup_(json_variant_unrefp) JsonVariant *rj = NULL;
1433 assert(j->rr);
1435 r = dns_resource_record_to_json(j->rr, &rj);
1436 if (r < 0)
1437 return r;
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 */
1440 if (r < 0)
1441 return r;
1443 r = json_variant_append_arrayb(
1445 JSON_BUILD_OBJECT(
1446 JSON_BUILD_PAIR_VARIANT("rr", rj),
1447 JSON_BUILD_PAIR_BASE64("raw", j->rr->wire_format, j->rr->wire_format_size)));
1448 if (r < 0)
1449 return r;
1452 if (!l) {
1453 r = json_variant_new_array(&l, NULL, 0);
1454 if (r < 0)
1455 return r;
1458 r = json_build(&d,
1459 JSON_BUILD_OBJECT(
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) {
1464 r = json_build(&d,
1465 JSON_BUILD_OBJECT(
1466 JSON_BUILD_PAIR_VARIANT("key", k),
1467 JSON_BUILD_PAIR_EMPTY_ARRAY("rrs"),
1468 JSON_BUILD_PAIR_UNSIGNED("until", i->until)));
1469 } else
1470 r = json_build(&d,
1471 JSON_BUILD_OBJECT(
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)));
1475 if (r < 0)
1476 return r;
1478 r = json_variant_append_array(&c, d);
1479 if (r < 0)
1480 return r;
1483 if (!c)
1484 return json_variant_new_array(ret, NULL, 0);
1486 *ret = TAKE_PTR(c);
1487 return 0;
1490 bool dns_cache_is_empty(DnsCache *cache) {
1491 if (!cache)
1492 return true;
1494 return hashmap_isempty(cache->by_key);
1497 unsigned dns_cache_size(DnsCache *cache) {
1498 if (!cache)
1499 return 0;
1501 return hashmap_size(cache->by_key);