]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/resolve/resolved-dns-cache.c
resolved: when using the ResolveRecord() bus call, adjust TTL for caching time
[thirdparty/systemd.git] / src / resolve / resolved-dns-cache.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2014 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <net/if.h>
21
22 #include "af-list.h"
23 #include "alloc-util.h"
24 #include "dns-domain.h"
25 #include "resolved-dns-answer.h"
26 #include "resolved-dns-cache.h"
27 #include "resolved-dns-packet.h"
28 #include "string-util.h"
29
30 /* Never cache more than 4K entries. RFC 1536, Section 5 suggests to
31 * leave DNS caches unbounded, but that's crazy. */
32 #define CACHE_MAX 4096
33
34 /* We never keep any item longer than 2h in our cache */
35 #define CACHE_TTL_MAX_USEC (2 * USEC_PER_HOUR)
36
37 typedef enum DnsCacheItemType DnsCacheItemType;
38 typedef struct DnsCacheItem DnsCacheItem;
39
40 enum DnsCacheItemType {
41 DNS_CACHE_POSITIVE,
42 DNS_CACHE_NODATA,
43 DNS_CACHE_NXDOMAIN,
44 };
45
46 struct DnsCacheItem {
47 DnsCacheItemType type;
48 DnsResourceKey *key;
49 DnsResourceRecord *rr;
50
51 usec_t until;
52 bool authenticated:1;
53 bool shared_owner:1;
54
55 int ifindex;
56 int owner_family;
57 union in_addr_union owner_address;
58
59 unsigned prioq_idx;
60 LIST_FIELDS(DnsCacheItem, by_key);
61 };
62
63 static void dns_cache_item_free(DnsCacheItem *i) {
64 if (!i)
65 return;
66
67 dns_resource_record_unref(i->rr);
68 dns_resource_key_unref(i->key);
69 free(i);
70 }
71
72 DEFINE_TRIVIAL_CLEANUP_FUNC(DnsCacheItem*, dns_cache_item_free);
73
74 static void dns_cache_item_unlink_and_free(DnsCache *c, DnsCacheItem *i) {
75 DnsCacheItem *first;
76
77 assert(c);
78
79 if (!i)
80 return;
81
82 first = hashmap_get(c->by_key, i->key);
83 LIST_REMOVE(by_key, first, i);
84
85 if (first)
86 assert_se(hashmap_replace(c->by_key, first->key, first) >= 0);
87 else
88 hashmap_remove(c->by_key, i->key);
89
90 prioq_remove(c->by_expiry, i, &i->prioq_idx);
91
92 dns_cache_item_free(i);
93 }
94
95 static bool dns_cache_remove_by_rr(DnsCache *c, DnsResourceRecord *rr) {
96 DnsCacheItem *first, *i;
97 int r;
98
99 first = hashmap_get(c->by_key, rr->key);
100 LIST_FOREACH(by_key, i, first) {
101 r = dns_resource_record_equal(i->rr, rr);
102 if (r < 0)
103 return r;
104 if (r > 0) {
105 dns_cache_item_unlink_and_free(c, i);
106 return true;
107 }
108 }
109
110 return false;
111 }
112
113 static bool dns_cache_remove_by_key(DnsCache *c, DnsResourceKey *key) {
114 DnsCacheItem *first, *i, *n;
115
116 assert(c);
117 assert(key);
118
119 first = hashmap_remove(c->by_key, key);
120 if (!first)
121 return false;
122
123 LIST_FOREACH_SAFE(by_key, i, n, first) {
124 prioq_remove(c->by_expiry, i, &i->prioq_idx);
125 dns_cache_item_free(i);
126 }
127
128 return true;
129 }
130
131 void dns_cache_flush(DnsCache *c) {
132 DnsResourceKey *key;
133
134 assert(c);
135
136 while ((key = hashmap_first_key(c->by_key)))
137 dns_cache_remove_by_key(c, key);
138
139 assert(hashmap_size(c->by_key) == 0);
140 assert(prioq_size(c->by_expiry) == 0);
141
142 c->by_key = hashmap_free(c->by_key);
143 c->by_expiry = prioq_free(c->by_expiry);
144 }
145
146 static void dns_cache_make_space(DnsCache *c, unsigned add) {
147 assert(c);
148
149 if (add <= 0)
150 return;
151
152 /* Makes space for n new entries. Note that we actually allow
153 * the cache to grow beyond CACHE_MAX, but only when we shall
154 * add more RRs to the cache than CACHE_MAX at once. In that
155 * case the cache will be emptied completely otherwise. */
156
157 for (;;) {
158 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
159 DnsCacheItem *i;
160
161 if (prioq_size(c->by_expiry) <= 0)
162 break;
163
164 if (prioq_size(c->by_expiry) + add < CACHE_MAX)
165 break;
166
167 i = prioq_peek(c->by_expiry);
168 assert(i);
169
170 /* Take an extra reference to the key so that it
171 * doesn't go away in the middle of the remove call */
172 key = dns_resource_key_ref(i->key);
173 dns_cache_remove_by_key(c, key);
174 }
175 }
176
177 void dns_cache_prune(DnsCache *c) {
178 usec_t t = 0;
179
180 assert(c);
181
182 /* Remove all entries that are past their TTL */
183
184 for (;;) {
185 DnsCacheItem *i;
186 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
187
188 i = prioq_peek(c->by_expiry);
189 if (!i)
190 break;
191
192 if (t <= 0)
193 t = now(clock_boottime_or_monotonic());
194
195 if (i->until > t)
196 break;
197
198 /* Depending whether this is an mDNS shared entry
199 * either remove only this one RR or the whole RRset */
200 log_debug("Removing %scache entry for %s (expired "USEC_FMT"s ago)",
201 i->shared_owner ? "shared " : "",
202 dns_resource_key_to_string(i->key, key_str, sizeof key_str),
203 (t - i->until) / USEC_PER_SEC);
204
205 if (i->shared_owner)
206 dns_cache_item_unlink_and_free(c, i);
207 else {
208 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
209
210 /* Take an extra reference to the key so that it
211 * doesn't go away in the middle of the remove call */
212 key = dns_resource_key_ref(i->key);
213 dns_cache_remove_by_key(c, key);
214 }
215 }
216 }
217
218 static int dns_cache_item_prioq_compare_func(const void *a, const void *b) {
219 const DnsCacheItem *x = a, *y = b;
220
221 if (x->until < y->until)
222 return -1;
223 if (x->until > y->until)
224 return 1;
225 return 0;
226 }
227
228 static int dns_cache_init(DnsCache *c) {
229 int r;
230
231 assert(c);
232
233 r = prioq_ensure_allocated(&c->by_expiry, dns_cache_item_prioq_compare_func);
234 if (r < 0)
235 return r;
236
237 r = hashmap_ensure_allocated(&c->by_key, &dns_resource_key_hash_ops);
238 if (r < 0)
239 return r;
240
241 return r;
242 }
243
244 static int dns_cache_link_item(DnsCache *c, DnsCacheItem *i) {
245 DnsCacheItem *first;
246 int r;
247
248 assert(c);
249 assert(i);
250
251 r = prioq_put(c->by_expiry, i, &i->prioq_idx);
252 if (r < 0)
253 return r;
254
255 first = hashmap_get(c->by_key, i->key);
256 if (first) {
257 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *k = NULL;
258
259 /* Keep a reference to the original key, while we manipulate the list. */
260 k = dns_resource_key_ref(first->key);
261
262 /* Now, try to reduce the number of keys we keep */
263 dns_resource_key_reduce(&first->key, &i->key);
264
265 if (first->rr)
266 dns_resource_key_reduce(&first->rr->key, &i->key);
267 if (i->rr)
268 dns_resource_key_reduce(&i->rr->key, &i->key);
269
270 LIST_PREPEND(by_key, first, i);
271 assert_se(hashmap_replace(c->by_key, first->key, first) >= 0);
272 } else {
273 r = hashmap_put(c->by_key, i->key, i);
274 if (r < 0) {
275 prioq_remove(c->by_expiry, i, &i->prioq_idx);
276 return r;
277 }
278 }
279
280 return 0;
281 }
282
283 static DnsCacheItem* dns_cache_get(DnsCache *c, DnsResourceRecord *rr) {
284 DnsCacheItem *i;
285
286 assert(c);
287 assert(rr);
288
289 LIST_FOREACH(by_key, i, hashmap_get(c->by_key, rr->key))
290 if (i->rr && dns_resource_record_equal(i->rr, rr) > 0)
291 return i;
292
293 return NULL;
294 }
295
296 static usec_t calculate_until(DnsResourceRecord *rr, uint32_t nsec_ttl, usec_t timestamp, bool use_soa_minimum) {
297 uint32_t ttl;
298 usec_t u;
299
300 assert(rr);
301
302 ttl = MIN(rr->ttl, nsec_ttl);
303 if (rr->key->type == DNS_TYPE_SOA && use_soa_minimum) {
304 /* If this is a SOA RR, and it is requested, clamp to
305 * the SOA's minimum field. This is used when we do
306 * negative caching, to determine the TTL for the
307 * negative caching entry. See RFC 2308, Section
308 * 5. */
309
310 if (ttl > rr->soa.minimum)
311 ttl = rr->soa.minimum;
312 }
313
314 u = ttl * USEC_PER_SEC;
315 if (u > CACHE_TTL_MAX_USEC)
316 u = CACHE_TTL_MAX_USEC;
317
318 if (rr->expiry != USEC_INFINITY) {
319 usec_t left;
320
321 /* Make use of the DNSSEC RRSIG expiry info, if we
322 * have it */
323
324 left = LESS_BY(rr->expiry, now(CLOCK_REALTIME));
325 if (u > left)
326 u = left;
327 }
328
329 return timestamp + u;
330 }
331
332 static void dns_cache_item_update_positive(
333 DnsCache *c,
334 DnsCacheItem *i,
335 DnsResourceRecord *rr,
336 bool authenticated,
337 bool shared_owner,
338 usec_t timestamp,
339 int ifindex,
340 int owner_family,
341 const union in_addr_union *owner_address) {
342
343 assert(c);
344 assert(i);
345 assert(rr);
346 assert(owner_address);
347
348 i->type = DNS_CACHE_POSITIVE;
349
350 if (!i->by_key_prev)
351 /* We are the first item in the list, we need to
352 * update the key used in the hashmap */
353
354 assert_se(hashmap_replace(c->by_key, rr->key, i) >= 0);
355
356 dns_resource_record_ref(rr);
357 dns_resource_record_unref(i->rr);
358 i->rr = rr;
359
360 dns_resource_key_unref(i->key);
361 i->key = dns_resource_key_ref(rr->key);
362
363 i->until = calculate_until(rr, (uint32_t) -1, timestamp, false);
364 i->authenticated = authenticated;
365 i->shared_owner = shared_owner;
366
367 i->ifindex = ifindex;
368
369 i->owner_family = owner_family;
370 i->owner_address = *owner_address;
371
372 prioq_reshuffle(c->by_expiry, i, &i->prioq_idx);
373 }
374
375 static int dns_cache_put_positive(
376 DnsCache *c,
377 DnsResourceRecord *rr,
378 bool authenticated,
379 bool shared_owner,
380 usec_t timestamp,
381 int ifindex,
382 int owner_family,
383 const union in_addr_union *owner_address) {
384
385 _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
386 DnsCacheItem *existing;
387 char key_str[DNS_RESOURCE_KEY_STRING_MAX], ifname[IF_NAMESIZE];
388 int r, k;
389
390 assert(c);
391 assert(rr);
392 assert(owner_address);
393
394 /* Never cache pseudo RRs */
395 if (dns_class_is_pseudo(rr->key->class))
396 return 0;
397 if (dns_type_is_pseudo(rr->key->type))
398 return 0;
399
400 /* New TTL is 0? Delete this specific entry... */
401 if (rr->ttl <= 0) {
402 k = dns_cache_remove_by_rr(c, rr);
403 log_debug("%s: %s",
404 k > 0 ? "Removed zero TTL entry from cache" : "Not caching zero TTL cache entry",
405 dns_resource_key_to_string(rr->key, key_str, sizeof key_str));
406 return 0;
407 }
408
409 /* Entry exists already? Update TTL, timestamp and owner*/
410 existing = dns_cache_get(c, rr);
411 if (existing) {
412 dns_cache_item_update_positive(
413 c,
414 existing,
415 rr,
416 authenticated,
417 shared_owner,
418 timestamp,
419 ifindex,
420 owner_family,
421 owner_address);
422 return 0;
423 }
424
425 /* Otherwise, add the new RR */
426 r = dns_cache_init(c);
427 if (r < 0)
428 return r;
429
430 dns_cache_make_space(c, 1);
431
432 i = new0(DnsCacheItem, 1);
433 if (!i)
434 return -ENOMEM;
435
436 i->type = DNS_CACHE_POSITIVE;
437 i->key = dns_resource_key_ref(rr->key);
438 i->rr = dns_resource_record_ref(rr);
439 i->until = calculate_until(rr, (uint32_t) -1, timestamp, false);
440 i->authenticated = authenticated;
441 i->shared_owner = shared_owner;
442 i->ifindex = ifindex;
443 i->owner_family = owner_family;
444 i->owner_address = *owner_address;
445 i->prioq_idx = PRIOQ_IDX_NULL;
446
447 r = dns_cache_link_item(c, i);
448 if (r < 0)
449 return r;
450
451 if (log_get_max_level() >= LOG_DEBUG) {
452 _cleanup_free_ char *t = NULL;
453
454 (void) in_addr_to_string(i->owner_family, &i->owner_address, &t);
455
456 log_debug("Added positive %s%s cache entry for %s "USEC_FMT"s on %s/%s/%s",
457 i->authenticated ? "authenticated" : "unauthenticated",
458 i->shared_owner ? " shared" : "",
459 dns_resource_key_to_string(i->key, key_str, sizeof key_str),
460 (i->until - timestamp) / USEC_PER_SEC,
461 i->ifindex == 0 ? "*" : strna(if_indextoname(i->ifindex, ifname)),
462 af_to_name_short(i->owner_family),
463 strna(t));
464 }
465
466 i = NULL;
467 return 0;
468 }
469
470 static int dns_cache_put_negative(
471 DnsCache *c,
472 DnsResourceKey *key,
473 int rcode,
474 bool authenticated,
475 uint32_t nsec_ttl,
476 usec_t timestamp,
477 DnsResourceRecord *soa,
478 int owner_family,
479 const union in_addr_union *owner_address) {
480
481 _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
482 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
483 int r;
484
485 assert(c);
486 assert(key);
487 assert(soa);
488 assert(owner_address);
489
490 /* Never cache pseudo RR keys. DNS_TYPE_ANY is particularly
491 * important to filter out as we use this as a pseudo-type for
492 * NXDOMAIN entries */
493 if (dns_class_is_pseudo(key->class))
494 return 0;
495 if (dns_type_is_pseudo(key->type))
496 return 0;
497
498 if (nsec_ttl <= 0 || soa->soa.minimum <= 0 || soa->ttl <= 0) {
499 log_debug("Not caching negative entry with zero SOA/NSEC/NSEC3 TTL: %s",
500 dns_resource_key_to_string(key, key_str, sizeof key_str));
501 return 0;
502 }
503
504 if (!IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
505 return 0;
506
507 r = dns_cache_init(c);
508 if (r < 0)
509 return r;
510
511 dns_cache_make_space(c, 1);
512
513 i = new0(DnsCacheItem, 1);
514 if (!i)
515 return -ENOMEM;
516
517 i->type = rcode == DNS_RCODE_SUCCESS ? DNS_CACHE_NODATA : DNS_CACHE_NXDOMAIN;
518 i->until = calculate_until(soa, nsec_ttl, timestamp, true);
519 i->authenticated = authenticated;
520 i->owner_family = owner_family;
521 i->owner_address = *owner_address;
522 i->prioq_idx = PRIOQ_IDX_NULL;
523
524 if (i->type == DNS_CACHE_NXDOMAIN) {
525 /* NXDOMAIN entries should apply equally to all types, so we use ANY as
526 * a pseudo type for this purpose here. */
527 i->key = dns_resource_key_new(key->class, DNS_TYPE_ANY, dns_resource_key_name(key));
528 if (!i->key)
529 return -ENOMEM;
530
531 /* Make sure to remove any previous entry for this
532 * specific ANY key. (For non-ANY keys the cache data
533 * is already cleared by the caller.) Note that we
534 * don't bother removing positive or NODATA cache
535 * items in this case, because it would either be slow
536 * or require explicit indexing by name */
537 dns_cache_remove_by_key(c, key);
538 } else
539 i->key = dns_resource_key_ref(key);
540
541 r = dns_cache_link_item(c, i);
542 if (r < 0)
543 return r;
544
545 log_debug("Added %s cache entry for %s "USEC_FMT"s",
546 i->type == DNS_CACHE_NODATA ? "NODATA" : "NXDOMAIN",
547 dns_resource_key_to_string(i->key, key_str, sizeof key_str),
548 (i->until - timestamp) / USEC_PER_SEC);
549
550 i = NULL;
551 return 0;
552 }
553
554 static void dns_cache_remove_previous(
555 DnsCache *c,
556 DnsResourceKey *key,
557 DnsAnswer *answer) {
558
559 DnsResourceRecord *rr;
560 DnsAnswerFlags flags;
561
562 assert(c);
563
564 /* First, if we were passed a key (i.e. on LLMNR/DNS, but
565 * not on mDNS), delete all matching old RRs, so that we only
566 * keep complete by_key in place. */
567 if (key)
568 dns_cache_remove_by_key(c, key);
569
570 /* Second, flush all entries matching the answer, unless this
571 * is an RR that is explicitly marked to be "shared" between
572 * peers (i.e. mDNS RRs without the flush-cache bit set). */
573 DNS_ANSWER_FOREACH_FLAGS(rr, flags, answer) {
574 if ((flags & DNS_ANSWER_CACHEABLE) == 0)
575 continue;
576
577 if (flags & DNS_ANSWER_SHARED_OWNER)
578 continue;
579
580 dns_cache_remove_by_key(c, rr->key);
581 }
582 }
583
584 static bool rr_eligible(DnsResourceRecord *rr) {
585 assert(rr);
586
587 /* When we see an NSEC/NSEC3 RR, we'll only cache it if it is from the lower zone, not the upper zone, since
588 * that's where the interesting bits are (with exception of DS RRs). Of course, this way we cannot derive DS
589 * existence from any cached NSEC/NSEC3, but that should be fine. */
590
591 switch (rr->key->type) {
592
593 case DNS_TYPE_NSEC:
594 return !bitmap_isset(rr->nsec.types, DNS_TYPE_NS) ||
595 bitmap_isset(rr->nsec.types, DNS_TYPE_SOA);
596
597 case DNS_TYPE_NSEC3:
598 return !bitmap_isset(rr->nsec3.types, DNS_TYPE_NS) ||
599 bitmap_isset(rr->nsec3.types, DNS_TYPE_SOA);
600
601 default:
602 return true;
603 }
604 }
605
606 int dns_cache_put(
607 DnsCache *c,
608 DnsResourceKey *key,
609 int rcode,
610 DnsAnswer *answer,
611 bool authenticated,
612 uint32_t nsec_ttl,
613 usec_t timestamp,
614 int owner_family,
615 const union in_addr_union *owner_address) {
616
617 DnsResourceRecord *soa = NULL, *rr;
618 DnsAnswerFlags flags;
619 unsigned cache_keys;
620 int r, ifindex;
621
622 assert(c);
623 assert(owner_address);
624
625 dns_cache_remove_previous(c, key, answer);
626
627 if (dns_answer_size(answer) <= 0) {
628 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
629
630 log_debug("Not caching negative entry without a SOA record: %s",
631 dns_resource_key_to_string(key, key_str, sizeof key_str));
632 return 0;
633 }
634
635 /* We only care for positive replies and NXDOMAINs, on all
636 * other replies we will simply flush the respective entries,
637 * and that's it */
638 if (!IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
639 return 0;
640
641 cache_keys = dns_answer_size(answer);
642 if (key)
643 cache_keys++;
644
645 /* Make some space for our new entries */
646 dns_cache_make_space(c, cache_keys);
647
648 if (timestamp <= 0)
649 timestamp = now(clock_boottime_or_monotonic());
650
651 /* Second, add in positive entries for all contained RRs */
652 DNS_ANSWER_FOREACH_FULL(rr, ifindex, flags, answer) {
653 if ((flags & DNS_ANSWER_CACHEABLE) == 0)
654 continue;
655
656 r = rr_eligible(rr);
657 if (r < 0)
658 return r;
659 if (r == 0)
660 continue;
661
662 r = dns_cache_put_positive(
663 c,
664 rr,
665 flags & DNS_ANSWER_AUTHENTICATED,
666 flags & DNS_ANSWER_SHARED_OWNER,
667 timestamp,
668 ifindex,
669 owner_family, owner_address);
670 if (r < 0)
671 goto fail;
672 }
673
674 if (!key) /* mDNS doesn't know negative caching, really */
675 return 0;
676
677 /* Third, add in negative entries if the key has no RR */
678 r = dns_answer_match_key(answer, key, NULL);
679 if (r < 0)
680 goto fail;
681 if (r > 0)
682 return 0;
683
684 /* But not if it has a matching CNAME/DNAME (the negative
685 * caching will be done on the canonical name, not on the
686 * alias) */
687 r = dns_answer_find_cname_or_dname(answer, key, NULL, NULL);
688 if (r < 0)
689 goto fail;
690 if (r > 0)
691 return 0;
692
693 /* See https://tools.ietf.org/html/rfc2308, which say that a
694 * matching SOA record in the packet is used to to enable
695 * negative caching. */
696 r = dns_answer_find_soa(answer, key, &soa, &flags);
697 if (r < 0)
698 goto fail;
699 if (r == 0)
700 return 0;
701
702 /* Refuse using the SOA data if it is unsigned, but the key is
703 * signed */
704 if (authenticated && (flags & DNS_ANSWER_AUTHENTICATED) == 0)
705 return 0;
706
707 r = dns_cache_put_negative(
708 c,
709 key,
710 rcode,
711 authenticated,
712 nsec_ttl,
713 timestamp,
714 soa,
715 owner_family, owner_address);
716 if (r < 0)
717 goto fail;
718
719 return 0;
720
721 fail:
722 /* Adding all RRs failed. Let's clean up what we already
723 * added, just in case */
724
725 if (key)
726 dns_cache_remove_by_key(c, key);
727
728 DNS_ANSWER_FOREACH_FLAGS(rr, flags, answer) {
729 if ((flags & DNS_ANSWER_CACHEABLE) == 0)
730 continue;
731
732 dns_cache_remove_by_key(c, rr->key);
733 }
734
735 return r;
736 }
737
738 static DnsCacheItem *dns_cache_get_by_key_follow_cname_dname_nsec(DnsCache *c, DnsResourceKey *k) {
739 DnsCacheItem *i;
740 const char *n;
741 int r;
742
743 assert(c);
744 assert(k);
745
746 /* If we hit some OOM error, or suchlike, we don't care too
747 * much, after all this is just a cache */
748
749 i = hashmap_get(c->by_key, k);
750 if (i)
751 return i;
752
753 n = dns_resource_key_name(k);
754
755 /* Check if we have an NXDOMAIN cache item for the name, notice that we use
756 * the pseudo-type ANY for NXDOMAIN cache items. */
757 i = hashmap_get(c->by_key, &DNS_RESOURCE_KEY_CONST(k->class, DNS_TYPE_ANY, n));
758 if (i && i->type == DNS_CACHE_NXDOMAIN)
759 return i;
760
761 if (dns_type_may_redirect(k->type)) {
762 /* Check if we have a CNAME record instead */
763 i = hashmap_get(c->by_key, &DNS_RESOURCE_KEY_CONST(k->class, DNS_TYPE_CNAME, n));
764 if (i)
765 return i;
766
767 /* OK, let's look for cached DNAME records. */
768 for (;;) {
769 if (isempty(n))
770 return NULL;
771
772 i = hashmap_get(c->by_key, &DNS_RESOURCE_KEY_CONST(k->class, DNS_TYPE_DNAME, n));
773 if (i)
774 return i;
775
776 /* Jump one label ahead */
777 r = dns_name_parent(&n);
778 if (r <= 0)
779 return NULL;
780 }
781 }
782
783 if (k->type != DNS_TYPE_NSEC) {
784 /* Check if we have an NSEC record instead for the name. */
785 i = hashmap_get(c->by_key, &DNS_RESOURCE_KEY_CONST(k->class, DNS_TYPE_NSEC, n));
786 if (i)
787 return i;
788 }
789
790 return NULL;
791 }
792
793 int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, bool clamp_ttl, int *rcode, DnsAnswer **ret, bool *authenticated) {
794 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
795 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
796 unsigned n = 0;
797 int r;
798 bool nxdomain = false;
799 DnsCacheItem *j, *first, *nsec = NULL;
800 bool have_authenticated = false, have_non_authenticated = false;
801 usec_t current;
802
803 assert(c);
804 assert(key);
805 assert(rcode);
806 assert(ret);
807 assert(authenticated);
808
809 if (key->type == DNS_TYPE_ANY || key->class == DNS_CLASS_ANY) {
810 /* If we have ANY lookups we don't use the cache, so
811 * that the caller refreshes via the network. */
812
813 log_debug("Ignoring cache for ANY lookup: %s",
814 dns_resource_key_to_string(key, key_str, sizeof key_str));
815
816 c->n_miss++;
817
818 *ret = NULL;
819 *rcode = DNS_RCODE_SUCCESS;
820 return 0;
821 }
822
823 first = dns_cache_get_by_key_follow_cname_dname_nsec(c, key);
824 if (!first) {
825 /* If one question cannot be answered we need to refresh */
826
827 log_debug("Cache miss for %s",
828 dns_resource_key_to_string(key, key_str, sizeof key_str));
829
830 c->n_miss++;
831
832 *ret = NULL;
833 *rcode = DNS_RCODE_SUCCESS;
834 return 0;
835 }
836
837 LIST_FOREACH(by_key, j, first) {
838 if (j->rr) {
839 if (j->rr->key->type == DNS_TYPE_NSEC)
840 nsec = j;
841
842 n++;
843 } else if (j->type == DNS_CACHE_NXDOMAIN)
844 nxdomain = true;
845
846 if (j->authenticated)
847 have_authenticated = true;
848 else
849 have_non_authenticated = true;
850 }
851
852 if (nsec && !IN_SET(key->type, DNS_TYPE_NSEC, DNS_TYPE_DS)) {
853 /* Note that we won't derive information for DS RRs from an NSEC, because we only cache NSEC RRs from
854 * the lower-zone of a zone cut, but the DS RRs are on the upper zone. */
855
856 log_debug("NSEC NODATA cache hit for %s",
857 dns_resource_key_to_string(key, key_str, sizeof key_str));
858
859 /* We only found an NSEC record that matches our name.
860 * If it says the type doesn't exist report
861 * NODATA. Otherwise report a cache miss. */
862
863 *ret = NULL;
864 *rcode = DNS_RCODE_SUCCESS;
865 *authenticated = nsec->authenticated;
866
867 if (!bitmap_isset(nsec->rr->nsec.types, key->type) &&
868 !bitmap_isset(nsec->rr->nsec.types, DNS_TYPE_CNAME) &&
869 !bitmap_isset(nsec->rr->nsec.types, DNS_TYPE_DNAME)) {
870 c->n_hit++;
871 return 1;
872 }
873
874 c->n_miss++;
875 return 0;
876 }
877
878 log_debug("%s cache hit for %s",
879 n > 0 ? "Positive" :
880 nxdomain ? "NXDOMAIN" : "NODATA",
881 dns_resource_key_to_string(key, key_str, sizeof key_str));
882
883 if (n <= 0) {
884 c->n_hit++;
885
886 *ret = NULL;
887 *rcode = nxdomain ? DNS_RCODE_NXDOMAIN : DNS_RCODE_SUCCESS;
888 *authenticated = have_authenticated && !have_non_authenticated;
889 return 1;
890 }
891
892 answer = dns_answer_new(n);
893 if (!answer)
894 return -ENOMEM;
895
896 if (clamp_ttl)
897 current = now(clock_boottime_or_monotonic());
898
899 LIST_FOREACH(by_key, j, first) {
900 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
901
902 if (!j->rr)
903 continue;
904
905 if (clamp_ttl) {
906 rr = dns_resource_record_ref(j->rr);
907
908 r = dns_resource_record_clamp_ttl(&rr, LESS_BY(j->until, current) / USEC_PER_SEC);
909 if (r < 0)
910 return r;
911 }
912
913 r = dns_answer_add(answer, rr ?: j->rr, j->ifindex, j->authenticated ? DNS_ANSWER_AUTHENTICATED : 0);
914 if (r < 0)
915 return r;
916 }
917
918 c->n_hit++;
919
920 *ret = answer;
921 *rcode = DNS_RCODE_SUCCESS;
922 *authenticated = have_authenticated && !have_non_authenticated;
923 answer = NULL;
924
925 return n;
926 }
927
928 int dns_cache_check_conflicts(DnsCache *cache, DnsResourceRecord *rr, int owner_family, const union in_addr_union *owner_address) {
929 DnsCacheItem *i, *first;
930 bool same_owner = true;
931
932 assert(cache);
933 assert(rr);
934
935 dns_cache_prune(cache);
936
937 /* See if there's a cache entry for the same key. If there
938 * isn't there's no conflict */
939 first = hashmap_get(cache->by_key, rr->key);
940 if (!first)
941 return 0;
942
943 /* See if the RR key is owned by the same owner, if so, there
944 * isn't a conflict either */
945 LIST_FOREACH(by_key, i, first) {
946 if (i->owner_family != owner_family ||
947 !in_addr_equal(owner_family, &i->owner_address, owner_address)) {
948 same_owner = false;
949 break;
950 }
951 }
952 if (same_owner)
953 return 0;
954
955 /* See if there's the exact same RR in the cache. If yes, then
956 * there's no conflict. */
957 if (dns_cache_get(cache, rr))
958 return 0;
959
960 /* There's a conflict */
961 return 1;
962 }
963
964 int dns_cache_export_shared_to_packet(DnsCache *cache, DnsPacket *p) {
965 unsigned ancount = 0;
966 Iterator iterator;
967 DnsCacheItem *i;
968 int r;
969
970 assert(cache);
971 assert(p);
972
973 HASHMAP_FOREACH(i, cache->by_key, iterator) {
974 DnsCacheItem *j;
975
976 LIST_FOREACH(by_key, j, i) {
977 if (!j->rr)
978 continue;
979
980 if (!j->shared_owner)
981 continue;
982
983 r = dns_packet_append_rr(p, j->rr, NULL, NULL);
984 if (r == -EMSGSIZE && p->protocol == DNS_PROTOCOL_MDNS) {
985 /* For mDNS, if we're unable to stuff all known answers into the given packet,
986 * allocate a new one, push the RR into that one and link it to the current one.
987 */
988
989 DNS_PACKET_HEADER(p)->ancount = htobe16(ancount);
990 ancount = 0;
991
992 r = dns_packet_new_query(&p->more, p->protocol, 0, true);
993 if (r < 0)
994 return r;
995
996 /* continue with new packet */
997 p = p->more;
998 r = dns_packet_append_rr(p, j->rr, NULL, NULL);
999 }
1000
1001 if (r < 0)
1002 return r;
1003
1004 ancount++;
1005 }
1006 }
1007
1008 DNS_PACKET_HEADER(p)->ancount = htobe16(ancount);
1009
1010 return 0;
1011 }
1012
1013 void dns_cache_dump(DnsCache *cache, FILE *f) {
1014 Iterator iterator;
1015 DnsCacheItem *i;
1016
1017 if (!cache)
1018 return;
1019
1020 if (!f)
1021 f = stdout;
1022
1023 HASHMAP_FOREACH(i, cache->by_key, iterator) {
1024 DnsCacheItem *j;
1025
1026 LIST_FOREACH(by_key, j, i) {
1027
1028 fputc('\t', f);
1029
1030 if (j->rr) {
1031 const char *t;
1032 t = dns_resource_record_to_string(j->rr);
1033 if (!t) {
1034 log_oom();
1035 continue;
1036 }
1037
1038 fputs(t, f);
1039 fputc('\n', f);
1040 } else {
1041 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
1042
1043 fputs(dns_resource_key_to_string(j->key, key_str, sizeof key_str), f);
1044 fputs(" -- ", f);
1045 fputs(j->type == DNS_CACHE_NODATA ? "NODATA" : "NXDOMAIN", f);
1046 fputc('\n', f);
1047 }
1048 }
1049 }
1050 }
1051
1052 bool dns_cache_is_empty(DnsCache *cache) {
1053 if (!cache)
1054 return true;
1055
1056 return hashmap_isempty(cache->by_key);
1057 }
1058
1059 unsigned dns_cache_size(DnsCache *cache) {
1060 if (!cache)
1061 return 0;
1062
1063 return hashmap_size(cache->by_key);
1064 }