xref: /freebsd/contrib/unbound/services/cache/dns.c (revision 46d2f61818f594174cafe31ee338c6e083fa1876)
1 /*
2  * services/cache/dns.c - Cache services for DNS using msg and rrset caches.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
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.
18  *
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.
22  *
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.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains the DNS cache.
40  */
41 #include "config.h"
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"
57 
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
75  *	expired then.
76  */
77 static void
store_rrsets(struct module_env * env,struct reply_info * rep,time_t now,time_t leeway,int pside,struct reply_info * qrep,struct regional * region,time_t qstarttime)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)
81 {
82 	size_t i;
83 	time_t ttl, min_ttl = rep->ttl;
84 	/* see if rrset already exists in cache, if not insert it. */
85 	for(i=0; i<rep->rrset_count; i++) {
86 		rep->ref[i].key = rep->rrsets[i];
87 		rep->ref[i].id = rep->rrsets[i]->id;
88 		/* update ref if it was in the cache */
89 		switch(rrset_cache_update(env->rrset_cache, &rep->ref[i],
90 				env->alloc, ((ntohs(rep->ref[i].key->rk.type)==
91 				LDNS_RR_TYPE_NS && !pside)?qstarttime:now) + leeway)) {
92 		case 0: /* ref unchanged, item inserted */
93 			break;
94 		case 2: /* ref updated, cache is superior */
95 			if(region) {
96 				struct ub_packed_rrset_key* ck;
97 				lock_rw_rdlock(&rep->ref[i].key->entry.lock);
98 				/* if deleted rrset, do not copy it */
99 				if(rep->ref[i].key->id == 0 ||
100 					rep->ref[i].id != rep->ref[i].key->id)
101 					ck = NULL;
102 				else 	ck = packed_rrset_copy_region(
103 					rep->ref[i].key, region, now);
104 				lock_rw_unlock(&rep->ref[i].key->entry.lock);
105 				if(ck) {
106 					/* use cached copy if memory allows */
107 					qrep->rrsets[i] = ck;
108 				}
109 			}
110 			/* no break: also copy key item */
111 			/* the line below is matched by gcc regex and silences
112 			 * the fallthrough warning */
113 			ATTR_FALLTHROUGH
114 			/* fallthrough */
115 		case 1: /* ref updated, item inserted */
116 			rep->rrsets[i] = rep->ref[i].key;
117 			/* ref was updated; make sure the message ttl is
118 			 * updated to the minimum of the current rrsets. */
119 			lock_rw_rdlock(&rep->ref[i].key->entry.lock);
120 			/* if deleted, skip ttl update. */
121 			if(rep->ref[i].key->id != 0 &&
122 				rep->ref[i].id == rep->ref[i].key->id) {
123 				ttl = ((struct packed_rrset_data*)
124 				    rep->rrsets[i]->entry.data)->ttl;
125 				if(ttl < min_ttl) min_ttl = ttl;
126 			}
127 			lock_rw_unlock(&rep->ref[i].key->entry.lock);
128 		}
129 	}
130 	if(min_ttl < rep->ttl) {
131 		rep->ttl = min_ttl;
132 		rep->prefetch_ttl = PREFETCH_TTL_CALC(rep->ttl);
133 		rep->serve_expired_ttl = rep->ttl + SERVE_EXPIRED_TTL;
134 	}
135 }
136 
137 /** delete message from message cache */
138 void
msg_cache_remove(struct module_env * env,uint8_t * qname,size_t qnamelen,uint16_t qtype,uint16_t qclass,uint16_t flags)139 msg_cache_remove(struct module_env* env, uint8_t* qname, size_t qnamelen,
140 	uint16_t qtype, uint16_t qclass, uint16_t flags)
141 {
142 	struct query_info k;
143 	hashvalue_type h;
144 
145 	k.qname = qname;
146 	k.qname_len = qnamelen;
147 	k.qtype = qtype;
148 	k.qclass = qclass;
149 	k.local_alias = NULL;
150 	h = query_info_hash(&k, flags);
151 	slabhash_remove(env->msg_cache, h, &k);
152 }
153 
154 void
dns_cache_store_msg(struct module_env * env,struct query_info * qinfo,hashvalue_type hash,struct reply_info * rep,time_t leeway,int pside,struct reply_info * qrep,uint32_t flags,struct regional * region,time_t qstarttime)155 dns_cache_store_msg(struct module_env* env, struct query_info* qinfo,
156 	hashvalue_type hash, struct reply_info* rep, time_t leeway, int pside,
157 	struct reply_info* qrep, uint32_t flags, struct regional* region,
158 	time_t qstarttime)
159 {
160 	struct msgreply_entry* e;
161 	time_t ttl = rep->ttl;
162 	size_t i;
163 
164 	/* store RRsets */
165 	for(i=0; i<rep->rrset_count; i++) {
166 		rep->ref[i].key = rep->rrsets[i];
167 		rep->ref[i].id = rep->rrsets[i]->id;
168 	}
169 
170 	/* there was a reply_info_sortref(rep) here but it seems to be
171 	 * unnecessary, because the cache gets locked per rrset. */
172 	reply_info_set_ttls(rep, *env->now);
173 	store_rrsets(env, rep, *env->now, leeway, pside, qrep, region,
174 		qstarttime);
175 	if(ttl == 0 && !(flags & DNSCACHE_STORE_ZEROTTL)) {
176 		/* we do not store the message, but we did store the RRs,
177 		 * which could be useful for delegation information */
178 		verbose(VERB_ALGO, "TTL 0: dropped msg from cache");
179 		reply_info_delete(rep, NULL);
180 		/* if the message is in the cache, remove that msg,
181 		 * so that the TTL 0 response can be returned for future
182 		 * responses (i.e. don't get answered from
183 		 * cache, but instead go to recursion to get this TTL0
184 		 * response).
185 		 * Possible messages that could be in the cache:
186 		 * - SERVFAIL
187 		 * - NXDOMAIN
188 		 * - NODATA
189 		 * - an older record that is expired
190 		 * - an older record that did not yet expire */
191 		msg_cache_remove(env, qinfo->qname, qinfo->qname_len,
192 			qinfo->qtype, qinfo->qclass, flags);
193 		return;
194 	}
195 
196 	/* store msg in the cache */
197 	reply_info_sortref(rep);
198 	if(!(e = query_info_entrysetup(qinfo, rep, hash))) {
199 		log_err("store_msg: malloc failed");
200 		reply_info_delete(rep, NULL);
201 		return;
202 	}
203 	slabhash_insert(env->msg_cache, hash, &e->entry, rep, env->alloc);
204 }
205 
206 /** find closest NS or DNAME and returns the rrset (locked) */
207 static struct ub_packed_rrset_key*
find_closest_of_type(struct module_env * env,uint8_t * qname,size_t qnamelen,uint16_t qclass,time_t now,uint16_t searchtype,int stripfront,int noexpiredabove,uint8_t * expiretop,size_t expiretoplen)208 find_closest_of_type(struct module_env* env, uint8_t* qname, size_t qnamelen,
209 	uint16_t qclass, time_t now, uint16_t searchtype, int stripfront,
210 	int noexpiredabove, uint8_t* expiretop, size_t expiretoplen)
211 {
212 	struct ub_packed_rrset_key *rrset;
213 	uint8_t lablen;
214 
215 	if(stripfront) {
216 		/* strip off so that DNAMEs have strict subdomain match */
217 		lablen = *qname;
218 		qname += lablen + 1;
219 		qnamelen -= lablen + 1;
220 	}
221 
222 	/* snip off front part of qname until the type is found */
223 	while(qnamelen > 0) {
224 		if((rrset = rrset_cache_lookup(env->rrset_cache, qname,
225 			qnamelen, searchtype, qclass, 0, now, 0))) {
226 			uint8_t* origqname = qname;
227 			size_t origqnamelen = qnamelen;
228 			if(!noexpiredabove)
229 				return rrset;
230 			/* if expiretop set, do not look above it, but
231 			 * qname is equal, so the just found result is also
232 			 * the nonexpired above part. */
233 			if(expiretop && qnamelen == expiretoplen &&
234 				query_dname_compare(qname, expiretop)==0)
235 				return rrset;
236 			/* check for expiry, but we have to let go of the rrset
237 			 * for the lock ordering */
238 			lock_rw_unlock(&rrset->entry.lock);
239 			/* the rrset_cache_expired_above function always takes
240 			 * off one label (if qnamelen>0) and returns the final
241 			 * qname where it searched, so we can continue from
242 			 * there turning the O N*N search into O N. */
243 			if(!rrset_cache_expired_above(env->rrset_cache, &qname,
244 				&qnamelen, searchtype, qclass, now, expiretop,
245 				expiretoplen)) {
246 				/* we want to return rrset, but it may be
247 				 * gone from cache, if so, just loop like
248 				 * it was not in the cache in the first place.
249 				 */
250 				if((rrset = rrset_cache_lookup(env->
251 					rrset_cache, origqname, origqnamelen,
252 					searchtype, qclass, 0, now, 0))) {
253 					return rrset;
254 				}
255 			}
256 			log_nametypeclass(VERB_ALGO, "ignoring rrset because expired rrsets exist above it", origqname, searchtype, qclass);
257 			continue;
258 		}
259 
260 		/* snip off front label */
261 		lablen = *qname;
262 		qname += lablen + 1;
263 		qnamelen -= lablen + 1;
264 	}
265 	return NULL;
266 }
267 
268 /** add addr to additional section */
269 static void
addr_to_additional(struct ub_packed_rrset_key * rrset,struct regional * region,struct dns_msg * msg,time_t now)270 addr_to_additional(struct ub_packed_rrset_key* rrset, struct regional* region,
271 	struct dns_msg* msg, time_t now)
272 {
273 	if((msg->rep->rrsets[msg->rep->rrset_count] =
274 		packed_rrset_copy_region(rrset, region, now))) {
275 		msg->rep->ar_numrrsets++;
276 		msg->rep->rrset_count++;
277 	}
278 }
279 
280 /** lookup message in message cache */
281 struct msgreply_entry*
msg_cache_lookup(struct module_env * env,uint8_t * qname,size_t qnamelen,uint16_t qtype,uint16_t qclass,uint16_t flags,time_t now,int wr)282 msg_cache_lookup(struct module_env* env, uint8_t* qname, size_t qnamelen,
283 	uint16_t qtype, uint16_t qclass, uint16_t flags, time_t now, int wr)
284 {
285 	struct lruhash_entry* e;
286 	struct query_info k;
287 	hashvalue_type h;
288 
289 	k.qname = qname;
290 	k.qname_len = qnamelen;
291 	k.qtype = qtype;
292 	k.qclass = qclass;
293 	k.local_alias = NULL;
294 	h = query_info_hash(&k, flags);
295 	e = slabhash_lookup(env->msg_cache, h, &k, wr);
296 
297 	if(!e) return NULL;
298 	if( now > ((struct reply_info*)e->data)->ttl ) {
299 		lock_rw_unlock(&e->lock);
300 		return NULL;
301 	}
302 	return (struct msgreply_entry*)e->key;
303 }
304 
305 /** find and add A and AAAA records for nameservers in delegpt */
306 static int
find_add_addrs(struct module_env * env,uint16_t qclass,struct regional * region,struct delegpt * dp,time_t now,struct dns_msg ** msg)307 find_add_addrs(struct module_env* env, uint16_t qclass,
308 	struct regional* region, struct delegpt* dp, time_t now,
309 	struct dns_msg** msg)
310 {
311 	struct delegpt_ns* ns;
312 	struct msgreply_entry* neg;
313 	struct ub_packed_rrset_key* akey;
314 	for(ns = dp->nslist; ns; ns = ns->next) {
315 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
316 			ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
317 		if(akey) {
318 			if(!delegpt_add_rrset_A(dp, region, akey, 0, NULL)) {
319 				lock_rw_unlock(&akey->entry.lock);
320 				return 0;
321 			}
322 			if(msg)
323 				addr_to_additional(akey, region, *msg, now);
324 			lock_rw_unlock(&akey->entry.lock);
325 		} else {
326 			/* BIT_CD on false because delegpt lookup does
327 			 * not use dns64 translation */
328 			neg = msg_cache_lookup(env, ns->name, ns->namelen,
329 				LDNS_RR_TYPE_A, qclass, 0, now, 0);
330 			if(neg) {
331 				delegpt_add_neg_msg(dp, neg);
332 				lock_rw_unlock(&neg->entry.lock);
333 			}
334 		}
335 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
336 			ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
337 		if(akey) {
338 			if(!delegpt_add_rrset_AAAA(dp, region, akey, 0, NULL)) {
339 				lock_rw_unlock(&akey->entry.lock);
340 				return 0;
341 			}
342 			if(msg)
343 				addr_to_additional(akey, region, *msg, now);
344 			lock_rw_unlock(&akey->entry.lock);
345 		} else {
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_AAAA, qclass, 0, now, 0);
350 			/* Because recursion for lookup uses BIT_CD, check
351 			 * for that so it stops the recursion lookup, if a
352 			 * negative answer is cached. Because the cache uses
353 			 * the CD flag for type AAAA. */
354 			if(!neg)
355 				neg = msg_cache_lookup(env, ns->name, ns->namelen,
356 					LDNS_RR_TYPE_AAAA, qclass, BIT_CD, now, 0);
357 			if(neg) {
358 				delegpt_add_neg_msg(dp, neg);
359 				lock_rw_unlock(&neg->entry.lock);
360 			}
361 		}
362 	}
363 	return 1;
364 }
365 
366 /** find and add A and AAAA records for missing nameservers in delegpt */
367 int
cache_fill_missing(struct module_env * env,uint16_t qclass,struct regional * region,struct delegpt * dp,uint32_t flags)368 cache_fill_missing(struct module_env* env, uint16_t qclass,
369 	struct regional* region, struct delegpt* dp, uint32_t flags)
370 {
371 	struct delegpt_ns* ns;
372 	struct msgreply_entry* neg;
373 	struct ub_packed_rrset_key* akey;
374 	time_t now = *env->now;
375 	for(ns = dp->nslist; ns; ns = ns->next) {
376 		if(ns->cache_lookup_count > ITERATOR_NAME_CACHELOOKUP_MAX)
377 			continue;
378 		ns->cache_lookup_count++;
379 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
380 			ns->namelen, LDNS_RR_TYPE_A, qclass, flags, now, 0);
381 		if(akey) {
382 			if(!delegpt_add_rrset_A(dp, region, akey, ns->lame,
383 				NULL)) {
384 				lock_rw_unlock(&akey->entry.lock);
385 				return 0;
386 			}
387 			log_nametypeclass(VERB_ALGO, "found in cache",
388 				ns->name, LDNS_RR_TYPE_A, qclass);
389 			lock_rw_unlock(&akey->entry.lock);
390 		} else {
391 			/* BIT_CD on false because delegpt lookup does
392 			 * not use dns64 translation */
393 			neg = msg_cache_lookup(env, ns->name, ns->namelen,
394 				LDNS_RR_TYPE_A, qclass, 0, now, 0);
395 			if(neg) {
396 				delegpt_add_neg_msg(dp, neg);
397 				lock_rw_unlock(&neg->entry.lock);
398 			}
399 		}
400 		akey = rrset_cache_lookup(env->rrset_cache, ns->name,
401 			ns->namelen, LDNS_RR_TYPE_AAAA, qclass, flags, now, 0);
402 		if(akey) {
403 			if(!delegpt_add_rrset_AAAA(dp, region, akey, ns->lame,
404 				NULL)) {
405 				lock_rw_unlock(&akey->entry.lock);
406 				return 0;
407 			}
408 			log_nametypeclass(VERB_ALGO, "found in cache",
409 				ns->name, LDNS_RR_TYPE_AAAA, qclass);
410 			lock_rw_unlock(&akey->entry.lock);
411 		} else {
412 			/* BIT_CD on false because delegpt lookup does
413 			 * not use dns64 translation */
414 			neg = msg_cache_lookup(env, ns->name, ns->namelen,
415 				LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
416 			/* Because recursion for lookup uses BIT_CD, check
417 			 * for that so it stops the recursion lookup, if a
418 			 * negative answer is cached. Because the cache uses
419 			 * the CD flag for type AAAA. */
420 			if(!neg)
421 				neg = msg_cache_lookup(env, ns->name, ns->namelen,
422 					LDNS_RR_TYPE_AAAA, qclass, BIT_CD, now, 0);
423 			if(neg) {
424 				delegpt_add_neg_msg(dp, neg);
425 				lock_rw_unlock(&neg->entry.lock);
426 			}
427 		}
428 	}
429 	return 1;
430 }
431 
432 /** find and add DS or NSEC to delegation msg */
433 static void
find_add_ds(struct module_env * env,struct regional * region,struct dns_msg * msg,struct delegpt * dp,time_t now)434 find_add_ds(struct module_env* env, struct regional* region,
435 	struct dns_msg* msg, struct delegpt* dp, time_t now)
436 {
437 	/* Lookup the DS or NSEC at the delegation point. */
438 	struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
439 		env->rrset_cache, dp->name, dp->namelen, LDNS_RR_TYPE_DS,
440 		msg->qinfo.qclass, 0, now, 0);
441 	if(!rrset) {
442 		/* NOTE: this won't work for alternate NSEC schemes
443 		 *	(opt-in, NSEC3) */
444 		rrset = rrset_cache_lookup(env->rrset_cache, dp->name,
445 			dp->namelen, LDNS_RR_TYPE_NSEC, msg->qinfo.qclass,
446 			0, now, 0);
447 		/* Note: the PACKED_RRSET_NSEC_AT_APEX flag is not used.
448 		 * since this is a referral, we need the NSEC at the parent
449 		 * side of the zone cut, not the NSEC at apex side. */
450 		if(rrset && nsec_has_type(rrset, LDNS_RR_TYPE_DS)) {
451 			lock_rw_unlock(&rrset->entry.lock);
452 			rrset = NULL; /* discard wrong NSEC */
453 		}
454 	}
455 	if(rrset) {
456 		/* add it to auth section. This is the second rrset. */
457 		if((msg->rep->rrsets[msg->rep->rrset_count] =
458 			packed_rrset_copy_region(rrset, region, now))) {
459 			msg->rep->ns_numrrsets++;
460 			msg->rep->rrset_count++;
461 		}
462 		lock_rw_unlock(&rrset->entry.lock);
463 	}
464 }
465 
466 struct dns_msg*
dns_msg_create(uint8_t * qname,size_t qnamelen,uint16_t qtype,uint16_t qclass,struct regional * region,size_t capacity)467 dns_msg_create(uint8_t* qname, size_t qnamelen, uint16_t qtype,
468 	uint16_t qclass, struct regional* region, size_t capacity)
469 {
470 	struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
471 		sizeof(struct dns_msg));
472 	if(!msg)
473 		return NULL;
474 	msg->qinfo.qname = regional_alloc_init(region, qname, qnamelen);
475 	if(!msg->qinfo.qname)
476 		return NULL;
477 	msg->qinfo.qname_len = qnamelen;
478 	msg->qinfo.qtype = qtype;
479 	msg->qinfo.qclass = qclass;
480 	msg->qinfo.local_alias = NULL;
481 	/* non-packed reply_info, because it needs to grow the array */
482 	msg->rep = (struct reply_info*)regional_alloc_zero(region,
483 		sizeof(struct reply_info)-sizeof(struct rrset_ref));
484 	if(!msg->rep)
485 		return NULL;
486 	if(capacity > RR_COUNT_MAX)
487 		return NULL; /* integer overflow protection */
488 	msg->rep->flags = BIT_QR; /* with QR, no AA */
489 	msg->rep->qdcount = 1;
490 	msg->rep->reason_bogus = LDNS_EDE_NONE;
491 	msg->rep->rrsets = (struct ub_packed_rrset_key**)
492 		regional_alloc(region,
493 		capacity*sizeof(struct ub_packed_rrset_key*));
494 	if(!msg->rep->rrsets)
495 		return NULL;
496 	return msg;
497 }
498 
499 int
dns_msg_authadd(struct dns_msg * msg,struct regional * region,struct ub_packed_rrset_key * rrset,time_t now)500 dns_msg_authadd(struct dns_msg* msg, struct regional* region,
501 	struct ub_packed_rrset_key* rrset, time_t now)
502 {
503 	if(!(msg->rep->rrsets[msg->rep->rrset_count++] =
504 		packed_rrset_copy_region(rrset, region, now)))
505 		return 0;
506 	msg->rep->ns_numrrsets++;
507 	return 1;
508 }
509 
510 int
dns_msg_ansadd(struct dns_msg * msg,struct regional * region,struct ub_packed_rrset_key * rrset,time_t now)511 dns_msg_ansadd(struct dns_msg* msg, struct regional* region,
512 	struct ub_packed_rrset_key* rrset, time_t now)
513 {
514 	if(!(msg->rep->rrsets[msg->rep->rrset_count++] =
515 		packed_rrset_copy_region(rrset, region, now)))
516 		return 0;
517 	msg->rep->an_numrrsets++;
518 	return 1;
519 }
520 
521 struct delegpt*
dns_cache_find_delegation(struct module_env * env,uint8_t * qname,size_t qnamelen,uint16_t qtype,uint16_t qclass,struct regional * region,struct dns_msg ** msg,time_t now,int noexpiredabove,uint8_t * expiretop,size_t expiretoplen)522 dns_cache_find_delegation(struct module_env* env, uint8_t* qname,
523 	size_t qnamelen, uint16_t qtype, uint16_t qclass,
524 	struct regional* region, struct dns_msg** msg, time_t now,
525 	int noexpiredabove, uint8_t* expiretop, size_t expiretoplen)
526 {
527 	/* try to find closest NS rrset */
528 	struct ub_packed_rrset_key* nskey;
529 	struct packed_rrset_data* nsdata;
530 	struct delegpt* dp;
531 
532 	nskey = find_closest_of_type(env, qname, qnamelen, qclass, now,
533 		LDNS_RR_TYPE_NS, 0, noexpiredabove, expiretop, expiretoplen);
534 	if(!nskey) /* hope the caller has hints to prime or something */
535 		return NULL;
536 	nsdata = (struct packed_rrset_data*)nskey->entry.data;
537 	/* got the NS key, create delegation point */
538 	dp = delegpt_create(region);
539 	if(!dp || !delegpt_set_name(dp, region, nskey->rk.dname)) {
540 		lock_rw_unlock(&nskey->entry.lock);
541 		log_err("find_delegation: out of memory");
542 		return NULL;
543 	}
544 	/* create referral message */
545 	if(msg) {
546 		/* allocate the array to as much as we could need:
547 		 *	NS rrset + DS/NSEC rrset +
548 		 *	A rrset for every NS RR
549 		 *	AAAA rrset for every NS RR
550 		 */
551 		*msg = dns_msg_create(qname, qnamelen, qtype, qclass, region,
552 			2 + nsdata->count*2);
553 		if(!*msg || !dns_msg_authadd(*msg, region, nskey, now)) {
554 			lock_rw_unlock(&nskey->entry.lock);
555 			log_err("find_delegation: out of memory");
556 			return NULL;
557 		}
558 	}
559 	if(!delegpt_rrset_add_ns(dp, region, nskey, 0))
560 		log_err("find_delegation: addns out of memory");
561 	lock_rw_unlock(&nskey->entry.lock); /* first unlock before next lookup*/
562 	/* find and add DS/NSEC (if any) */
563 	if(msg)
564 		find_add_ds(env, region, *msg, dp, now);
565 	/* find and add A entries */
566 	if(!find_add_addrs(env, qclass, region, dp, now, msg))
567 		log_err("find_delegation: addrs out of memory");
568 	return dp;
569 }
570 
571 /** allocate dns_msg from query_info and reply_info */
572 static struct dns_msg*
gen_dns_msg(struct regional * region,struct query_info * q,size_t num)573 gen_dns_msg(struct regional* region, struct query_info* q, size_t num)
574 {
575 	struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
576 		sizeof(struct dns_msg));
577 	if(!msg)
578 		return NULL;
579 	memcpy(&msg->qinfo, q, sizeof(struct query_info));
580 	msg->qinfo.qname = regional_alloc_init(region, q->qname, q->qname_len);
581 	if(!msg->qinfo.qname)
582 		return NULL;
583 	/* allocate replyinfo struct and rrset key array separately */
584 	msg->rep = (struct reply_info*)regional_alloc(region,
585 		sizeof(struct reply_info) - sizeof(struct rrset_ref));
586 	if(!msg->rep)
587 		return NULL;
588 	msg->rep->reason_bogus = LDNS_EDE_NONE;
589 	msg->rep->reason_bogus_str = NULL;
590 	if(num > RR_COUNT_MAX)
591 		return NULL; /* integer overflow protection */
592 	msg->rep->rrsets = (struct ub_packed_rrset_key**)
593 		regional_alloc(region,
594 		num * sizeof(struct ub_packed_rrset_key*));
595 	if(!msg->rep->rrsets)
596 		return NULL;
597 	return msg;
598 }
599 
600 struct dns_msg*
tomsg(struct module_env * env,struct query_info * q,struct reply_info * r,struct regional * region,time_t now,int allow_expired,struct regional * scratch)601 tomsg(struct module_env* env, struct query_info* q, struct reply_info* r,
602 	struct regional* region, time_t now, int allow_expired,
603 	struct regional* scratch)
604 {
605 	struct dns_msg* msg;
606 	size_t i;
607 	int is_expired = 0;
608 	time_t now_control = now;
609 	if(now > r->ttl) {
610 		/* Check if we are allowed to serve expired */
611 		if(!allow_expired || !reply_info_can_answer_expired(r, now))
612 			return NULL;
613 		/* Change the current time so we can pass the below TTL checks when
614 		 * serving expired data. */
615 		now_control = r->ttl - env->cfg->serve_expired_reply_ttl;
616 		is_expired = 1;
617 	}
618 
619 	msg = gen_dns_msg(region, q, r->rrset_count);
620 	if(!msg) return NULL;
621 	msg->rep->flags = r->flags;
622 	msg->rep->qdcount = r->qdcount;
623 	msg->rep->ttl = is_expired
624 		?SERVE_EXPIRED_REPLY_TTL
625 		:r->ttl - now;
626 	if(r->prefetch_ttl > now)
627 		msg->rep->prefetch_ttl = r->prefetch_ttl - now;
628 	else
629 		msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
630 	msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
631 	msg->rep->serve_expired_norec_ttl = 0;
632 	msg->rep->security = r->security;
633 	msg->rep->an_numrrsets = r->an_numrrsets;
634 	msg->rep->ns_numrrsets = r->ns_numrrsets;
635 	msg->rep->ar_numrrsets = r->ar_numrrsets;
636 	msg->rep->rrset_count = r->rrset_count;
637 	msg->rep->authoritative = r->authoritative;
638 	msg->rep->reason_bogus = r->reason_bogus;
639 	if(r->reason_bogus_str) {
640 		msg->rep->reason_bogus_str = regional_strdup(region, r->reason_bogus_str);
641 	}
642 
643 	if(!rrset_array_lock(r->ref, r->rrset_count, now_control)) {
644 		return NULL;
645 	}
646 	if(r->an_numrrsets > 0 && (r->rrsets[0]->rk.type == htons(
647 		LDNS_RR_TYPE_CNAME) || r->rrsets[0]->rk.type == htons(
648 		LDNS_RR_TYPE_DNAME)) && !reply_check_cname_chain(q, r)) {
649 		/* cname chain is now invalid, reconstruct msg */
650 		rrset_array_unlock(r->ref, r->rrset_count);
651 		return NULL;
652 	}
653 	if(r->security == sec_status_secure && !reply_all_rrsets_secure(r)) {
654 		/* message rrsets have changed status, revalidate */
655 		rrset_array_unlock(r->ref, r->rrset_count);
656 		return NULL;
657 	}
658 	for(i=0; i<msg->rep->rrset_count; i++) {
659 		msg->rep->rrsets[i] = packed_rrset_copy_region(r->rrsets[i],
660 			region, now);
661 		if(!msg->rep->rrsets[i]) {
662 			rrset_array_unlock(r->ref, r->rrset_count);
663 			return NULL;
664 		}
665 	}
666 	if(env)
667 		rrset_array_unlock_touch(env->rrset_cache, scratch, r->ref,
668 		r->rrset_count);
669 	else
670 		rrset_array_unlock(r->ref, r->rrset_count);
671 	return msg;
672 }
673 
674 struct dns_msg*
dns_msg_deepcopy_region(struct dns_msg * origin,struct regional * region)675 dns_msg_deepcopy_region(struct dns_msg* origin, struct regional* region)
676 {
677 	size_t i;
678 	struct dns_msg* res = NULL;
679 	res = gen_dns_msg(region, &origin->qinfo, origin->rep->rrset_count);
680 	if(!res) return NULL;
681 	*res->rep = *origin->rep;
682 	if(origin->rep->reason_bogus_str) {
683 		res->rep->reason_bogus_str = regional_strdup(region,
684 			origin->rep->reason_bogus_str);
685 	}
686 	for(i=0; i<res->rep->rrset_count; i++) {
687 		res->rep->rrsets[i] = packed_rrset_copy_region(
688 			origin->rep->rrsets[i], region, 0);
689 		if(!res->rep->rrsets[i]) {
690 			return NULL;
691 		}
692 	}
693 	return res;
694 }
695 
696 /** synthesize RRset-only response from cached RRset item */
697 static struct dns_msg*
rrset_msg(struct ub_packed_rrset_key * rrset,struct regional * region,time_t now,struct query_info * q)698 rrset_msg(struct ub_packed_rrset_key* rrset, struct regional* region,
699 	time_t now, struct query_info* q)
700 {
701 	struct dns_msg* msg;
702 	struct packed_rrset_data* d = (struct packed_rrset_data*)
703 		rrset->entry.data;
704 	if(now > d->ttl)
705 		return NULL;
706 	msg = gen_dns_msg(region, q, 1); /* only the CNAME (or other) RRset */
707 	if(!msg)
708 		return NULL;
709 	msg->rep->flags = BIT_QR; /* reply, no AA, no error */
710         msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
711 	msg->rep->qdcount = 1;
712 	msg->rep->ttl = d->ttl - now;
713 	msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
714 	msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
715 	msg->rep->serve_expired_norec_ttl = 0;
716 	msg->rep->security = sec_status_unchecked;
717 	msg->rep->an_numrrsets = 1;
718 	msg->rep->ns_numrrsets = 0;
719 	msg->rep->ar_numrrsets = 0;
720 	msg->rep->rrset_count = 1;
721 	msg->rep->reason_bogus = LDNS_EDE_NONE;
722 	msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
723 	if(!msg->rep->rrsets[0]) /* copy CNAME */
724 		return NULL;
725 	return msg;
726 }
727 
728 /** synthesize DNAME+CNAME response from cached DNAME item */
729 static struct dns_msg*
synth_dname_msg(struct ub_packed_rrset_key * rrset,struct regional * region,time_t now,struct query_info * q,enum sec_status * sec_status)730 synth_dname_msg(struct ub_packed_rrset_key* rrset, struct regional* region,
731 	time_t now, struct query_info* q, enum sec_status* sec_status)
732 {
733 	struct dns_msg* msg;
734 	struct ub_packed_rrset_key* ck;
735 	struct packed_rrset_data* newd, *d = (struct packed_rrset_data*)
736 		rrset->entry.data;
737 	uint8_t* newname, *dtarg = NULL;
738 	size_t newlen, dtarglen;
739 	if(now > d->ttl)
740 		return NULL;
741 	/* only allow validated (with DNSSEC) DNAMEs used from cache
742 	 * for insecure DNAMEs, query again. */
743 	*sec_status = d->security;
744 	/* return sec status, so the status of the CNAME can be checked
745 	 * by the calling routine. */
746 	msg = gen_dns_msg(region, q, 2); /* DNAME + CNAME RRset */
747 	if(!msg)
748 		return NULL;
749 	msg->rep->flags = BIT_QR; /* reply, no AA, no error */
750         msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
751 	msg->rep->qdcount = 1;
752 	msg->rep->ttl = d->ttl - now;
753 	msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
754 	msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
755 	msg->rep->serve_expired_norec_ttl = 0;
756 	msg->rep->security = sec_status_unchecked;
757 	msg->rep->an_numrrsets = 1;
758 	msg->rep->ns_numrrsets = 0;
759 	msg->rep->ar_numrrsets = 0;
760 	msg->rep->rrset_count = 1;
761 	msg->rep->reason_bogus = LDNS_EDE_NONE;
762 	msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
763 	if(!msg->rep->rrsets[0]) /* copy DNAME */
764 		return NULL;
765 	/* synth CNAME rrset */
766 	get_cname_target(rrset, &dtarg, &dtarglen);
767 	if(!dtarg)
768 		return NULL;
769 	newlen = q->qname_len + dtarglen - rrset->rk.dname_len;
770 	if(newlen > LDNS_MAX_DOMAINLEN) {
771 		msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
772 		return msg;
773 	}
774 	newname = (uint8_t*)regional_alloc(region, newlen);
775 	if(!newname)
776 		return NULL;
777 	/* new name is concatenation of qname front (without DNAME owner)
778 	 * and DNAME target name */
779 	memcpy(newname, q->qname, q->qname_len-rrset->rk.dname_len);
780 	memmove(newname+(q->qname_len-rrset->rk.dname_len), dtarg, dtarglen);
781 	/* create rest of CNAME rrset */
782 	ck = (struct ub_packed_rrset_key*)regional_alloc(region,
783 		sizeof(struct ub_packed_rrset_key));
784 	if(!ck)
785 		return NULL;
786 	memset(&ck->entry, 0, sizeof(ck->entry));
787 	msg->rep->rrsets[1] = ck;
788 	ck->entry.key = ck;
789 	ck->rk.type = htons(LDNS_RR_TYPE_CNAME);
790 	ck->rk.rrset_class = rrset->rk.rrset_class;
791 	ck->rk.flags = 0;
792 	ck->rk.dname = regional_alloc_init(region, q->qname, q->qname_len);
793 	if(!ck->rk.dname)
794 		return NULL;
795 	ck->rk.dname_len = q->qname_len;
796 	ck->entry.hash = rrset_key_hash(&ck->rk);
797 	newd = (struct packed_rrset_data*)regional_alloc_zero(region,
798 		sizeof(struct packed_rrset_data) + sizeof(size_t) +
799 		sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t)
800 		+ newlen);
801 	if(!newd)
802 		return NULL;
803 	ck->entry.data = newd;
804 	newd->ttl = d->ttl - now; /* RFC6672: synth CNAME TTL == DNAME TTL */
805 	newd->count = 1;
806 	newd->rrsig_count = 0;
807 	newd->trust = rrset_trust_ans_noAA;
808 	newd->rr_len = (size_t*)((uint8_t*)newd +
809 		sizeof(struct packed_rrset_data));
810 	newd->rr_len[0] = newlen + sizeof(uint16_t);
811 	packed_rrset_ptr_fixup(newd);
812 	newd->rr_ttl[0] = newd->ttl;
813 	msg->rep->ttl = newd->ttl;
814 	msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(newd->ttl);
815 	msg->rep->serve_expired_ttl = newd->ttl + SERVE_EXPIRED_TTL;
816 	sldns_write_uint16(newd->rr_data[0], newlen);
817 	memmove(newd->rr_data[0] + sizeof(uint16_t), newname, newlen);
818 	msg->rep->an_numrrsets ++;
819 	msg->rep->rrset_count ++;
820 	return msg;
821 }
822 
823 /** Fill TYPE_ANY response with some data from cache */
824 static struct dns_msg*
fill_any(struct module_env * env,uint8_t * qname,size_t qnamelen,uint16_t qtype,uint16_t qclass,struct regional * region)825 fill_any(struct module_env* env,
826 	uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
827 	struct regional* region)
828 {
829 	time_t now = *env->now;
830 	struct dns_msg* msg = NULL;
831 	uint16_t lookup[] = {LDNS_RR_TYPE_A, LDNS_RR_TYPE_AAAA,
832 		LDNS_RR_TYPE_MX, LDNS_RR_TYPE_SOA, LDNS_RR_TYPE_NS,
833 		LDNS_RR_TYPE_DNAME, 0};
834 	int i, num=6; /* number of RR types to look up */
835 	log_assert(lookup[num] == 0);
836 
837 	if(env->cfg->deny_any) {
838 		/* return empty message */
839 		msg = dns_msg_create(qname, qnamelen, qtype, qclass,
840 			region, 0);
841 		if(!msg) {
842 			return NULL;
843 		}
844 		/* set NOTIMPL for RFC 8482 */
845 		msg->rep->flags |= LDNS_RCODE_NOTIMPL;
846 		msg->rep->security = sec_status_indeterminate;
847 		return msg;
848 	}
849 
850 	for(i=0; i<num; i++) {
851 		/* look up this RR for inclusion in type ANY response */
852 		struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
853 			env->rrset_cache, qname, qnamelen, lookup[i],
854 			qclass, 0, now, 0);
855 		struct packed_rrset_data *d;
856 		if(!rrset)
857 			continue;
858 
859 		/* only if rrset from answer section */
860 		d = (struct packed_rrset_data*)rrset->entry.data;
861 		if(d->trust == rrset_trust_add_noAA ||
862 			d->trust == rrset_trust_auth_noAA ||
863 			d->trust == rrset_trust_add_AA ||
864 			d->trust == rrset_trust_auth_AA) {
865 			lock_rw_unlock(&rrset->entry.lock);
866 			continue;
867 		}
868 
869 		/* create msg if none */
870 		if(!msg) {
871 			msg = dns_msg_create(qname, qnamelen, qtype, qclass,
872 				region, (size_t)(num-i));
873 			if(!msg) {
874 				lock_rw_unlock(&rrset->entry.lock);
875 				return NULL;
876 			}
877 		}
878 
879 		/* add RRset to response */
880 		if(!dns_msg_ansadd(msg, region, rrset, now)) {
881 			lock_rw_unlock(&rrset->entry.lock);
882 			return NULL;
883 		}
884 		lock_rw_unlock(&rrset->entry.lock);
885 	}
886 	return msg;
887 }
888 
889 struct dns_msg*
dns_cache_lookup(struct module_env * env,uint8_t * qname,size_t qnamelen,uint16_t qtype,uint16_t qclass,uint16_t flags,struct regional * region,struct regional * scratch,int no_partial,uint8_t * dpname,size_t dpnamelen)890 dns_cache_lookup(struct module_env* env,
891 	uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
892 	uint16_t flags, struct regional* region, struct regional* scratch,
893 	int no_partial, uint8_t* dpname, size_t dpnamelen)
894 {
895 	struct lruhash_entry* e;
896 	struct query_info k;
897 	hashvalue_type h;
898 	time_t now = *env->now;
899 	struct ub_packed_rrset_key* rrset;
900 
901 	/* lookup first, this has both NXdomains and ANSWER responses */
902 	k.qname = qname;
903 	k.qname_len = qnamelen;
904 	k.qtype = qtype;
905 	k.qclass = qclass;
906 	k.local_alias = NULL;
907 	h = query_info_hash(&k, flags);
908 	e = slabhash_lookup(env->msg_cache, h, &k, 0);
909 	if(e) {
910 		struct msgreply_entry* key = (struct msgreply_entry*)e->key;
911 		struct reply_info* data = (struct reply_info*)e->data;
912 		struct dns_msg* msg = tomsg(env, &key->key, data, region, now, 0,
913 			scratch);
914 		if(msg) {
915 			lock_rw_unlock(&e->lock);
916 			return msg;
917 		}
918 		/* could be msg==NULL; due to TTL or not all rrsets available */
919 		lock_rw_unlock(&e->lock);
920 	}
921 
922 	/* see if a DNAME exists. Checked for first, to enforce that DNAMEs
923 	 * are more important, the CNAME is resynthesized and thus
924 	 * consistent with the DNAME */
925 	if(!no_partial &&
926 		(rrset=find_closest_of_type(env, qname, qnamelen, qclass, now,
927 		LDNS_RR_TYPE_DNAME, 1, 0, NULL, 0))) {
928 		/* synthesize a DNAME+CNAME message based on this */
929 		enum sec_status sec_status = sec_status_unchecked;
930 		struct dns_msg* msg = synth_dname_msg(rrset, region, now, &k,
931 			&sec_status);
932 		if(msg) {
933 			struct ub_packed_rrset_key* cname_rrset;
934 			lock_rw_unlock(&rrset->entry.lock);
935 			/* now, after unlocking the DNAME rrset lock,
936 			 * check the sec_status, and see if we need to look
937 			 * up the CNAME record associated before it can
938 			 * be used */
939 			/* normally, only secure DNAMEs allowed from cache*/
940 			if(sec_status == sec_status_secure)
941 				return msg;
942 			/* but if we have a CNAME cached with this name, then we
943 			 * have previously already allowed this name to pass.
944 			 * the next cache lookup is going to fetch that CNAME itself,
945 			 * but it is better to have the (unsigned)DNAME + CNAME in
946 			 * that case */
947 			cname_rrset = rrset_cache_lookup(
948 				env->rrset_cache, qname, qnamelen,
949 				LDNS_RR_TYPE_CNAME, qclass, 0, now, 0);
950 			if(cname_rrset) {
951 				/* CNAME already synthesized by
952 				 * synth_dname_msg routine, so we can
953 				 * straight up return the msg */
954 				lock_rw_unlock(&cname_rrset->entry.lock);
955 				return msg;
956 			}
957 		} else {
958 			lock_rw_unlock(&rrset->entry.lock);
959 		}
960 	}
961 
962 	/* see if we have CNAME for this domain,
963 	 * but not for DS records (which are part of the parent) */
964 	if(!no_partial && qtype != LDNS_RR_TYPE_DS &&
965 	   (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen,
966 		LDNS_RR_TYPE_CNAME, qclass, 0, now, 0))) {
967 		uint8_t* wc = NULL;
968 		size_t wl;
969 		/* if the rrset is not a wildcard expansion, with wcname */
970 		/* because, if we return that CNAME rrset on its own, it is
971 		 * missing the NSEC or NSEC3 proof */
972 		if(!(val_rrset_wildcard(rrset, &wc, &wl) && wc != NULL)) {
973 			struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
974 			if(msg) {
975 				lock_rw_unlock(&rrset->entry.lock);
976 				return msg;
977 			}
978 		}
979 		lock_rw_unlock(&rrset->entry.lock);
980 	}
981 
982 	/* construct DS, DNSKEY messages from rrset cache. */
983 	if((qtype == LDNS_RR_TYPE_DS || qtype == LDNS_RR_TYPE_DNSKEY) &&
984 		(rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen,
985 		qtype, qclass, 0, now, 0))) {
986 		/* if the rrset is from the additional section, and the
987 		 * signatures have fallen off, then do not synthesize a msg
988 		 * instead, allow a full query for signed results to happen.
989 		 * Forego all rrset data from additional section, because
990 		 * some signatures may not be present and cause validation
991 		 * failure.
992 		 */
993 		struct packed_rrset_data *d = (struct packed_rrset_data*)
994 			rrset->entry.data;
995 		if(d->trust != rrset_trust_add_noAA &&
996 			d->trust != rrset_trust_add_AA &&
997 			(qtype == LDNS_RR_TYPE_DS ||
998 				(d->trust != rrset_trust_auth_noAA
999 				&& d->trust != rrset_trust_auth_AA) )) {
1000 			struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
1001 			if(msg) {
1002 				lock_rw_unlock(&rrset->entry.lock);
1003 				return msg;
1004 			}
1005 		}
1006 		lock_rw_unlock(&rrset->entry.lock);
1007 	}
1008 
1009 	/* stop downwards cache search on NXDOMAIN.
1010 	 * Empty nonterminals are NOERROR, so an NXDOMAIN for foo
1011 	 * means bla.foo also does not exist.  The DNSSEC proofs are
1012 	 * the same.  We search upwards for NXDOMAINs. */
1013 	if(env->cfg->harden_below_nxdomain) {
1014 		while(!dname_is_root(k.qname)) {
1015 			if(dpname && dpnamelen
1016 				&& !dname_subdomain_c(k.qname, dpname))
1017 				break; /* no synth nxdomain above the stub */
1018 			dname_remove_label(&k.qname, &k.qname_len);
1019 			h = query_info_hash(&k, flags);
1020 			e = slabhash_lookup(env->msg_cache, h, &k, 0);
1021 			if(!e && k.qtype != LDNS_RR_TYPE_A &&
1022 				env->cfg->qname_minimisation) {
1023 				k.qtype = LDNS_RR_TYPE_A;
1024 				h = query_info_hash(&k, flags);
1025 				e = slabhash_lookup(env->msg_cache, h, &k, 0);
1026 			}
1027 			if(e) {
1028 				struct reply_info* data = (struct reply_info*)e->data;
1029 				struct dns_msg* msg;
1030 				if(FLAGS_GET_RCODE(data->flags) == LDNS_RCODE_NXDOMAIN
1031 					&& data->security == sec_status_secure
1032 					&& (data->an_numrrsets == 0 ||
1033 						ntohs(data->rrsets[0]->rk.type) != LDNS_RR_TYPE_CNAME)
1034 					&& (msg=tomsg(env, &k, data, region, now, 0, scratch))) {
1035 					lock_rw_unlock(&e->lock);
1036 					msg->qinfo.qname=qname;
1037 					msg->qinfo.qname_len=qnamelen;
1038 					/* check that DNSSEC really works out */
1039 					msg->rep->security = sec_status_unchecked;
1040 					iter_scrub_nxdomain(msg);
1041 					return msg;
1042 				}
1043 				lock_rw_unlock(&e->lock);
1044 			}
1045 			k.qtype = qtype;
1046 		}
1047 	}
1048 
1049 	/* fill common RR types for ANY response to avoid requery */
1050 	if(qtype == LDNS_RR_TYPE_ANY) {
1051 		return fill_any(env, qname, qnamelen, qtype, qclass, region);
1052 	}
1053 
1054 	return NULL;
1055 }
1056 
1057 int
dns_cache_store(struct module_env * env,struct query_info * msgqinf,struct reply_info * msgrep,int is_referral,time_t leeway,int pside,struct regional * region,uint32_t flags,time_t qstarttime)1058 dns_cache_store(struct module_env* env, struct query_info* msgqinf,
1059         struct reply_info* msgrep, int is_referral, time_t leeway, int pside,
1060 	struct regional* region, uint32_t flags, time_t qstarttime)
1061 {
1062 	struct reply_info* rep = NULL;
1063 	if(SERVE_EXPIRED) {
1064 		/* We are serving expired records. Before caching, check if a
1065 		 * useful expired record exists. */
1066 		struct msgreply_entry* e = msg_cache_lookup(env,
1067 			msgqinf->qname, msgqinf->qname_len, msgqinf->qtype,
1068 			msgqinf->qclass, flags, 0, 0);
1069 		if(e) {
1070 			struct reply_info* cached = e->entry.data;
1071 			if(cached->ttl < *env->now
1072 				&& reply_info_could_use_expired(cached, *env->now)
1073 				/* If we are validating make sure only
1074 				 * validating modules can update such messages.
1075 				 * In that case don't cache it and let a
1076 				 * subsequent module handle the caching. For
1077 				 * example, the iterator should not replace an
1078 				 * expired secure answer with a fresh unchecked
1079 				 * one and let the validator manage caching. */
1080 				&& cached->security != sec_status_bogus
1081 				&& (env->need_to_validate &&
1082 				msgrep->security == sec_status_unchecked)) {
1083 				verbose(VERB_ALGO, "a validated expired entry "
1084 					"could be overwritten, skip caching "
1085 					"the new message at this stage");
1086 				lock_rw_unlock(&e->entry.lock);
1087 				return 1;
1088 			}
1089 			lock_rw_unlock(&e->entry.lock);
1090 		}
1091 	}
1092 	/* alloc, malloc properly (not in region, like msg is) */
1093 	rep = reply_info_copy(msgrep, env->alloc, NULL);
1094 	if(!rep)
1095 		return 0;
1096 	/* ttl must be relative ;i.e. 0..86400 not  time(0)+86400.
1097 	 * the env->now is added to message and RRsets in this routine. */
1098 	/* the leeway is used to invalidate other rrsets earlier */
1099 	if(is_referral) {
1100 		/* store rrsets */
1101 		struct rrset_ref ref;
1102 		size_t i;
1103 		for(i=0; i<rep->rrset_count; i++) {
1104 			packed_rrset_ttl_add((struct packed_rrset_data*)
1105 				rep->rrsets[i]->entry.data, *env->now);
1106 			ref.key = rep->rrsets[i];
1107 			ref.id = rep->rrsets[i]->id;
1108 			/*ignore ret: it was in the cache, ref updated */
1109 			/* no leeway for typeNS */
1110 			(void)rrset_cache_update(env->rrset_cache, &ref,
1111 				env->alloc,
1112 				((ntohs(ref.key->rk.type)==LDNS_RR_TYPE_NS
1113 				 && !pside) ? qstarttime:*env->now + leeway));
1114 		}
1115 		reply_info_delete(rep, NULL);
1116 		return 1;
1117 	} else {
1118 		/* store msg, and rrsets */
1119 		struct query_info qinf;
1120 		hashvalue_type h;
1121 
1122 		qinf = *msgqinf;
1123 		qinf.qname = memdup(msgqinf->qname, msgqinf->qname_len);
1124 		if(!qinf.qname) {
1125 			reply_info_parsedelete(rep, env->alloc);
1126 			return 0;
1127 		}
1128 		/* fixup flags to be sensible for a reply based on the cache */
1129 		/* this module means that RA is available. It is an answer QR.
1130 		 * Not AA from cache. Not CD in cache (depends on client bit). */
1131 		rep->flags |= (BIT_RA | BIT_QR);
1132 		rep->flags &= ~(BIT_AA | BIT_CD);
1133 		h = query_info_hash(&qinf, (uint16_t)flags);
1134 		dns_cache_store_msg(env, &qinf, h, rep, leeway, pside, msgrep,
1135 			flags, region, qstarttime);
1136 		/* qname is used inside query_info_entrysetup, and set to
1137 		 * NULL. If it has not been used, free it. free(0) is safe. */
1138 		free(qinf.qname);
1139 	}
1140 	return 1;
1141 }
1142 
1143 int
dns_cache_prefetch_adjust(struct module_env * env,struct query_info * qinfo,time_t adjust,uint16_t flags)1144 dns_cache_prefetch_adjust(struct module_env* env, struct query_info* qinfo,
1145         time_t adjust, uint16_t flags)
1146 {
1147 	struct msgreply_entry* msg;
1148 	msg = msg_cache_lookup(env, qinfo->qname, qinfo->qname_len,
1149 		qinfo->qtype, qinfo->qclass, flags, *env->now, 1);
1150 	if(msg) {
1151 		struct reply_info* rep = (struct reply_info*)msg->entry.data;
1152 		if(rep) {
1153 			rep->prefetch_ttl += adjust;
1154 			lock_rw_unlock(&msg->entry.lock);
1155 			return 1;
1156 		}
1157 		lock_rw_unlock(&msg->entry.lock);
1158 	}
1159 	return 0;
1160 }
1161