2 * services/cache/dns.c - Cache services for DNS using msg and rrset caches.
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 * This file contains the DNS cache.
42 #include "iterator/iter_delegpt.h"
43 #include "iterator/iter_utils.h"
44 #include "validator/val_nsec.h"
45 #include "validator/val_utils.h"
46 #include "services/cache/dns.h"
47 #include "services/cache/rrset.h"
48 #include "util/data/msgparse.h"
49 #include "util/data/msgreply.h"
50 #include "util/data/packed_rrset.h"
51 #include "util/data/dname.h"
52 #include "util/module.h"
53 #include "util/net_help.h"
54 #include "util/regional.h"
55 #include "util/config_file.h"
56 #include "sldns/sbuffer.h"
58 /** store rrsets in the rrset cache.
59 * @param env: module environment with caches.
60 * @param rep: contains list of rrsets to store.
61 * @param now: current time.
62 * @param leeway: during prefetch how much leeway to update TTLs.
63 * This makes rrsets (other than type NS) timeout sooner so they get
64 * updated with a new full TTL.
65 * Type NS does not get this, because it must not be refreshed from the
66 * child domain, but keep counting down properly.
67 * @param pside: if from parentside discovered NS, so that its NS is okay
68 * in a prefetch situation to be updated (without becoming sticky).
69 * @param qrep: update rrsets here if cache is better
70 * @param region: for qrep allocs.
71 * @param qstarttime: time when delegations were looked up, this is perhaps
72 * earlier than the time in now. The time is used to determine if RRsets
73 * of type NS have expired, so that they can only be updated using
74 * lookups of delegation points that did not use them, since they had
78 store_rrsets(struct module_env* env, struct reply_info* rep, time_t now,
79 time_t leeway, int pside, struct reply_info* qrep,
80 struct regional* region, time_t qstarttime)
83 /* see if rrset already exists in cache, if not insert it. */
84 for(i=0; i<rep->rrset_count; i++) {
85 rep->ref[i].key = rep->rrsets[i];
86 rep->ref[i].id = rep->rrsets[i]->id;
87 /* update ref if it was in the cache */
88 switch(rrset_cache_update(env->rrset_cache, &rep->ref[i],
89 env->alloc, ((ntohs(rep->ref[i].key->rk.type)==
90 LDNS_RR_TYPE_NS && !pside)?qstarttime:now + leeway))) {
91 case 0: /* ref unchanged, item inserted */
93 case 2: /* ref updated, cache is superior */
95 struct ub_packed_rrset_key* ck;
96 lock_rw_rdlock(&rep->ref[i].key->entry.lock);
97 /* if deleted rrset, do not copy it */
98 if(rep->ref[i].key->id == 0)
100 else ck = packed_rrset_copy_region(
101 rep->ref[i].key, region, now);
102 lock_rw_unlock(&rep->ref[i].key->entry.lock);
104 /* use cached copy if memory allows */
105 qrep->rrsets[i] = ck;
108 /* no break: also copy key item */
109 /* the line below is matched by gcc regex and silences
110 * the fallthrough warning */
112 case 1: /* ref updated, item inserted */
113 rep->rrsets[i] = rep->ref[i].key;
118 /** delete message from message cache */
120 msg_cache_remove(struct module_env* env, uint8_t* qname, size_t qnamelen,
121 uint16_t qtype, uint16_t qclass, uint16_t flags)
127 k.qname_len = qnamelen;
130 k.local_alias = NULL;
131 h = query_info_hash(&k, flags);
132 slabhash_remove(env->msg_cache, h, &k);
136 dns_cache_store_msg(struct module_env* env, struct query_info* qinfo,
137 hashvalue_type hash, struct reply_info* rep, time_t leeway, int pside,
138 struct reply_info* qrep, uint32_t flags, struct regional* region,
141 struct msgreply_entry* e;
142 time_t ttl = rep->ttl;
146 for(i=0; i<rep->rrset_count; i++) {
147 rep->ref[i].key = rep->rrsets[i];
148 rep->ref[i].id = rep->rrsets[i]->id;
151 /* there was a reply_info_sortref(rep) here but it seems to be
152 * unnecessary, because the cache gets locked per rrset. */
153 reply_info_set_ttls(rep, *env->now);
154 store_rrsets(env, rep, *env->now, leeway, pside, qrep, region,
156 if(ttl == 0 && !(flags & DNSCACHE_STORE_ZEROTTL)) {
157 /* we do not store the message, but we did store the RRs,
158 * which could be useful for delegation information */
159 verbose(VERB_ALGO, "TTL 0: dropped msg from cache");
160 reply_info_delete(rep, NULL);
161 /* if the message is in the cache, remove that msg,
162 * so that the TTL 0 response can be returned for future
163 * responses (i.e. don't get answered from
164 * cache, but instead go to recursion to get this TTL0
166 * Possible messages that could be in the cache:
170 * - an older record that is expired
171 * - an older record that did not yet expire */
172 msg_cache_remove(env, qinfo->qname, qinfo->qname_len,
173 qinfo->qtype, qinfo->qclass, flags);
177 /* store msg in the cache */
178 reply_info_sortref(rep);
179 if(!(e = query_info_entrysetup(qinfo, rep, hash))) {
180 log_err("store_msg: malloc failed");
183 slabhash_insert(env->msg_cache, hash, &e->entry, rep, env->alloc);
186 /** see if an rrset is expired above the qname, return upper qname. */
188 rrset_expired_above(struct module_env* env, uint8_t** qname, size_t* qnamelen,
189 uint16_t searchtype, uint16_t qclass, time_t now, uint8_t* expiretop,
192 struct ub_packed_rrset_key *rrset;
195 while(*qnamelen > 0) {
196 /* look one label higher */
198 *qname += lablen + 1;
199 *qnamelen -= lablen + 1;
203 /* looks up with a time of 0, to see expired entries */
204 if((rrset = rrset_cache_lookup(env->rrset_cache, *qname,
205 *qnamelen, searchtype, qclass, 0, 0, 0))) {
206 struct packed_rrset_data* data =
207 (struct packed_rrset_data*)rrset->entry.data;
208 if(now > data->ttl) {
209 /* it is expired, this is not wanted */
210 lock_rw_unlock(&rrset->entry.lock);
211 log_nametypeclass(VERB_ALGO, "this rrset is expired", *qname, searchtype, qclass);
214 /* it is not expired, continue looking */
215 lock_rw_unlock(&rrset->entry.lock);
218 /* do not look above the expiretop. */
219 if(expiretop && *qnamelen == expiretoplen &&
220 query_dname_compare(*qname, expiretop)==0)
226 /** find closest NS or DNAME and returns the rrset (locked) */
227 static struct ub_packed_rrset_key*
228 find_closest_of_type(struct module_env* env, uint8_t* qname, size_t qnamelen,
229 uint16_t qclass, time_t now, uint16_t searchtype, int stripfront,
230 int noexpiredabove, uint8_t* expiretop, size_t expiretoplen)
232 struct ub_packed_rrset_key *rrset;
236 /* strip off so that DNAMEs have strict subdomain match */
239 qnamelen -= lablen + 1;
242 /* snip off front part of qname until the type is found */
243 while(qnamelen > 0) {
244 if((rrset = rrset_cache_lookup(env->rrset_cache, qname,
245 qnamelen, searchtype, qclass, 0, now, 0))) {
246 uint8_t* origqname = qname;
247 size_t origqnamelen = qnamelen;
250 /* if expiretop set, do not look above it, but
251 * qname is equal, so the just found result is also
252 * the nonexpired above part. */
253 if(expiretop && qnamelen == expiretoplen &&
254 query_dname_compare(qname, expiretop)==0)
256 /* check for expiry, but we have to let go of the rrset
257 * for the lock ordering */
258 lock_rw_unlock(&rrset->entry.lock);
259 /* the expired_above function always takes off one
260 * label (if qnamelen>0) and returns the final qname
261 * where it searched, so we can continue from there
262 * turning the O N*N search into O N. */
263 if(!rrset_expired_above(env, &qname, &qnamelen,
264 searchtype, qclass, now, expiretop,
266 /* we want to return rrset, but it may be
267 * gone from cache, if so, just loop like
268 * it was not in the cache in the first place.
270 if((rrset = rrset_cache_lookup(env->
271 rrset_cache, origqname, origqnamelen,
272 searchtype, qclass, 0, now, 0))) {
276 log_nametypeclass(VERB_ALGO, "ignoring rrset because expired rrsets exist above it", origqname, searchtype, qclass);
280 /* snip off front label */
283 qnamelen -= lablen + 1;
288 /** add addr to additional section */
290 addr_to_additional(struct ub_packed_rrset_key* rrset, struct regional* region,
291 struct dns_msg* msg, time_t now)
293 if((msg->rep->rrsets[msg->rep->rrset_count] =
294 packed_rrset_copy_region(rrset, region, now))) {
295 msg->rep->ar_numrrsets++;
296 msg->rep->rrset_count++;
300 /** lookup message in message cache */
301 struct msgreply_entry*
302 msg_cache_lookup(struct module_env* env, uint8_t* qname, size_t qnamelen,
303 uint16_t qtype, uint16_t qclass, uint16_t flags, time_t now, int wr)
305 struct lruhash_entry* e;
310 k.qname_len = qnamelen;
313 k.local_alias = NULL;
314 h = query_info_hash(&k, flags);
315 e = slabhash_lookup(env->msg_cache, h, &k, wr);
318 if( now > ((struct reply_info*)e->data)->ttl ) {
319 lock_rw_unlock(&e->lock);
322 return (struct msgreply_entry*)e->key;
325 /** find and add A and AAAA records for nameservers in delegpt */
327 find_add_addrs(struct module_env* env, uint16_t qclass,
328 struct regional* region, struct delegpt* dp, time_t now,
329 struct dns_msg** msg)
331 struct delegpt_ns* ns;
332 struct msgreply_entry* neg;
333 struct ub_packed_rrset_key* akey;
334 for(ns = dp->nslist; ns; ns = ns->next) {
335 akey = rrset_cache_lookup(env->rrset_cache, ns->name,
336 ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
338 if(!delegpt_add_rrset_A(dp, region, akey, 0, NULL)) {
339 lock_rw_unlock(&akey->entry.lock);
343 addr_to_additional(akey, region, *msg, now);
344 lock_rw_unlock(&akey->entry.lock);
346 /* BIT_CD on false because delegpt lookup does
347 * not use dns64 translation */
348 neg = msg_cache_lookup(env, ns->name, ns->namelen,
349 LDNS_RR_TYPE_A, qclass, 0, now, 0);
351 delegpt_add_neg_msg(dp, neg);
352 lock_rw_unlock(&neg->entry.lock);
355 akey = rrset_cache_lookup(env->rrset_cache, ns->name,
356 ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
358 if(!delegpt_add_rrset_AAAA(dp, region, akey, 0, NULL)) {
359 lock_rw_unlock(&akey->entry.lock);
363 addr_to_additional(akey, region, *msg, now);
364 lock_rw_unlock(&akey->entry.lock);
366 /* BIT_CD on false because delegpt lookup does
367 * not use dns64 translation */
368 neg = msg_cache_lookup(env, ns->name, ns->namelen,
369 LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
371 delegpt_add_neg_msg(dp, neg);
372 lock_rw_unlock(&neg->entry.lock);
379 /** find and add A and AAAA records for missing nameservers in delegpt */
381 cache_fill_missing(struct module_env* env, uint16_t qclass,
382 struct regional* region, struct delegpt* dp)
384 struct delegpt_ns* ns;
385 struct msgreply_entry* neg;
386 struct ub_packed_rrset_key* akey;
387 time_t now = *env->now;
388 for(ns = dp->nslist; ns; ns = ns->next) {
389 if(ns->cache_lookup_count > ITERATOR_NAME_CACHELOOKUP_MAX)
391 ns->cache_lookup_count++;
392 akey = rrset_cache_lookup(env->rrset_cache, ns->name,
393 ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
395 if(!delegpt_add_rrset_A(dp, region, akey, ns->lame,
397 lock_rw_unlock(&akey->entry.lock);
400 log_nametypeclass(VERB_ALGO, "found in cache",
401 ns->name, LDNS_RR_TYPE_A, qclass);
402 lock_rw_unlock(&akey->entry.lock);
404 /* BIT_CD on false because delegpt lookup does
405 * not use dns64 translation */
406 neg = msg_cache_lookup(env, ns->name, ns->namelen,
407 LDNS_RR_TYPE_A, qclass, 0, now, 0);
409 delegpt_add_neg_msg(dp, neg);
410 lock_rw_unlock(&neg->entry.lock);
413 akey = rrset_cache_lookup(env->rrset_cache, ns->name,
414 ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
416 if(!delegpt_add_rrset_AAAA(dp, region, akey, ns->lame,
418 lock_rw_unlock(&akey->entry.lock);
421 log_nametypeclass(VERB_ALGO, "found in cache",
422 ns->name, LDNS_RR_TYPE_AAAA, qclass);
423 lock_rw_unlock(&akey->entry.lock);
425 /* BIT_CD on false because delegpt lookup does
426 * not use dns64 translation */
427 neg = msg_cache_lookup(env, ns->name, ns->namelen,
428 LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
430 delegpt_add_neg_msg(dp, neg);
431 lock_rw_unlock(&neg->entry.lock);
438 /** find and add DS or NSEC to delegation msg */
440 find_add_ds(struct module_env* env, struct regional* region,
441 struct dns_msg* msg, struct delegpt* dp, time_t now)
443 /* Lookup the DS or NSEC at the delegation point. */
444 struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
445 env->rrset_cache, dp->name, dp->namelen, LDNS_RR_TYPE_DS,
446 msg->qinfo.qclass, 0, now, 0);
448 /* NOTE: this won't work for alternate NSEC schemes
450 rrset = rrset_cache_lookup(env->rrset_cache, dp->name,
451 dp->namelen, LDNS_RR_TYPE_NSEC, msg->qinfo.qclass,
453 /* Note: the PACKED_RRSET_NSEC_AT_APEX flag is not used.
454 * since this is a referral, we need the NSEC at the parent
455 * side of the zone cut, not the NSEC at apex side. */
456 if(rrset && nsec_has_type(rrset, LDNS_RR_TYPE_DS)) {
457 lock_rw_unlock(&rrset->entry.lock);
458 rrset = NULL; /* discard wrong NSEC */
462 /* add it to auth section. This is the second rrset. */
463 if((msg->rep->rrsets[msg->rep->rrset_count] =
464 packed_rrset_copy_region(rrset, region, now))) {
465 msg->rep->ns_numrrsets++;
466 msg->rep->rrset_count++;
468 lock_rw_unlock(&rrset->entry.lock);
473 dns_msg_create(uint8_t* qname, size_t qnamelen, uint16_t qtype,
474 uint16_t qclass, struct regional* region, size_t capacity)
476 struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
477 sizeof(struct dns_msg));
480 msg->qinfo.qname = regional_alloc_init(region, qname, qnamelen);
481 if(!msg->qinfo.qname)
483 msg->qinfo.qname_len = qnamelen;
484 msg->qinfo.qtype = qtype;
485 msg->qinfo.qclass = qclass;
486 msg->qinfo.local_alias = NULL;
487 /* non-packed reply_info, because it needs to grow the array */
488 msg->rep = (struct reply_info*)regional_alloc_zero(region,
489 sizeof(struct reply_info)-sizeof(struct rrset_ref));
492 if(capacity > RR_COUNT_MAX)
493 return NULL; /* integer overflow protection */
494 msg->rep->flags = BIT_QR; /* with QR, no AA */
495 msg->rep->qdcount = 1;
496 msg->rep->reason_bogus = LDNS_EDE_NONE;
497 msg->rep->rrsets = (struct ub_packed_rrset_key**)
498 regional_alloc(region,
499 capacity*sizeof(struct ub_packed_rrset_key*));
500 if(!msg->rep->rrsets)
506 dns_msg_authadd(struct dns_msg* msg, struct regional* region,
507 struct ub_packed_rrset_key* rrset, time_t now)
509 if(!(msg->rep->rrsets[msg->rep->rrset_count++] =
510 packed_rrset_copy_region(rrset, region, now)))
512 msg->rep->ns_numrrsets++;
517 dns_msg_ansadd(struct dns_msg* msg, struct regional* region,
518 struct ub_packed_rrset_key* rrset, time_t now)
520 if(!(msg->rep->rrsets[msg->rep->rrset_count++] =
521 packed_rrset_copy_region(rrset, region, now)))
523 msg->rep->an_numrrsets++;
528 dns_cache_find_delegation(struct module_env* env, uint8_t* qname,
529 size_t qnamelen, uint16_t qtype, uint16_t qclass,
530 struct regional* region, struct dns_msg** msg, time_t now,
531 int noexpiredabove, uint8_t* expiretop, size_t expiretoplen)
533 /* try to find closest NS rrset */
534 struct ub_packed_rrset_key* nskey;
535 struct packed_rrset_data* nsdata;
538 nskey = find_closest_of_type(env, qname, qnamelen, qclass, now,
539 LDNS_RR_TYPE_NS, 0, noexpiredabove, expiretop, expiretoplen);
540 if(!nskey) /* hope the caller has hints to prime or something */
542 nsdata = (struct packed_rrset_data*)nskey->entry.data;
543 /* got the NS key, create delegation point */
544 dp = delegpt_create(region);
545 if(!dp || !delegpt_set_name(dp, region, nskey->rk.dname)) {
546 lock_rw_unlock(&nskey->entry.lock);
547 log_err("find_delegation: out of memory");
550 /* create referral message */
552 /* allocate the array to as much as we could need:
553 * NS rrset + DS/NSEC rrset +
554 * A rrset for every NS RR
555 * AAAA rrset for every NS RR
557 *msg = dns_msg_create(qname, qnamelen, qtype, qclass, region,
558 2 + nsdata->count*2);
559 if(!*msg || !dns_msg_authadd(*msg, region, nskey, now)) {
560 lock_rw_unlock(&nskey->entry.lock);
561 log_err("find_delegation: out of memory");
565 if(!delegpt_rrset_add_ns(dp, region, nskey, 0))
566 log_err("find_delegation: addns out of memory");
567 lock_rw_unlock(&nskey->entry.lock); /* first unlock before next lookup*/
568 /* find and add DS/NSEC (if any) */
570 find_add_ds(env, region, *msg, dp, now);
571 /* find and add A entries */
572 if(!find_add_addrs(env, qclass, region, dp, now, msg))
573 log_err("find_delegation: addrs out of memory");
577 /** allocate dns_msg from query_info and reply_info */
578 static struct dns_msg*
579 gen_dns_msg(struct regional* region, struct query_info* q, size_t num)
581 struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
582 sizeof(struct dns_msg));
585 memcpy(&msg->qinfo, q, sizeof(struct query_info));
586 msg->qinfo.qname = regional_alloc_init(region, q->qname, q->qname_len);
587 if(!msg->qinfo.qname)
589 /* allocate replyinfo struct and rrset key array separately */
590 msg->rep = (struct reply_info*)regional_alloc(region,
591 sizeof(struct reply_info) - sizeof(struct rrset_ref));
594 msg->rep->reason_bogus = LDNS_EDE_NONE;
595 msg->rep->reason_bogus_str = NULL;
596 if(num > RR_COUNT_MAX)
597 return NULL; /* integer overflow protection */
598 msg->rep->rrsets = (struct ub_packed_rrset_key**)
599 regional_alloc(region,
600 num * sizeof(struct ub_packed_rrset_key*));
601 if(!msg->rep->rrsets)
607 tomsg(struct module_env* env, struct query_info* q, struct reply_info* r,
608 struct regional* region, time_t now, int allow_expired,
609 struct regional* scratch)
614 time_t now_control = now;
616 /* Check if we are allowed to serve expired */
618 if(env->cfg->serve_expired_ttl &&
619 r->serve_expired_ttl < now) {
622 /* Ignore expired failure answers */
623 if(FLAGS_GET_RCODE(r->flags) !=
624 LDNS_RCODE_NOERROR &&
625 FLAGS_GET_RCODE(r->flags) !=
626 LDNS_RCODE_NXDOMAIN &&
627 FLAGS_GET_RCODE(r->flags) !=
633 /* Change the current time so we can pass the below TTL checks when
634 * serving expired data. */
635 now_control = r->ttl - env->cfg->serve_expired_reply_ttl;
639 msg = gen_dns_msg(region, q, r->rrset_count);
640 if(!msg) return NULL;
641 msg->rep->flags = r->flags;
642 msg->rep->qdcount = r->qdcount;
643 msg->rep->ttl = is_expired
644 ?SERVE_EXPIRED_REPLY_TTL
646 if(r->prefetch_ttl > now)
647 msg->rep->prefetch_ttl = r->prefetch_ttl - now;
649 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
650 msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
651 msg->rep->security = r->security;
652 msg->rep->an_numrrsets = r->an_numrrsets;
653 msg->rep->ns_numrrsets = r->ns_numrrsets;
654 msg->rep->ar_numrrsets = r->ar_numrrsets;
655 msg->rep->rrset_count = r->rrset_count;
656 msg->rep->authoritative = r->authoritative;
657 msg->rep->reason_bogus = r->reason_bogus;
658 if(r->reason_bogus_str) {
659 msg->rep->reason_bogus_str = regional_strdup(region, r->reason_bogus_str);
662 if(!rrset_array_lock(r->ref, r->rrset_count, now_control)) {
665 if(r->an_numrrsets > 0 && (r->rrsets[0]->rk.type == htons(
666 LDNS_RR_TYPE_CNAME) || r->rrsets[0]->rk.type == htons(
667 LDNS_RR_TYPE_DNAME)) && !reply_check_cname_chain(q, r)) {
668 /* cname chain is now invalid, reconstruct msg */
669 rrset_array_unlock(r->ref, r->rrset_count);
672 if(r->security == sec_status_secure && !reply_all_rrsets_secure(r)) {
673 /* message rrsets have changed status, revalidate */
674 rrset_array_unlock(r->ref, r->rrset_count);
677 for(i=0; i<msg->rep->rrset_count; i++) {
678 msg->rep->rrsets[i] = packed_rrset_copy_region(r->rrsets[i],
680 if(!msg->rep->rrsets[i]) {
681 rrset_array_unlock(r->ref, r->rrset_count);
686 rrset_array_unlock_touch(env->rrset_cache, scratch, r->ref,
689 rrset_array_unlock(r->ref, r->rrset_count);
693 /** synthesize RRset-only response from cached RRset item */
694 static struct dns_msg*
695 rrset_msg(struct ub_packed_rrset_key* rrset, struct regional* region,
696 time_t now, struct query_info* q)
699 struct packed_rrset_data* d = (struct packed_rrset_data*)
703 msg = gen_dns_msg(region, q, 1); /* only the CNAME (or other) RRset */
706 msg->rep->flags = BIT_QR; /* reply, no AA, no error */
707 msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
708 msg->rep->qdcount = 1;
709 msg->rep->ttl = d->ttl - now;
710 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
711 msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
712 msg->rep->security = sec_status_unchecked;
713 msg->rep->an_numrrsets = 1;
714 msg->rep->ns_numrrsets = 0;
715 msg->rep->ar_numrrsets = 0;
716 msg->rep->rrset_count = 1;
717 msg->rep->reason_bogus = LDNS_EDE_NONE;
718 msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
719 if(!msg->rep->rrsets[0]) /* copy CNAME */
724 /** synthesize DNAME+CNAME response from cached DNAME item */
725 static struct dns_msg*
726 synth_dname_msg(struct ub_packed_rrset_key* rrset, struct regional* region,
727 time_t now, struct query_info* q, enum sec_status* sec_status)
730 struct ub_packed_rrset_key* ck;
731 struct packed_rrset_data* newd, *d = (struct packed_rrset_data*)
733 uint8_t* newname, *dtarg = NULL;
734 size_t newlen, dtarglen;
737 /* only allow validated (with DNSSEC) DNAMEs used from cache
738 * for insecure DNAMEs, query again. */
739 *sec_status = d->security;
740 /* return sec status, so the status of the CNAME can be checked
741 * by the calling routine. */
742 msg = gen_dns_msg(region, q, 2); /* DNAME + CNAME RRset */
745 msg->rep->flags = BIT_QR; /* reply, no AA, no error */
746 msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
747 msg->rep->qdcount = 1;
748 msg->rep->ttl = d->ttl - now;
749 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
750 msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
751 msg->rep->security = sec_status_unchecked;
752 msg->rep->an_numrrsets = 1;
753 msg->rep->ns_numrrsets = 0;
754 msg->rep->ar_numrrsets = 0;
755 msg->rep->rrset_count = 1;
756 msg->rep->reason_bogus = LDNS_EDE_NONE;
757 msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
758 if(!msg->rep->rrsets[0]) /* copy DNAME */
760 /* synth CNAME rrset */
761 get_cname_target(rrset, &dtarg, &dtarglen);
764 newlen = q->qname_len + dtarglen - rrset->rk.dname_len;
765 if(newlen > LDNS_MAX_DOMAINLEN) {
766 msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
769 newname = (uint8_t*)regional_alloc(region, newlen);
772 /* new name is concatenation of qname front (without DNAME owner)
773 * and DNAME target name */
774 memcpy(newname, q->qname, q->qname_len-rrset->rk.dname_len);
775 memmove(newname+(q->qname_len-rrset->rk.dname_len), dtarg, dtarglen);
776 /* create rest of CNAME rrset */
777 ck = (struct ub_packed_rrset_key*)regional_alloc(region,
778 sizeof(struct ub_packed_rrset_key));
781 memset(&ck->entry, 0, sizeof(ck->entry));
782 msg->rep->rrsets[1] = ck;
784 ck->rk.type = htons(LDNS_RR_TYPE_CNAME);
785 ck->rk.rrset_class = rrset->rk.rrset_class;
787 ck->rk.dname = regional_alloc_init(region, q->qname, q->qname_len);
790 ck->rk.dname_len = q->qname_len;
791 ck->entry.hash = rrset_key_hash(&ck->rk);
792 newd = (struct packed_rrset_data*)regional_alloc_zero(region,
793 sizeof(struct packed_rrset_data) + sizeof(size_t) +
794 sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t)
798 ck->entry.data = newd;
799 newd->ttl = 0; /* 0 for synthesized CNAME TTL */
801 newd->rrsig_count = 0;
802 newd->trust = rrset_trust_ans_noAA;
803 newd->rr_len = (size_t*)((uint8_t*)newd +
804 sizeof(struct packed_rrset_data));
805 newd->rr_len[0] = newlen + sizeof(uint16_t);
806 packed_rrset_ptr_fixup(newd);
807 newd->rr_ttl[0] = newd->ttl;
808 msg->rep->ttl = newd->ttl;
809 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(newd->ttl);
810 msg->rep->serve_expired_ttl = newd->ttl + SERVE_EXPIRED_TTL;
811 sldns_write_uint16(newd->rr_data[0], newlen);
812 memmove(newd->rr_data[0] + sizeof(uint16_t), newname, newlen);
813 msg->rep->an_numrrsets ++;
814 msg->rep->rrset_count ++;
818 /** Fill TYPE_ANY response with some data from cache */
819 static struct dns_msg*
820 fill_any(struct module_env* env,
821 uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
822 struct regional* region)
824 time_t now = *env->now;
825 struct dns_msg* msg = NULL;
826 uint16_t lookup[] = {LDNS_RR_TYPE_A, LDNS_RR_TYPE_AAAA,
827 LDNS_RR_TYPE_MX, LDNS_RR_TYPE_SOA, LDNS_RR_TYPE_NS,
828 LDNS_RR_TYPE_DNAME, 0};
829 int i, num=6; /* number of RR types to look up */
830 log_assert(lookup[num] == 0);
832 if(env->cfg->deny_any) {
833 /* return empty message */
834 msg = dns_msg_create(qname, qnamelen, qtype, qclass,
839 /* set NOTIMPL for RFC 8482 */
840 msg->rep->flags |= LDNS_RCODE_NOTIMPL;
841 msg->rep->security = sec_status_indeterminate;
845 for(i=0; i<num; i++) {
846 /* look up this RR for inclusion in type ANY response */
847 struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
848 env->rrset_cache, qname, qnamelen, lookup[i],
850 struct packed_rrset_data *d;
854 /* only if rrset from answer section */
855 d = (struct packed_rrset_data*)rrset->entry.data;
856 if(d->trust == rrset_trust_add_noAA ||
857 d->trust == rrset_trust_auth_noAA ||
858 d->trust == rrset_trust_add_AA ||
859 d->trust == rrset_trust_auth_AA) {
860 lock_rw_unlock(&rrset->entry.lock);
864 /* create msg if none */
866 msg = dns_msg_create(qname, qnamelen, qtype, qclass,
867 region, (size_t)(num-i));
869 lock_rw_unlock(&rrset->entry.lock);
874 /* add RRset to response */
875 if(!dns_msg_ansadd(msg, region, rrset, now)) {
876 lock_rw_unlock(&rrset->entry.lock);
879 lock_rw_unlock(&rrset->entry.lock);
885 dns_cache_lookup(struct module_env* env,
886 uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
887 uint16_t flags, struct regional* region, struct regional* scratch,
888 int no_partial, uint8_t* dpname, size_t dpnamelen)
890 struct lruhash_entry* e;
893 time_t now = *env->now;
894 struct ub_packed_rrset_key* rrset;
896 /* lookup first, this has both NXdomains and ANSWER responses */
898 k.qname_len = qnamelen;
901 k.local_alias = NULL;
902 h = query_info_hash(&k, flags);
903 e = slabhash_lookup(env->msg_cache, h, &k, 0);
905 struct msgreply_entry* key = (struct msgreply_entry*)e->key;
906 struct reply_info* data = (struct reply_info*)e->data;
907 struct dns_msg* msg = tomsg(env, &key->key, data, region, now, 0,
910 lock_rw_unlock(&e->lock);
913 /* could be msg==NULL; due to TTL or not all rrsets available */
914 lock_rw_unlock(&e->lock);
917 /* see if a DNAME exists. Checked for first, to enforce that DNAMEs
918 * are more important, the CNAME is resynthesized and thus
919 * consistent with the DNAME */
921 (rrset=find_closest_of_type(env, qname, qnamelen, qclass, now,
922 LDNS_RR_TYPE_DNAME, 1, 0, NULL, 0))) {
923 /* synthesize a DNAME+CNAME message based on this */
924 enum sec_status sec_status = sec_status_unchecked;
925 struct dns_msg* msg = synth_dname_msg(rrset, region, now, &k,
928 struct ub_packed_rrset_key* cname_rrset;
929 lock_rw_unlock(&rrset->entry.lock);
930 /* now, after unlocking the DNAME rrset lock,
931 * check the sec_status, and see if we need to look
932 * up the CNAME record associated before it can
934 /* normally, only secure DNAMEs allowed from cache*/
935 if(sec_status == sec_status_secure)
937 /* but if we have a CNAME cached with this name, then we
938 * have previously already allowed this name to pass.
939 * the next cache lookup is going to fetch that CNAME itself,
940 * but it is better to have the (unsigned)DNAME + CNAME in
942 cname_rrset = rrset_cache_lookup(
943 env->rrset_cache, qname, qnamelen,
944 LDNS_RR_TYPE_CNAME, qclass, 0, now, 0);
946 /* CNAME already synthesized by
947 * synth_dname_msg routine, so we can
948 * straight up return the msg */
949 lock_rw_unlock(&cname_rrset->entry.lock);
953 lock_rw_unlock(&rrset->entry.lock);
957 /* see if we have CNAME for this domain,
958 * but not for DS records (which are part of the parent) */
959 if(!no_partial && qtype != LDNS_RR_TYPE_DS &&
960 (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen,
961 LDNS_RR_TYPE_CNAME, qclass, 0, now, 0))) {
964 /* if the rrset is not a wildcard expansion, with wcname */
965 /* because, if we return that CNAME rrset on its own, it is
966 * missing the NSEC or NSEC3 proof */
967 if(!(val_rrset_wildcard(rrset, &wc, &wl) && wc != NULL)) {
968 struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
970 lock_rw_unlock(&rrset->entry.lock);
974 lock_rw_unlock(&rrset->entry.lock);
977 /* construct DS, DNSKEY messages from rrset cache. */
978 if((qtype == LDNS_RR_TYPE_DS || qtype == LDNS_RR_TYPE_DNSKEY) &&
979 (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen,
980 qtype, qclass, 0, now, 0))) {
981 /* if the rrset is from the additional section, and the
982 * signatures have fallen off, then do not synthesize a msg
983 * instead, allow a full query for signed results to happen.
984 * Forego all rrset data from additional section, because
985 * some signatures may not be present and cause validation
988 struct packed_rrset_data *d = (struct packed_rrset_data*)
990 if(d->trust != rrset_trust_add_noAA &&
991 d->trust != rrset_trust_add_AA &&
992 (qtype == LDNS_RR_TYPE_DS ||
993 (d->trust != rrset_trust_auth_noAA
994 && d->trust != rrset_trust_auth_AA) )) {
995 struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
997 lock_rw_unlock(&rrset->entry.lock);
1001 lock_rw_unlock(&rrset->entry.lock);
1004 /* stop downwards cache search on NXDOMAIN.
1005 * Empty nonterminals are NOERROR, so an NXDOMAIN for foo
1006 * means bla.foo also does not exist. The DNSSEC proofs are
1007 * the same. We search upwards for NXDOMAINs. */
1008 if(env->cfg->harden_below_nxdomain) {
1009 while(!dname_is_root(k.qname)) {
1010 if(dpname && dpnamelen
1011 && !dname_subdomain_c(k.qname, dpname))
1012 break; /* no synth nxdomain above the stub */
1013 dname_remove_label(&k.qname, &k.qname_len);
1014 h = query_info_hash(&k, flags);
1015 e = slabhash_lookup(env->msg_cache, h, &k, 0);
1016 if(!e && k.qtype != LDNS_RR_TYPE_A &&
1017 env->cfg->qname_minimisation) {
1018 k.qtype = LDNS_RR_TYPE_A;
1019 h = query_info_hash(&k, flags);
1020 e = slabhash_lookup(env->msg_cache, h, &k, 0);
1023 struct reply_info* data = (struct reply_info*)e->data;
1024 struct dns_msg* msg;
1025 if(FLAGS_GET_RCODE(data->flags) == LDNS_RCODE_NXDOMAIN
1026 && data->security == sec_status_secure
1027 && (data->an_numrrsets == 0 ||
1028 ntohs(data->rrsets[0]->rk.type) != LDNS_RR_TYPE_CNAME)
1029 && (msg=tomsg(env, &k, data, region, now, 0, scratch))) {
1030 lock_rw_unlock(&e->lock);
1031 msg->qinfo.qname=qname;
1032 msg->qinfo.qname_len=qnamelen;
1033 /* check that DNSSEC really works out */
1034 msg->rep->security = sec_status_unchecked;
1035 iter_scrub_nxdomain(msg);
1038 lock_rw_unlock(&e->lock);
1044 /* fill common RR types for ANY response to avoid requery */
1045 if(qtype == LDNS_RR_TYPE_ANY) {
1046 return fill_any(env, qname, qnamelen, qtype, qclass, region);
1053 dns_cache_store(struct module_env* env, struct query_info* msgqinf,
1054 struct reply_info* msgrep, int is_referral, time_t leeway, int pside,
1055 struct regional* region, uint32_t flags, time_t qstarttime)
1057 struct reply_info* rep = NULL;
1058 /* alloc, malloc properly (not in region, like msg is) */
1059 rep = reply_info_copy(msgrep, env->alloc, NULL);
1062 /* ttl must be relative ;i.e. 0..86400 not time(0)+86400.
1063 * the env->now is added to message and RRsets in this routine. */
1064 /* the leeway is used to invalidate other rrsets earlier */
1067 struct rrset_ref ref;
1069 for(i=0; i<rep->rrset_count; i++) {
1070 packed_rrset_ttl_add((struct packed_rrset_data*)
1071 rep->rrsets[i]->entry.data, *env->now);
1072 ref.key = rep->rrsets[i];
1073 ref.id = rep->rrsets[i]->id;
1074 /*ignore ret: it was in the cache, ref updated */
1075 /* no leeway for typeNS */
1076 (void)rrset_cache_update(env->rrset_cache, &ref,
1078 ((ntohs(ref.key->rk.type)==LDNS_RR_TYPE_NS
1079 && !pside) ? qstarttime:*env->now + leeway));
1081 reply_info_delete(rep, NULL);
1084 /* store msg, and rrsets */
1085 struct query_info qinf;
1089 qinf.qname = memdup(msgqinf->qname, msgqinf->qname_len);
1091 reply_info_parsedelete(rep, env->alloc);
1094 /* fixup flags to be sensible for a reply based on the cache */
1095 /* this module means that RA is available. It is an answer QR.
1096 * Not AA from cache. Not CD in cache (depends on client bit). */
1097 rep->flags |= (BIT_RA | BIT_QR);
1098 rep->flags &= ~(BIT_AA | BIT_CD);
1099 h = query_info_hash(&qinf, (uint16_t)flags);
1100 dns_cache_store_msg(env, &qinf, h, rep, leeway, pside, msgrep,
1101 flags, region, qstarttime);
1102 /* qname is used inside query_info_entrysetup, and set to
1103 * NULL. If it has not been used, free it. free(0) is safe. */
1110 dns_cache_prefetch_adjust(struct module_env* env, struct query_info* qinfo,
1111 time_t adjust, uint16_t flags)
1113 struct msgreply_entry* msg;
1114 msg = msg_cache_lookup(env, qinfo->qname, qinfo->qname_len,
1115 qinfo->qtype, qinfo->qclass, flags, *env->now, 1);
1117 struct reply_info* rep = (struct reply_info*)msg->entry.data;
1119 rep->prefetch_ttl += adjust;
1120 lock_rw_unlock(&msg->entry.lock);
1123 lock_rw_unlock(&msg->entry.lock);