]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/resolve/resolved-dns-cache.c
Use provided buffer in dns_resource_key_to_string
[thirdparty/systemd.git] / src / resolve / resolved-dns-cache.c
CommitLineData
322345fd
LP
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
202b76ae
ZJS
20#include <net/if.h>
21
22#include "af-list.h"
b5efdb8a 23#include "alloc-util.h"
58db254a 24#include "dns-domain.h"
02c2857b 25#include "resolved-dns-answer.h"
322345fd 26#include "resolved-dns-cache.h"
7e8e0422 27#include "resolved-dns-packet.h"
58db254a 28#include "string-util.h"
322345fd 29
6af47493
LP
30/* Never cache more than 4K entries. RFC 1536, Section 5 suggests to
31 * leave DNS caches unbounded, but that's crazy. */
d98e5504 32#define CACHE_MAX 4096
cbd4560e 33
d98e5504
LP
34/* We never keep any item longer than 2h in our cache */
35#define CACHE_TTL_MAX_USEC (2 * USEC_PER_HOUR)
322345fd 36
623a4c97
LP
37typedef enum DnsCacheItemType DnsCacheItemType;
38typedef struct DnsCacheItem DnsCacheItem;
39
40enum DnsCacheItemType {
41 DNS_CACHE_POSITIVE,
42 DNS_CACHE_NODATA,
43 DNS_CACHE_NXDOMAIN,
44};
45
46struct DnsCacheItem {
d2579eec 47 DnsCacheItemType type;
623a4c97
LP
48 DnsResourceKey *key;
49 DnsResourceRecord *rr;
d2579eec 50
623a4c97 51 usec_t until;
d2579eec
LP
52 bool authenticated:1;
53 bool shared_owner:1;
54
06d12754 55 int ifindex;
a4076574
LP
56 int owner_family;
57 union in_addr_union owner_address;
d2579eec
LP
58
59 unsigned prioq_idx;
623a4c97
LP
60 LIST_FIELDS(DnsCacheItem, by_key);
61};
62
322345fd
LP
63static void dns_cache_item_free(DnsCacheItem *i) {
64 if (!i)
65 return;
66
67 dns_resource_record_unref(i->rr);
7e8e0422 68 dns_resource_key_unref(i->key);
322345fd
LP
69 free(i);
70}
71
72DEFINE_TRIVIAL_CLEANUP_FUNC(DnsCacheItem*, dns_cache_item_free);
73
39963f11 74static void dns_cache_item_unlink_and_free(DnsCache *c, DnsCacheItem *i) {
322345fd
LP
75 DnsCacheItem *first;
76
77 assert(c);
78
79 if (!i)
80 return;
81
7e8e0422
LP
82 first = hashmap_get(c->by_key, i->key);
83 LIST_REMOVE(by_key, first, i);
322345fd
LP
84
85 if (first)
7e8e0422 86 assert_se(hashmap_replace(c->by_key, first->key, first) >= 0);
322345fd 87 else
7e8e0422 88 hashmap_remove(c->by_key, i->key);
322345fd 89
7e8e0422 90 prioq_remove(c->by_expiry, i, &i->prioq_idx);
322345fd
LP
91
92 dns_cache_item_free(i);
93}
94
f5bdeb01
LP
95static 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) {
39963f11 105 dns_cache_item_unlink_and_free(c, i);
f5bdeb01
LP
106 return true;
107 }
108 }
109
110 return false;
111}
112
2dda578f 113static bool dns_cache_remove_by_key(DnsCache *c, DnsResourceKey *key) {
1f97052f 114 DnsCacheItem *first, *i, *n;
322345fd
LP
115
116 assert(c);
117 assert(key);
118
1f97052f
LP
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);
6b34a6c9
TG
126 }
127
1f97052f 128 return true;
322345fd
LP
129}
130
ef9a3e3c
LP
131void dns_cache_flush(DnsCache *c) {
132 DnsResourceKey *key;
133
134 assert(c);
135
136 while ((key = hashmap_first_key(c->by_key)))
2dda578f 137 dns_cache_remove_by_key(c, key);
ef9a3e3c
LP
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
322345fd
LP
146static 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 (;;) {
faa133f3 158 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
322345fd
LP
159 DnsCacheItem *i;
160
7e8e0422 161 if (prioq_size(c->by_expiry) <= 0)
322345fd
LP
162 break;
163
7e8e0422 164 if (prioq_size(c->by_expiry) + add < CACHE_MAX)
322345fd
LP
165 break;
166
7e8e0422 167 i = prioq_peek(c->by_expiry);
cbd4560e
LP
168 assert(i);
169
faa133f3 170 /* Take an extra reference to the key so that it
cbd4560e 171 * doesn't go away in the middle of the remove call */
7e8e0422 172 key = dns_resource_key_ref(i->key);
2dda578f 173 dns_cache_remove_by_key(c, key);
322345fd
LP
174 }
175}
176
177void 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;
202b76ae 186 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
322345fd 187
7e8e0422 188 i = prioq_peek(c->by_expiry);
322345fd
LP
189 if (!i)
190 break;
191
322345fd 192 if (t <= 0)
240b589b 193 t = now(clock_boottime_or_monotonic());
322345fd 194
7e8e0422 195 if (i->until > t)
322345fd
LP
196 break;
197
d2579eec 198 /* Depending whether this is an mDNS shared entry
202b76ae
ZJS
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
d2579eec 205 if (i->shared_owner)
39963f11 206 dns_cache_item_unlink_and_free(c, i);
d2579eec
LP
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);
2dda578f 213 dns_cache_remove_by_key(c, key);
d2579eec 214 }
322345fd
LP
215 }
216}
217
218static int dns_cache_item_prioq_compare_func(const void *a, const void *b) {
322345fd
LP
219 const DnsCacheItem *x = a, *y = b;
220
7e8e0422 221 if (x->until < y->until)
322345fd 222 return -1;
7e8e0422 223 if (x->until > y->until)
322345fd
LP
224 return 1;
225 return 0;
226}
227
623a4c97 228static int dns_cache_init(DnsCache *c) {
7e8e0422
LP
229 int r;
230
623a4c97
LP
231 assert(c);
232
7e8e0422
LP
233 r = prioq_ensure_allocated(&c->by_expiry, dns_cache_item_prioq_compare_func);
234 if (r < 0)
235 return r;
236
d5099efc 237 r = hashmap_ensure_allocated(&c->by_key, &dns_resource_key_hash_ops);
7e8e0422
LP
238 if (r < 0)
239 return r;
240
241 return r;
242}
243
244static int dns_cache_link_item(DnsCache *c, DnsCacheItem *i) {
245 DnsCacheItem *first;
246 int r;
247
322345fd
LP
248 assert(c);
249 assert(i);
322345fd 250
7e8e0422
LP
251 r = prioq_put(c->by_expiry, i, &i->prioq_idx);
252 if (r < 0)
253 return r;
322345fd 254
7e8e0422
LP
255 first = hashmap_get(c->by_key, i->key);
256 if (first) {
f57e3cd5
LP
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
7e8e0422
LP
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 }
322345fd
LP
278 }
279
7e8e0422 280 return 0;
322345fd
LP
281}
282
faa133f3
LP
283static DnsCacheItem* dns_cache_get(DnsCache *c, DnsResourceRecord *rr) {
284 DnsCacheItem *i;
285
286 assert(c);
287 assert(rr);
288
7e8e0422 289 LIST_FOREACH(by_key, i, hashmap_get(c->by_key, rr->key))
3ef77d04 290 if (i->rr && dns_resource_record_equal(i->rr, rr) > 0)
faa133f3
LP
291 return i;
292
293 return NULL;
294}
295
d3760be0 296static usec_t calculate_until(DnsResourceRecord *rr, uint32_t nsec_ttl, usec_t timestamp, bool use_soa_minimum) {
b211dc7e
LP
297 uint32_t ttl;
298 usec_t u;
ee3d6aff
LP
299
300 assert(rr);
301
d3760be0 302 ttl = MIN(rr->ttl, nsec_ttl);
b211dc7e
LP
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. */
ee3d6aff 309
b211dc7e
LP
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;
ee3d6aff
LP
317
318 if (rr->expiry != USEC_INFINITY) {
319 usec_t left;
320
b211dc7e
LP
321 /* Make use of the DNSSEC RRSIG expiry info, if we
322 * have it */
ee3d6aff
LP
323
324 left = LESS_BY(rr->expiry, now(CLOCK_REALTIME));
b211dc7e
LP
325 if (u > left)
326 u = left;
ee3d6aff
LP
327 }
328
b211dc7e 329 return timestamp + u;
ee3d6aff
LP
330}
331
d2579eec
LP
332static 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,
06d12754 339 int ifindex,
d2579eec
LP
340 int owner_family,
341 const union in_addr_union *owner_address) {
342
7e8e0422
LP
343 assert(c);
344 assert(i);
345 assert(rr);
d2579eec 346 assert(owner_address);
7e8e0422
LP
347
348 i->type = DNS_CACHE_POSITIVE;
349
ece174c5 350 if (!i->by_key_prev)
7e8e0422
LP
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);
7e8e0422
LP
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
d3760be0 363 i->until = calculate_until(rr, (uint32_t) -1, timestamp, false);
d2579eec
LP
364 i->authenticated = authenticated;
365 i->shared_owner = shared_owner;
366
06d12754
LP
367 i->ifindex = ifindex;
368
d2579eec
LP
369 i->owner_family = owner_family;
370 i->owner_address = *owner_address;
7e8e0422
LP
371
372 prioq_reshuffle(c->by_expiry, i, &i->prioq_idx);
373}
374
a4076574
LP
375static int dns_cache_put_positive(
376 DnsCache *c,
377 DnsResourceRecord *rr,
931851e8 378 bool authenticated,
d2579eec 379 bool shared_owner,
a4076574 380 usec_t timestamp,
06d12754 381 int ifindex,
a4076574
LP
382 int owner_family,
383 const union in_addr_union *owner_address) {
384
322345fd 385 _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
7e8e0422 386 DnsCacheItem *existing;
202b76ae 387 char key_str[DNS_RESOURCE_KEY_STRING_MAX], ifname[IF_NAMESIZE];
a257f9d4 388 int r, k;
322345fd
LP
389
390 assert(c);
391 assert(rr);
a4076574 392 assert(owner_address);
322345fd 393
222148b6
LP
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
f5bdeb01 400 /* New TTL is 0? Delete this specific entry... */
322345fd 401 if (rr->ttl <= 0) {
f5bdeb01 402 k = dns_cache_remove_by_rr(c, rr);
202b76ae
ZJS
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(i->key, key_str, sizeof key_str));
322345fd
LP
406 return 0;
407 }
408
d2579eec 409 /* Entry exists already? Update TTL, timestamp and owner*/
322345fd
LP
410 existing = dns_cache_get(c, rr);
411 if (existing) {
d2579eec
LP
412 dns_cache_item_update_positive(
413 c,
414 existing,
415 rr,
416 authenticated,
417 shared_owner,
418 timestamp,
06d12754 419 ifindex,
d2579eec
LP
420 owner_family,
421 owner_address);
322345fd
LP
422 return 0;
423 }
424
425 /* Otherwise, add the new RR */
623a4c97 426 r = dns_cache_init(c);
322345fd
LP
427 if (r < 0)
428 return r;
429
7e8e0422
LP
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);
d3760be0 439 i->until = calculate_until(rr, (uint32_t) -1, timestamp, false);
d2579eec
LP
440 i->authenticated = authenticated;
441 i->shared_owner = shared_owner;
06d12754 442 i->ifindex = ifindex;
a4076574
LP
443 i->owner_family = owner_family;
444 i->owner_address = *owner_address;
d2579eec 445 i->prioq_idx = PRIOQ_IDX_NULL;
7e8e0422
LP
446
447 r = dns_cache_link_item(c, i);
448 if (r < 0)
449 return r;
450
a257f9d4 451 if (log_get_max_level() >= LOG_DEBUG) {
202b76ae
ZJS
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));
a257f9d4 464 }
6b34a6c9 465
7e8e0422
LP
466 i = NULL;
467 return 0;
468}
469
a4076574
LP
470static int dns_cache_put_negative(
471 DnsCache *c,
472 DnsResourceKey *key,
473 int rcode,
931851e8 474 bool authenticated,
d3760be0 475 uint32_t nsec_ttl,
a4076574 476 usec_t timestamp,
b211dc7e 477 DnsResourceRecord *soa,
a4076574
LP
478 int owner_family,
479 const union in_addr_union *owner_address) {
480
7e8e0422 481 _cleanup_(dns_cache_item_freep) DnsCacheItem *i = NULL;
202b76ae 482 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
7e8e0422
LP
483 int r;
484
485 assert(c);
486 assert(key);
b211dc7e 487 assert(soa);
a4076574 488 assert(owner_address);
7e8e0422 489
98b6be77
LP
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 */
222148b6 493 if (dns_class_is_pseudo(key->class))
ddf16339 494 return 0;
c33be4a6 495 if (dns_type_is_pseudo(key->type))
ddf16339 496 return 0;
222148b6 497
d3760be0 498 if (nsec_ttl <= 0 || soa->soa.minimum <= 0 || soa->ttl <= 0) {
202b76ae
ZJS
499 log_debug("Not caching negative entry with zero SOA/NSEC/NSEC3 TTL: %s",
500 dns_resource_key_to_string(i->key, key_str, sizeof key_str));
95dd6257 501 return 0;
6b34a6c9 502 }
ddf16339 503
7e8e0422
LP
504 if (!IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
505 return 0;
506
623a4c97 507 r = dns_cache_init(c);
322345fd
LP
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
7e8e0422 517 i->type = rcode == DNS_RCODE_SUCCESS ? DNS_CACHE_NODATA : DNS_CACHE_NXDOMAIN;
d3760be0 518 i->until = calculate_until(soa, nsec_ttl, timestamp, true);
d2579eec 519 i->authenticated = authenticated;
a4076574
LP
520 i->owner_family = owner_family;
521 i->owner_address = *owner_address;
d2579eec 522 i->prioq_idx = PRIOQ_IDX_NULL;
322345fd 523
71e13669
TG
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. */
1c02e7ba 527 i->key = dns_resource_key_new(key->class, DNS_TYPE_ANY, dns_resource_key_name(key));
71e13669
TG
528 if (!i->key)
529 return -ENOMEM;
a5444ca9
LP
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);
71e13669
TG
538 } else
539 i->key = dns_resource_key_ref(key);
540
7e8e0422 541 r = dns_cache_link_item(c, i);
322345fd
LP
542 if (r < 0)
543 return r;
544
202b76ae
ZJS
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);
6b34a6c9 549
322345fd 550 i = NULL;
322345fd
LP
551 return 0;
552}
553
d2579eec
LP
554static 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)
2dda578f 568 dns_cache_remove_by_key(c, key);
d2579eec
LP
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
2dda578f 580 dns_cache_remove_by_key(c, rr->key);
d2579eec
LP
581 }
582}
583
f6618dcd
LP
584static 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
a4076574
LP
606int dns_cache_put(
607 DnsCache *c,
8e427d9b 608 DnsResourceKey *key,
a4076574
LP
609 int rcode,
610 DnsAnswer *answer,
931851e8 611 bool authenticated,
d3760be0 612 uint32_t nsec_ttl,
a4076574
LP
613 usec_t timestamp,
614 int owner_family,
615 const union in_addr_union *owner_address) {
616
02c2857b 617 DnsResourceRecord *soa = NULL, *rr;
105e1512
LP
618 DnsAnswerFlags flags;
619 unsigned cache_keys;
06d12754 620 int r, ifindex;
322345fd
LP
621
622 assert(c);
d2579eec 623 assert(owner_address);
322345fd 624
d2579eec 625 dns_cache_remove_previous(c, key, answer);
0ec7c46e 626
ea207b63 627 if (dns_answer_size(answer) <= 0) {
202b76ae 628 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
c3cb6dc2 629
202b76ae
ZJS
630 log_debug("Not caching negative entry without a SOA record: %s",
631 dns_resource_key_to_string(key, key_str, sizeof key_str));
0ec7c46e 632 return 0;
c3cb6dc2 633 }
0ec7c46e 634
7e8e0422
LP
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 */
7e8e0422
LP
638 if (!IN_SET(rcode, DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
639 return 0;
640
ea207b63 641 cache_keys = dns_answer_size(answer);
8e427d9b
TG
642 if (key)
643 cache_keys ++;
eff91ee0 644
7e8e0422 645 /* Make some space for our new entries */
eff91ee0 646 dns_cache_make_space(c, cache_keys);
322345fd 647
7e8e0422 648 if (timestamp <= 0)
240b589b 649 timestamp = now(clock_boottime_or_monotonic());
322345fd 650
7e8e0422 651 /* Second, add in positive entries for all contained RRs */
06d12754 652 DNS_ANSWER_FOREACH_FULL(rr, ifindex, flags, answer) {
105e1512
LP
653 if ((flags & DNS_ANSWER_CACHEABLE) == 0)
654 continue;
655
f6618dcd
LP
656 r = rr_eligible(rr);
657 if (r < 0)
658 return r;
659 if (r == 0)
660 continue;
661
d2579eec
LP
662 r = dns_cache_put_positive(
663 c,
664 rr,
665 flags & DNS_ANSWER_AUTHENTICATED,
666 flags & DNS_ANSWER_SHARED_OWNER,
667 timestamp,
06d12754 668 ifindex,
d2579eec 669 owner_family, owner_address);
7e8e0422
LP
670 if (r < 0)
671 goto fail;
672 }
673
d2579eec 674 if (!key) /* mDNS doesn't know negative caching, really */
eff91ee0
DM
675 return 0;
676
8e427d9b 677 /* Third, add in negative entries if the key has no RR */
105e1512 678 r = dns_answer_match_key(answer, key, NULL);
8e427d9b
TG
679 if (r < 0)
680 goto fail;
681 if (r > 0)
682 return 0;
7e8e0422 683
5d27351f
TG
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) */
105e1512 687 r = dns_answer_find_cname_or_dname(answer, key, NULL, NULL);
5d27351f
TG
688 if (r < 0)
689 goto fail;
690 if (r > 0)
691 return 0;
692
547973de
LP
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. */
fd009cd8 696 r = dns_answer_find_soa(answer, key, &soa, &flags);
8e427d9b
TG
697 if (r < 0)
698 goto fail;
699 if (r == 0)
700 return 0;
7e8e0422 701
fd009cd8
LP
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
d2579eec
LP
707 r = dns_cache_put_negative(
708 c,
709 key,
710 rcode,
711 authenticated,
d3760be0 712 nsec_ttl,
d2579eec 713 timestamp,
b211dc7e 714 soa,
d2579eec 715 owner_family, owner_address);
8e427d9b
TG
716 if (r < 0)
717 goto fail;
322345fd
LP
718
719 return 0;
720
721fail:
722 /* Adding all RRs failed. Let's clean up what we already
723 * added, just in case */
724
8e427d9b 725 if (key)
2dda578f 726 dns_cache_remove_by_key(c, key);
eff91ee0 727
105e1512
LP
728 DNS_ANSWER_FOREACH_FLAGS(rr, flags, answer) {
729 if ((flags & DNS_ANSWER_CACHEABLE) == 0)
730 continue;
731
2dda578f 732 dns_cache_remove_by_key(c, rr->key);
105e1512 733 }
322345fd
LP
734
735 return r;
736}
737
37da8931 738static DnsCacheItem *dns_cache_get_by_key_follow_cname_dname_nsec(DnsCache *c, DnsResourceKey *k) {
58db254a
LP
739 DnsCacheItem *i;
740 const char *n;
741 int r;
5643c00a
TG
742
743 assert(c);
744 assert(k);
745
58db254a
LP
746 /* If we hit some OOM error, or suchlike, we don't care too
747 * much, after all this is just a cache */
748
5643c00a 749 i = hashmap_get(c->by_key, k);
d7ce6c94 750 if (i)
37da8931
LP
751 return i;
752
1c02e7ba 753 n = dns_resource_key_name(k);
37da8931 754
71e13669
TG
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
d3c7e913 761 if (dns_type_may_redirect(k->type)) {
d7ce6c94
TG
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;
5643c00a 766
d7ce6c94
TG
767 /* OK, let's look for cached DNAME records. */
768 for (;;) {
d7ce6c94
TG
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;
58db254a 775
d7ce6c94 776 /* Jump one label ahead */
950b692b 777 r = dns_name_parent(&n);
d7ce6c94
TG
778 if (r <= 0)
779 return NULL;
780 }
781 }
5643c00a 782
950b692b 783 if (k->type != DNS_TYPE_NSEC) {
d7ce6c94
TG
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));
58db254a
LP
786 if (i)
787 return i;
58db254a
LP
788 }
789
790 return NULL;
5643c00a
TG
791}
792
931851e8 793int dns_cache_lookup(DnsCache *c, DnsResourceKey *key, int *rcode, DnsAnswer **ret, bool *authenticated) {
faa133f3 794 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
202b76ae 795 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
f52e61da 796 unsigned n = 0;
322345fd 797 int r;
7e8e0422 798 bool nxdomain = false;
931851e8
LP
799 DnsCacheItem *j, *first, *nsec = NULL;
800 bool have_authenticated = false, have_non_authenticated = false;
322345fd
LP
801
802 assert(c);
f52e61da 803 assert(key);
623a4c97 804 assert(rcode);
faa133f3 805 assert(ret);
931851e8 806 assert(authenticated);
322345fd 807
202b76ae 808 if (key->type == DNS_TYPE_ANY || key->class == DNS_CLASS_ANY) {
931851e8
LP
809 /* If we have ANY lookups we don't use the cache, so
810 * that the caller refreshes via the network. */
322345fd 811
202b76ae
ZJS
812 log_debug("Ignoring cache for ANY lookup: %s",
813 dns_resource_key_to_string(key, key_str, sizeof key_str));
6b34a6c9 814
a150ff5e
LP
815 c->n_miss++;
816
f52e61da
LP
817 *ret = NULL;
818 *rcode = DNS_RCODE_SUCCESS;
819 return 0;
820 }
6b34a6c9 821
37da8931 822 first = dns_cache_get_by_key_follow_cname_dname_nsec(c, key);
f52e61da
LP
823 if (!first) {
824 /* If one question cannot be answered we need to refresh */
ddf16339 825
202b76ae
ZJS
826 log_debug("Cache miss for %s",
827 dns_resource_key_to_string(key, key_str, sizeof key_str));
6b34a6c9 828
a150ff5e
LP
829 c->n_miss++;
830
f52e61da
LP
831 *ret = NULL;
832 *rcode = DNS_RCODE_SUCCESS;
833 return 0;
834 }
6b34a6c9 835
f52e61da 836 LIST_FOREACH(by_key, j, first) {
37da8931
LP
837 if (j->rr) {
838 if (j->rr->key->type == DNS_TYPE_NSEC)
931851e8
LP
839 nsec = j;
840
f52e61da 841 n++;
37da8931 842 } else if (j->type == DNS_CACHE_NXDOMAIN)
f52e61da 843 nxdomain = true;
931851e8
LP
844
845 if (j->authenticated)
846 have_authenticated = true;
847 else
848 have_non_authenticated = true;
f52e61da 849 }
6b34a6c9 850
f6618dcd
LP
851 if (nsec && !IN_SET(key->type, DNS_TYPE_NSEC, DNS_TYPE_DS)) {
852 /* Note that we won't derive information for DS RRs from an NSEC, because we only cache NSEC RRs from
853 * the lower-zone of a zone cut, but the DS RRs are on the upper zone. */
854
202b76ae
ZJS
855 log_debug("NSEC NODATA cache hit for %s",
856 dns_resource_key_to_string(key, key_str, sizeof key_str));
37da8931
LP
857
858 /* We only found an NSEC record that matches our name.
a257f9d4 859 * If it says the type doesn't exist report
37da8931
LP
860 * NODATA. Otherwise report a cache miss. */
861
862 *ret = NULL;
863 *rcode = DNS_RCODE_SUCCESS;
931851e8 864 *authenticated = nsec->authenticated;
37da8931 865
a150ff5e
LP
866 if (!bitmap_isset(nsec->rr->nsec.types, key->type) &&
867 !bitmap_isset(nsec->rr->nsec.types, DNS_TYPE_CNAME) &&
868 !bitmap_isset(nsec->rr->nsec.types, DNS_TYPE_DNAME)) {
869 c->n_hit++;
870 return 1;
871 }
872
873 c->n_miss++;
874 return 0;
37da8931
LP
875 }
876
202b76ae
ZJS
877 log_debug("%s cache hit for %s",
878 n > 0 ? "Positive" :
879 nxdomain ? "NXDOMAIN" : "NODATA",
880 dns_resource_key_to_string(key, key_str, sizeof key_str));
faa133f3 881
7e8e0422 882 if (n <= 0) {
a150ff5e
LP
883 c->n_hit++;
884
7e8e0422
LP
885 *ret = NULL;
886 *rcode = nxdomain ? DNS_RCODE_NXDOMAIN : DNS_RCODE_SUCCESS;
931851e8 887 *authenticated = have_authenticated && !have_non_authenticated;
7e8e0422
LP
888 return 1;
889 }
faa133f3
LP
890
891 answer = dns_answer_new(n);
892 if (!answer)
893 return -ENOMEM;
322345fd 894
f52e61da
LP
895 LIST_FOREACH(by_key, j, first) {
896 if (!j->rr)
897 continue;
898
06d12754 899 r = dns_answer_add(answer, j->rr, j->ifindex, j->authenticated ? DNS_ANSWER_AUTHENTICATED : 0);
f52e61da
LP
900 if (r < 0)
901 return r;
322345fd
LP
902 }
903
a150ff5e
LP
904 c->n_hit++;
905
faa133f3 906 *ret = answer;
7e8e0422 907 *rcode = DNS_RCODE_SUCCESS;
931851e8 908 *authenticated = have_authenticated && !have_non_authenticated;
faa133f3
LP
909 answer = NULL;
910
911 return n;
322345fd 912}
a4076574
LP
913
914int dns_cache_check_conflicts(DnsCache *cache, DnsResourceRecord *rr, int owner_family, const union in_addr_union *owner_address) {
915 DnsCacheItem *i, *first;
916 bool same_owner = true;
917
918 assert(cache);
919 assert(rr);
920
921 dns_cache_prune(cache);
922
923 /* See if there's a cache entry for the same key. If there
924 * isn't there's no conflict */
925 first = hashmap_get(cache->by_key, rr->key);
926 if (!first)
927 return 0;
928
929 /* See if the RR key is owned by the same owner, if so, there
930 * isn't a conflict either */
931 LIST_FOREACH(by_key, i, first) {
932 if (i->owner_family != owner_family ||
933 !in_addr_equal(owner_family, &i->owner_address, owner_address)) {
934 same_owner = false;
935 break;
936 }
937 }
938 if (same_owner)
939 return 0;
940
941 /* See if there's the exact same RR in the cache. If yes, then
942 * there's no conflict. */
943 if (dns_cache_get(cache, rr))
944 return 0;
945
946 /* There's a conflict */
947 return 1;
948}
4d506d6b 949
7778dfff
DM
950int dns_cache_export_shared_to_packet(DnsCache *cache, DnsPacket *p) {
951 unsigned ancount = 0;
952 Iterator iterator;
953 DnsCacheItem *i;
954 int r;
955
956 assert(cache);
261f3673 957 assert(p);
7778dfff
DM
958
959 HASHMAP_FOREACH(i, cache->by_key, iterator) {
960 DnsCacheItem *j;
961
962 LIST_FOREACH(by_key, j, i) {
7778dfff
DM
963 if (!j->rr)
964 continue;
965
d2579eec 966 if (!j->shared_owner)
7778dfff
DM
967 continue;
968
969 r = dns_packet_append_rr(p, j->rr, NULL, NULL);
261f3673
DM
970 if (r == -EMSGSIZE && p->protocol == DNS_PROTOCOL_MDNS) {
971 /* For mDNS, if we're unable to stuff all known answers into the given packet,
972 * allocate a new one, push the RR into that one and link it to the current one.
973 */
974
975 DNS_PACKET_HEADER(p)->ancount = htobe16(ancount);
976 ancount = 0;
977
978 r = dns_packet_new_query(&p->more, p->protocol, 0, true);
979 if (r < 0)
980 return r;
981
982 /* continue with new packet */
983 p = p->more;
984 r = dns_packet_append_rr(p, j->rr, NULL, NULL);
985 }
986
7778dfff
DM
987 if (r < 0)
988 return r;
989
990 ancount ++;
991 }
992 }
993
994 DNS_PACKET_HEADER(p)->ancount = htobe16(ancount);
995
996 return 0;
997}
998
4d506d6b
LP
999void dns_cache_dump(DnsCache *cache, FILE *f) {
1000 Iterator iterator;
1001 DnsCacheItem *i;
4d506d6b
LP
1002
1003 if (!cache)
1004 return;
1005
1006 if (!f)
1007 f = stdout;
1008
1009 HASHMAP_FOREACH(i, cache->by_key, iterator) {
1010 DnsCacheItem *j;
1011
1012 LIST_FOREACH(by_key, j, i) {
4d506d6b
LP
1013
1014 fputc('\t', f);
1015
1016 if (j->rr) {
7b50eb2e
LP
1017 const char *t;
1018 t = dns_resource_record_to_string(j->rr);
1019 if (!t) {
4d506d6b
LP
1020 log_oom();
1021 continue;
1022 }
1023
1024 fputs(t, f);
1025 fputc('\n', f);
1026 } else {
202b76ae 1027 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
4d506d6b 1028
202b76ae 1029 fputs(dns_resource_key_to_string(j->key, key_str, sizeof key_str), f);
4d506d6b
LP
1030 fputs(" -- ", f);
1031 fputs(j->type == DNS_CACHE_NODATA ? "NODATA" : "NXDOMAIN", f);
1032 fputc('\n', f);
1033 }
1034 }
1035 }
1036}
1037
1038bool dns_cache_is_empty(DnsCache *cache) {
1039 if (!cache)
1040 return true;
1041
1042 return hashmap_isempty(cache->by_key);
1043}
a150ff5e
LP
1044
1045unsigned dns_cache_size(DnsCache *cache) {
1046 if (!cache)
1047 return 0;
1048
1049 return hashmap_size(cache->by_key);
1050}