]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/services/cache/dns.c
MFV r337020:9443 panic when scrub a v10 pool
[FreeBSD/FreeBSD.git] / contrib / unbound / services / cache / dns.c
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 "validator/val_nsec.h"
44 #include "validator/val_utils.h"
45 #include "services/cache/dns.h"
46 #include "services/cache/rrset.h"
47 #include "util/data/msgreply.h"
48 #include "util/data/packed_rrset.h"
49 #include "util/data/dname.h"
50 #include "util/module.h"
51 #include "util/net_help.h"
52 #include "util/regional.h"
53 #include "util/config_file.h"
54 #include "sldns/sbuffer.h"
55
56 /** store rrsets in the rrset cache. 
57  * @param env: module environment with caches.
58  * @param rep: contains list of rrsets to store.
59  * @param now: current time.
60  * @param leeway: during prefetch how much leeway to update TTLs.
61  *      This makes rrsets (other than type NS) timeout sooner so they get
62  *      updated with a new full TTL.
63  *      Type NS does not get this, because it must not be refreshed from the
64  *      child domain, but keep counting down properly.
65  * @param pside: if from parentside discovered NS, so that its NS is okay
66  *      in a prefetch situation to be updated (without becoming sticky).
67  * @param qrep: update rrsets here if cache is better
68  * @param region: for qrep allocs.
69  */
70 static void
71 store_rrsets(struct module_env* env, struct reply_info* rep, time_t now,
72         time_t leeway, int pside, struct reply_info* qrep,
73         struct regional* region)
74 {
75         size_t i;
76         /* see if rrset already exists in cache, if not insert it. */
77         for(i=0; i<rep->rrset_count; i++) {
78                 rep->ref[i].key = rep->rrsets[i];
79                 rep->ref[i].id = rep->rrsets[i]->id;
80                 /* update ref if it was in the cache */ 
81                 switch(rrset_cache_update(env->rrset_cache, &rep->ref[i],
82                         env->alloc, now + ((ntohs(rep->ref[i].key->rk.type)==
83                         LDNS_RR_TYPE_NS && !pside)?0:leeway))) {
84                 case 0: /* ref unchanged, item inserted */
85                         break;
86                 case 2: /* ref updated, cache is superior */
87                         if(region) {
88                                 struct ub_packed_rrset_key* ck;
89                                 lock_rw_rdlock(&rep->ref[i].key->entry.lock);
90                                 /* if deleted rrset, do not copy it */
91                                 if(rep->ref[i].key->id == 0)
92                                         ck = NULL;
93                                 else    ck = packed_rrset_copy_region(
94                                         rep->ref[i].key, region, now);
95                                 lock_rw_unlock(&rep->ref[i].key->entry.lock);
96                                 if(ck) {
97                                         /* use cached copy if memory allows */
98                                         qrep->rrsets[i] = ck;
99                                 }
100                         }
101                         /* no break: also copy key item */
102                         /* the line below is matched by gcc regex and silences
103                          * the fallthrough warning */
104                         /* fallthrough */
105                 case 1: /* ref updated, item inserted */
106                         rep->rrsets[i] = rep->ref[i].key;
107                 }
108         }
109 }
110
111 /** delete message from message cache */
112 static void
113 msg_cache_remove(struct module_env* env, uint8_t* qname, size_t qnamelen, 
114         uint16_t qtype, uint16_t qclass, uint16_t flags)
115 {
116         struct query_info k;
117         hashvalue_type h;
118
119         k.qname = qname;
120         k.qname_len = qnamelen;
121         k.qtype = qtype;
122         k.qclass = qclass;
123         k.local_alias = NULL;
124         h = query_info_hash(&k, flags);
125         slabhash_remove(env->msg_cache, h, &k);
126 }
127
128 /** remove servfail msg cache entry */
129 static void
130 msg_del_servfail(struct module_env* env, struct query_info* qinfo,
131         uint32_t flags)
132 {
133         struct msgreply_entry* e;
134         /* see if the entry is servfail, and then remove it, so that
135          * lookups move from the cacheresponse stage to the recursionresponse
136          * stage */
137         e = msg_cache_lookup(env, qinfo->qname, qinfo->qname_len,
138                 qinfo->qtype, qinfo->qclass, flags, 0, 0);
139         if(!e) return;
140         /* we don't check for the ttl here, also expired servfail entries
141          * are removed.  If the user uses serve-expired, they would still be
142          * used to answer from cache */
143         if(FLAGS_GET_RCODE(((struct reply_info*)e->entry.data)->flags)
144                 != LDNS_RCODE_SERVFAIL) {
145                 lock_rw_unlock(&e->entry.lock);
146                 return;
147         }
148         lock_rw_unlock(&e->entry.lock);
149         msg_cache_remove(env, qinfo->qname, qinfo->qname_len, qinfo->qtype,
150                 qinfo->qclass, flags);
151 }
152
153 void 
154 dns_cache_store_msg(struct module_env* env, struct query_info* qinfo,
155         hashvalue_type hash, struct reply_info* rep, time_t leeway, int pside,
156         struct reply_info* qrep, uint32_t flags, struct regional* region)
157 {
158         struct msgreply_entry* e;
159         time_t ttl = rep->ttl;
160         size_t i;
161
162         /* store RRsets */
163         for(i=0; i<rep->rrset_count; i++) {
164                 rep->ref[i].key = rep->rrsets[i];
165                 rep->ref[i].id = rep->rrsets[i]->id;
166         }
167
168         /* there was a reply_info_sortref(rep) here but it seems to be
169          * unnecessary, because the cache gets locked per rrset. */
170         reply_info_set_ttls(rep, *env->now);
171         store_rrsets(env, rep, *env->now, leeway, pside, qrep, region);
172         if(ttl == 0 && !(flags & DNSCACHE_STORE_ZEROTTL)) {
173                 /* we do not store the message, but we did store the RRs,
174                  * which could be useful for delegation information */
175                 verbose(VERB_ALGO, "TTL 0: dropped msg from cache");
176                 free(rep);
177                 /* if the message is SERVFAIL in cache, remove that SERVFAIL,
178                  * so that the TTL 0 response can be returned for future
179                  * responses (i.e. don't get answered by the servfail from
180                  * cache, but instead go to recursion to get this TTL0
181                  * response). */
182                 msg_del_servfail(env, qinfo, flags);
183                 return;
184         }
185
186         /* store msg in the cache */
187         reply_info_sortref(rep);
188         if(!(e = query_info_entrysetup(qinfo, rep, hash))) {
189                 log_err("store_msg: malloc failed");
190                 return;
191         }
192         slabhash_insert(env->msg_cache, hash, &e->entry, rep, env->alloc);
193 }
194
195 /** find closest NS or DNAME and returns the rrset (locked) */
196 static struct ub_packed_rrset_key*
197 find_closest_of_type(struct module_env* env, uint8_t* qname, size_t qnamelen, 
198         uint16_t qclass, time_t now, uint16_t searchtype, int stripfront)
199 {
200         struct ub_packed_rrset_key *rrset;
201         uint8_t lablen;
202
203         if(stripfront) {
204                 /* strip off so that DNAMEs have strict subdomain match */
205                 lablen = *qname;
206                 qname += lablen + 1;
207                 qnamelen -= lablen + 1;
208         }
209
210         /* snip off front part of qname until the type is found */
211         while(qnamelen > 0) {
212                 if((rrset = rrset_cache_lookup(env->rrset_cache, qname, 
213                         qnamelen, searchtype, qclass, 0, now, 0)))
214                         return rrset;
215
216                 /* snip off front label */
217                 lablen = *qname;
218                 qname += lablen + 1;
219                 qnamelen -= lablen + 1;
220         }
221         return NULL;
222 }
223
224 /** add addr to additional section */
225 static void
226 addr_to_additional(struct ub_packed_rrset_key* rrset, struct regional* region,
227         struct dns_msg* msg, time_t now)
228 {
229         if((msg->rep->rrsets[msg->rep->rrset_count] = 
230                 packed_rrset_copy_region(rrset, region, now))) {
231                 msg->rep->ar_numrrsets++;
232                 msg->rep->rrset_count++;
233         }
234 }
235
236 /** lookup message in message cache */
237 struct msgreply_entry* 
238 msg_cache_lookup(struct module_env* env, uint8_t* qname, size_t qnamelen, 
239         uint16_t qtype, uint16_t qclass, uint16_t flags, time_t now, int wr)
240 {
241         struct lruhash_entry* e;
242         struct query_info k;
243         hashvalue_type h;
244
245         k.qname = qname;
246         k.qname_len = qnamelen;
247         k.qtype = qtype;
248         k.qclass = qclass;
249         k.local_alias = NULL;
250         h = query_info_hash(&k, flags);
251         e = slabhash_lookup(env->msg_cache, h, &k, wr);
252
253         if(!e) return NULL;
254         if( now > ((struct reply_info*)e->data)->ttl ) {
255                 lock_rw_unlock(&e->lock);
256                 return NULL;
257         }
258         return (struct msgreply_entry*)e->key;
259 }
260
261 /** find and add A and AAAA records for nameservers in delegpt */
262 static int
263 find_add_addrs(struct module_env* env, uint16_t qclass, 
264         struct regional* region, struct delegpt* dp, time_t now, 
265         struct dns_msg** msg)
266 {
267         struct delegpt_ns* ns;
268         struct msgreply_entry* neg;
269         struct ub_packed_rrset_key* akey;
270         for(ns = dp->nslist; ns; ns = ns->next) {
271                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
272                         ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
273                 if(akey) {
274                         if(!delegpt_add_rrset_A(dp, region, akey, 0)) {
275                                 lock_rw_unlock(&akey->entry.lock);
276                                 return 0;
277                         }
278                         if(msg)
279                                 addr_to_additional(akey, region, *msg, now);
280                         lock_rw_unlock(&akey->entry.lock);
281                 } else {
282                         /* BIT_CD on false because delegpt lookup does
283                          * not use dns64 translation */
284                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
285                                 LDNS_RR_TYPE_A, qclass, 0, now, 0);
286                         if(neg) {
287                                 delegpt_add_neg_msg(dp, neg);
288                                 lock_rw_unlock(&neg->entry.lock);
289                         }
290                 }
291                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
292                         ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
293                 if(akey) {
294                         if(!delegpt_add_rrset_AAAA(dp, region, akey, 0)) {
295                                 lock_rw_unlock(&akey->entry.lock);
296                                 return 0;
297                         }
298                         if(msg)
299                                 addr_to_additional(akey, region, *msg, now);
300                         lock_rw_unlock(&akey->entry.lock);
301                 } else {
302                         /* BIT_CD on false because delegpt lookup does
303                          * not use dns64 translation */
304                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
305                                 LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
306                         if(neg) {
307                                 delegpt_add_neg_msg(dp, neg);
308                                 lock_rw_unlock(&neg->entry.lock);
309                         }
310                 }
311         }
312         return 1;
313 }
314
315 /** find and add A and AAAA records for missing nameservers in delegpt */
316 int
317 cache_fill_missing(struct module_env* env, uint16_t qclass, 
318         struct regional* region, struct delegpt* dp)
319 {
320         struct delegpt_ns* ns;
321         struct msgreply_entry* neg;
322         struct ub_packed_rrset_key* akey;
323         time_t now = *env->now;
324         for(ns = dp->nslist; ns; ns = ns->next) {
325                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
326                         ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
327                 if(akey) {
328                         if(!delegpt_add_rrset_A(dp, region, akey, ns->lame)) {
329                                 lock_rw_unlock(&akey->entry.lock);
330                                 return 0;
331                         }
332                         log_nametypeclass(VERB_ALGO, "found in cache",
333                                 ns->name, LDNS_RR_TYPE_A, qclass);
334                         lock_rw_unlock(&akey->entry.lock);
335                 } else {
336                         /* BIT_CD on false because delegpt lookup does
337                          * not use dns64 translation */
338                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
339                                 LDNS_RR_TYPE_A, qclass, 0, now, 0);
340                         if(neg) {
341                                 delegpt_add_neg_msg(dp, neg);
342                                 lock_rw_unlock(&neg->entry.lock);
343                         }
344                 }
345                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
346                         ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
347                 if(akey) {
348                         if(!delegpt_add_rrset_AAAA(dp, region, akey, ns->lame)) {
349                                 lock_rw_unlock(&akey->entry.lock);
350                                 return 0;
351                         }
352                         log_nametypeclass(VERB_ALGO, "found in cache",
353                                 ns->name, LDNS_RR_TYPE_AAAA, qclass);
354                         lock_rw_unlock(&akey->entry.lock);
355                 } else {
356                         /* BIT_CD on false because delegpt lookup does
357                          * not use dns64 translation */
358                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
359                                 LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
360                         if(neg) {
361                                 delegpt_add_neg_msg(dp, neg);
362                                 lock_rw_unlock(&neg->entry.lock);
363                         }
364                 }
365         }
366         return 1;
367 }
368
369 /** find and add DS or NSEC to delegation msg */
370 static void
371 find_add_ds(struct module_env* env, struct regional* region, 
372         struct dns_msg* msg, struct delegpt* dp, time_t now)
373 {
374         /* Lookup the DS or NSEC at the delegation point. */
375         struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
376                 env->rrset_cache, dp->name, dp->namelen, LDNS_RR_TYPE_DS, 
377                 msg->qinfo.qclass, 0, now, 0);
378         if(!rrset) {
379                 /* NOTE: this won't work for alternate NSEC schemes 
380                  *      (opt-in, NSEC3) */
381                 rrset = rrset_cache_lookup(env->rrset_cache, dp->name, 
382                         dp->namelen, LDNS_RR_TYPE_NSEC, msg->qinfo.qclass, 
383                         0, now, 0);
384                 /* Note: the PACKED_RRSET_NSEC_AT_APEX flag is not used.
385                  * since this is a referral, we need the NSEC at the parent
386                  * side of the zone cut, not the NSEC at apex side. */
387                 if(rrset && nsec_has_type(rrset, LDNS_RR_TYPE_DS)) {
388                         lock_rw_unlock(&rrset->entry.lock);
389                         rrset = NULL; /* discard wrong NSEC */
390                 }
391         }
392         if(rrset) {
393                 /* add it to auth section. This is the second rrset. */
394                 if((msg->rep->rrsets[msg->rep->rrset_count] = 
395                         packed_rrset_copy_region(rrset, region, now))) {
396                         msg->rep->ns_numrrsets++;
397                         msg->rep->rrset_count++;
398                 }
399                 lock_rw_unlock(&rrset->entry.lock);
400         }
401 }
402
403 struct dns_msg*
404 dns_msg_create(uint8_t* qname, size_t qnamelen, uint16_t qtype, 
405         uint16_t qclass, struct regional* region, size_t capacity)
406 {
407         struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
408                 sizeof(struct dns_msg));
409         if(!msg)
410                 return NULL;
411         msg->qinfo.qname = regional_alloc_init(region, qname, qnamelen);
412         if(!msg->qinfo.qname)
413                 return NULL;
414         msg->qinfo.qname_len = qnamelen;
415         msg->qinfo.qtype = qtype;
416         msg->qinfo.qclass = qclass;
417         msg->qinfo.local_alias = NULL;
418         /* non-packed reply_info, because it needs to grow the array */
419         msg->rep = (struct reply_info*)regional_alloc_zero(region, 
420                 sizeof(struct reply_info)-sizeof(struct rrset_ref));
421         if(!msg->rep)
422                 return NULL;
423         if(capacity > RR_COUNT_MAX)
424                 return NULL; /* integer overflow protection */
425         msg->rep->flags = BIT_QR; /* with QR, no AA */
426         msg->rep->qdcount = 1;
427         msg->rep->rrsets = (struct ub_packed_rrset_key**)
428                 regional_alloc(region, 
429                 capacity*sizeof(struct ub_packed_rrset_key*));
430         if(!msg->rep->rrsets)
431                 return NULL;
432         return msg;
433 }
434
435 int
436 dns_msg_authadd(struct dns_msg* msg, struct regional* region, 
437         struct ub_packed_rrset_key* rrset, time_t now)
438 {
439         if(!(msg->rep->rrsets[msg->rep->rrset_count++] = 
440                 packed_rrset_copy_region(rrset, region, now)))
441                 return 0;
442         msg->rep->ns_numrrsets++;
443         return 1;
444 }
445
446 int
447 dns_msg_ansadd(struct dns_msg* msg, struct regional* region, 
448         struct ub_packed_rrset_key* rrset, time_t now)
449 {
450         if(!(msg->rep->rrsets[msg->rep->rrset_count++] = 
451                 packed_rrset_copy_region(rrset, region, now)))
452                 return 0;
453         msg->rep->an_numrrsets++;
454         return 1;
455 }
456
457 struct delegpt* 
458 dns_cache_find_delegation(struct module_env* env, uint8_t* qname, 
459         size_t qnamelen, uint16_t qtype, uint16_t qclass, 
460         struct regional* region, struct dns_msg** msg, time_t now)
461 {
462         /* try to find closest NS rrset */
463         struct ub_packed_rrset_key* nskey;
464         struct packed_rrset_data* nsdata;
465         struct delegpt* dp;
466
467         nskey = find_closest_of_type(env, qname, qnamelen, qclass, now,
468                 LDNS_RR_TYPE_NS, 0);
469         if(!nskey) /* hope the caller has hints to prime or something */
470                 return NULL;
471         nsdata = (struct packed_rrset_data*)nskey->entry.data;
472         /* got the NS key, create delegation point */
473         dp = delegpt_create(region);
474         if(!dp || !delegpt_set_name(dp, region, nskey->rk.dname)) {
475                 lock_rw_unlock(&nskey->entry.lock);
476                 log_err("find_delegation: out of memory");
477                 return NULL;
478         }
479         /* create referral message */
480         if(msg) {
481                 /* allocate the array to as much as we could need:
482                  *      NS rrset + DS/NSEC rrset +
483                  *      A rrset for every NS RR
484                  *      AAAA rrset for every NS RR
485                  */
486                 *msg = dns_msg_create(qname, qnamelen, qtype, qclass, region, 
487                         2 + nsdata->count*2);
488                 if(!*msg || !dns_msg_authadd(*msg, region, nskey, now)) {
489                         lock_rw_unlock(&nskey->entry.lock);
490                         log_err("find_delegation: out of memory");
491                         return NULL;
492                 }
493         }
494         if(!delegpt_rrset_add_ns(dp, region, nskey, 0))
495                 log_err("find_delegation: addns out of memory");
496         lock_rw_unlock(&nskey->entry.lock); /* first unlock before next lookup*/
497         /* find and add DS/NSEC (if any) */
498         if(msg)
499                 find_add_ds(env, region, *msg, dp, now);
500         /* find and add A entries */
501         if(!find_add_addrs(env, qclass, region, dp, now, msg))
502                 log_err("find_delegation: addrs out of memory");
503         return dp;
504 }
505
506 /** allocate dns_msg from query_info and reply_info */
507 static struct dns_msg*
508 gen_dns_msg(struct regional* region, struct query_info* q, size_t num)
509 {
510         struct dns_msg* msg = (struct dns_msg*)regional_alloc(region, 
511                 sizeof(struct dns_msg));
512         if(!msg)
513                 return NULL;
514         memcpy(&msg->qinfo, q, sizeof(struct query_info));
515         msg->qinfo.qname = regional_alloc_init(region, q->qname, q->qname_len);
516         if(!msg->qinfo.qname)
517                 return NULL;
518         /* allocate replyinfo struct and rrset key array separately */
519         msg->rep = (struct reply_info*)regional_alloc(region,
520                 sizeof(struct reply_info) - sizeof(struct rrset_ref));
521         if(!msg->rep)
522                 return NULL;
523         if(num > RR_COUNT_MAX)
524                 return NULL; /* integer overflow protection */
525         msg->rep->rrsets = (struct ub_packed_rrset_key**)
526                 regional_alloc(region,
527                 num * sizeof(struct ub_packed_rrset_key*));
528         if(!msg->rep->rrsets)
529                 return NULL;
530         return msg;
531 }
532
533 struct dns_msg*
534 tomsg(struct module_env* env, struct query_info* q, struct reply_info* r, 
535         struct regional* region, time_t now, struct regional* scratch)
536 {
537         struct dns_msg* msg;
538         size_t i;
539         if(now > r->ttl)
540                 return NULL;
541         msg = gen_dns_msg(region, q, r->rrset_count);
542         if(!msg)
543                 return NULL;
544         msg->rep->flags = r->flags;
545         msg->rep->qdcount = r->qdcount;
546         msg->rep->ttl = r->ttl - now;
547         if(r->prefetch_ttl > now)
548                 msg->rep->prefetch_ttl = r->prefetch_ttl - now;
549         else    msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
550         msg->rep->security = r->security;
551         msg->rep->an_numrrsets = r->an_numrrsets;
552         msg->rep->ns_numrrsets = r->ns_numrrsets;
553         msg->rep->ar_numrrsets = r->ar_numrrsets;
554         msg->rep->rrset_count = r->rrset_count;
555         msg->rep->authoritative = r->authoritative;
556         if(!rrset_array_lock(r->ref, r->rrset_count, now))
557                 return NULL;
558         if(r->an_numrrsets > 0 && (r->rrsets[0]->rk.type == htons(
559                 LDNS_RR_TYPE_CNAME) || r->rrsets[0]->rk.type == htons(
560                 LDNS_RR_TYPE_DNAME)) && !reply_check_cname_chain(q, r)) {
561                 /* cname chain is now invalid, reconstruct msg */
562                 rrset_array_unlock(r->ref, r->rrset_count);
563                 return NULL;
564         }
565         if(r->security == sec_status_secure && !reply_all_rrsets_secure(r)) {
566                 /* message rrsets have changed status, revalidate */
567                 rrset_array_unlock(r->ref, r->rrset_count);
568                 return NULL;
569         }
570         for(i=0; i<msg->rep->rrset_count; i++) {
571                 msg->rep->rrsets[i] = packed_rrset_copy_region(r->rrsets[i], 
572                         region, now);
573                 if(!msg->rep->rrsets[i]) {
574                         rrset_array_unlock(r->ref, r->rrset_count);
575                         return NULL;
576                 }
577         }
578         if(env)
579                 rrset_array_unlock_touch(env->rrset_cache, scratch, r->ref, 
580                 r->rrset_count);
581         else
582                 rrset_array_unlock(r->ref, r->rrset_count);
583         return msg;
584 }
585
586 /** synthesize RRset-only response from cached RRset item */
587 static struct dns_msg*
588 rrset_msg(struct ub_packed_rrset_key* rrset, struct regional* region, 
589         time_t now, struct query_info* q)
590 {
591         struct dns_msg* msg;
592         struct packed_rrset_data* d = (struct packed_rrset_data*)
593                 rrset->entry.data;
594         if(now > d->ttl)
595                 return NULL;
596         msg = gen_dns_msg(region, q, 1); /* only the CNAME (or other) RRset */
597         if(!msg)
598                 return NULL;
599         msg->rep->flags = BIT_QR; /* reply, no AA, no error */
600         msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
601         msg->rep->qdcount = 1;
602         msg->rep->ttl = d->ttl - now;
603         msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
604         msg->rep->security = sec_status_unchecked;
605         msg->rep->an_numrrsets = 1;
606         msg->rep->ns_numrrsets = 0;
607         msg->rep->ar_numrrsets = 0;
608         msg->rep->rrset_count = 1;
609         msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
610         if(!msg->rep->rrsets[0]) /* copy CNAME */
611                 return NULL;
612         return msg;
613 }
614
615 /** synthesize DNAME+CNAME response from cached DNAME item */
616 static struct dns_msg*
617 synth_dname_msg(struct ub_packed_rrset_key* rrset, struct regional* region, 
618         time_t now, struct query_info* q, enum sec_status* sec_status)
619 {
620         struct dns_msg* msg;
621         struct ub_packed_rrset_key* ck;
622         struct packed_rrset_data* newd, *d = (struct packed_rrset_data*)
623                 rrset->entry.data;
624         uint8_t* newname, *dtarg = NULL;
625         size_t newlen, dtarglen;
626         if(now > d->ttl)
627                 return NULL;
628         /* only allow validated (with DNSSEC) DNAMEs used from cache 
629          * for insecure DNAMEs, query again. */
630         *sec_status = d->security;
631         /* return sec status, so the status of the CNAME can be checked
632          * by the calling routine. */
633         msg = gen_dns_msg(region, q, 2); /* DNAME + CNAME RRset */
634         if(!msg)
635                 return NULL;
636         msg->rep->flags = BIT_QR; /* reply, no AA, no error */
637         msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
638         msg->rep->qdcount = 1;
639         msg->rep->ttl = d->ttl - now;
640         msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
641         msg->rep->security = sec_status_unchecked;
642         msg->rep->an_numrrsets = 1;
643         msg->rep->ns_numrrsets = 0;
644         msg->rep->ar_numrrsets = 0;
645         msg->rep->rrset_count = 1;
646         msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
647         if(!msg->rep->rrsets[0]) /* copy DNAME */
648                 return NULL;
649         /* synth CNAME rrset */
650         get_cname_target(rrset, &dtarg, &dtarglen);
651         if(!dtarg)
652                 return NULL;
653         newlen = q->qname_len + dtarglen - rrset->rk.dname_len;
654         if(newlen > LDNS_MAX_DOMAINLEN) {
655                 msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
656                 return msg;
657         }
658         newname = (uint8_t*)regional_alloc(region, newlen);
659         if(!newname)
660                 return NULL;
661         /* new name is concatenation of qname front (without DNAME owner)
662          * and DNAME target name */
663         memcpy(newname, q->qname, q->qname_len-rrset->rk.dname_len);
664         memmove(newname+(q->qname_len-rrset->rk.dname_len), dtarg, dtarglen);
665         /* create rest of CNAME rrset */
666         ck = (struct ub_packed_rrset_key*)regional_alloc(region, 
667                 sizeof(struct ub_packed_rrset_key));
668         if(!ck)
669                 return NULL;
670         memset(&ck->entry, 0, sizeof(ck->entry));
671         msg->rep->rrsets[1] = ck;
672         ck->entry.key = ck;
673         ck->rk.type = htons(LDNS_RR_TYPE_CNAME);
674         ck->rk.rrset_class = rrset->rk.rrset_class;
675         ck->rk.flags = 0;
676         ck->rk.dname = regional_alloc_init(region, q->qname, q->qname_len);
677         if(!ck->rk.dname)
678                 return NULL;
679         ck->rk.dname_len = q->qname_len;
680         ck->entry.hash = rrset_key_hash(&ck->rk);
681         newd = (struct packed_rrset_data*)regional_alloc_zero(region,
682                 sizeof(struct packed_rrset_data) + sizeof(size_t) + 
683                 sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t) 
684                 + newlen);
685         if(!newd)
686                 return NULL;
687         ck->entry.data = newd;
688         newd->ttl = 0; /* 0 for synthesized CNAME TTL */
689         newd->count = 1;
690         newd->rrsig_count = 0;
691         newd->trust = rrset_trust_ans_noAA;
692         newd->rr_len = (size_t*)((uint8_t*)newd + 
693                 sizeof(struct packed_rrset_data));
694         newd->rr_len[0] = newlen + sizeof(uint16_t);
695         packed_rrset_ptr_fixup(newd);
696         newd->rr_ttl[0] = newd->ttl;
697         msg->rep->ttl = newd->ttl;
698         msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(newd->ttl);
699         sldns_write_uint16(newd->rr_data[0], newlen);
700         memmove(newd->rr_data[0] + sizeof(uint16_t), newname, newlen);
701         msg->rep->an_numrrsets ++;
702         msg->rep->rrset_count ++;
703         return msg;
704 }
705
706 /** Fill TYPE_ANY response with some data from cache */
707 static struct dns_msg*
708 fill_any(struct module_env* env,
709         uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
710         struct regional* region)
711 {
712         time_t now = *env->now;
713         struct dns_msg* msg = NULL;
714         uint16_t lookup[] = {LDNS_RR_TYPE_A, LDNS_RR_TYPE_AAAA,
715                 LDNS_RR_TYPE_MX, LDNS_RR_TYPE_SOA, LDNS_RR_TYPE_NS,
716                 LDNS_RR_TYPE_DNAME, 0};
717         int i, num=6; /* number of RR types to look up */
718         log_assert(lookup[num] == 0);
719
720         for(i=0; i<num; i++) {
721                 /* look up this RR for inclusion in type ANY response */
722                 struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
723                         env->rrset_cache, qname, qnamelen, lookup[i],
724                         qclass, 0, now, 0);
725                 struct packed_rrset_data *d;
726                 if(!rrset)
727                         continue;
728
729                 /* only if rrset from answer section */
730                 d = (struct packed_rrset_data*)rrset->entry.data;
731                 if(d->trust == rrset_trust_add_noAA ||
732                         d->trust == rrset_trust_auth_noAA ||
733                         d->trust == rrset_trust_add_AA ||
734                         d->trust == rrset_trust_auth_AA) {
735                         lock_rw_unlock(&rrset->entry.lock);
736                         continue;
737                 }
738
739                 /* create msg if none */
740                 if(!msg) {
741                         msg = dns_msg_create(qname, qnamelen, qtype, qclass,
742                                 region, (size_t)(num-i));
743                         if(!msg) {
744                                 lock_rw_unlock(&rrset->entry.lock);
745                                 return NULL;
746                         }
747                 }
748
749                 /* add RRset to response */
750                 if(!dns_msg_ansadd(msg, region, rrset, now)) {
751                         lock_rw_unlock(&rrset->entry.lock);
752                         return NULL;
753                 }
754                 lock_rw_unlock(&rrset->entry.lock);
755         }
756         return msg;
757 }
758
759 struct dns_msg* 
760 dns_cache_lookup(struct module_env* env,
761         uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
762         uint16_t flags, struct regional* region, struct regional* scratch,
763         int no_partial)
764 {
765         struct lruhash_entry* e;
766         struct query_info k;
767         hashvalue_type h;
768         time_t now = *env->now;
769         struct ub_packed_rrset_key* rrset;
770
771         /* lookup first, this has both NXdomains and ANSWER responses */
772         k.qname = qname;
773         k.qname_len = qnamelen;
774         k.qtype = qtype;
775         k.qclass = qclass;
776         k.local_alias = NULL;
777         h = query_info_hash(&k, flags);
778         e = slabhash_lookup(env->msg_cache, h, &k, 0);
779         if(e) {
780                 struct msgreply_entry* key = (struct msgreply_entry*)e->key;
781                 struct reply_info* data = (struct reply_info*)e->data;
782                 struct dns_msg* msg = tomsg(env, &key->key, data, region, now, 
783                         scratch);
784                 if(msg) {
785                         lock_rw_unlock(&e->lock);
786                         return msg;
787                 }
788                 /* could be msg==NULL; due to TTL or not all rrsets available */
789                 lock_rw_unlock(&e->lock);
790         }
791
792         /* see if a DNAME exists. Checked for first, to enforce that DNAMEs
793          * are more important, the CNAME is resynthesized and thus 
794          * consistent with the DNAME */
795         if(!no_partial &&
796                 (rrset=find_closest_of_type(env, qname, qnamelen, qclass, now,
797                 LDNS_RR_TYPE_DNAME, 1))) {
798                 /* synthesize a DNAME+CNAME message based on this */
799                 enum sec_status sec_status = sec_status_unchecked;
800                 struct dns_msg* msg = synth_dname_msg(rrset, region, now, &k,
801                         &sec_status);
802                 if(msg) {
803                         struct ub_packed_rrset_key* cname_rrset;
804                         lock_rw_unlock(&rrset->entry.lock);
805                         /* now, after unlocking the DNAME rrset lock,
806                          * check the sec_status, and see if we need to look
807                          * up the CNAME record associated before it can
808                          * be used */
809                         /* normally, only secure DNAMEs allowed from cache*/
810                         if(sec_status == sec_status_secure)
811                                 return msg;
812                         /* but if we have a CNAME cached with this name, then we
813                          * have previously already allowed this name to pass.
814                          * the next cache lookup is going to fetch that CNAME itself,
815                          * but it is better to have the (unsigned)DNAME + CNAME in
816                          * that case */
817                         cname_rrset = rrset_cache_lookup(
818                                 env->rrset_cache, qname, qnamelen,
819                                 LDNS_RR_TYPE_CNAME, qclass, 0, now, 0);
820                         if(cname_rrset) {
821                                 /* CNAME already synthesized by
822                                  * synth_dname_msg routine, so we can
823                                  * straight up return the msg */
824                                 lock_rw_unlock(&cname_rrset->entry.lock);
825                                 return msg;
826                         }
827                 } else {
828                         lock_rw_unlock(&rrset->entry.lock);
829                 }
830         }
831
832         /* see if we have CNAME for this domain,
833          * but not for DS records (which are part of the parent) */
834         if(!no_partial && qtype != LDNS_RR_TYPE_DS &&
835            (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen, 
836                 LDNS_RR_TYPE_CNAME, qclass, 0, now, 0))) {
837                 uint8_t* wc = NULL;
838                 size_t wl;
839                 /* if the rrset is not a wildcard expansion, with wcname */
840                 /* because, if we return that CNAME rrset on its own, it is
841                  * missing the NSEC or NSEC3 proof */
842                 if(!(val_rrset_wildcard(rrset, &wc, &wl) && wc != NULL)) {
843                         struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
844                         if(msg) {
845                                 lock_rw_unlock(&rrset->entry.lock);
846                                 return msg;
847                         }
848                 }
849                 lock_rw_unlock(&rrset->entry.lock);
850         }
851
852         /* construct DS, DNSKEY, DLV messages from rrset cache. */
853         if((qtype == LDNS_RR_TYPE_DS || qtype == LDNS_RR_TYPE_DNSKEY ||
854                 qtype == LDNS_RR_TYPE_DLV) &&
855                 (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen, 
856                 qtype, qclass, 0, now, 0))) {
857                 /* if the rrset is from the additional section, and the
858                  * signatures have fallen off, then do not synthesize a msg
859                  * instead, allow a full query for signed results to happen.
860                  * Forego all rrset data from additional section, because
861                  * some signatures may not be present and cause validation
862                  * failure.
863                  */
864                 struct packed_rrset_data *d = (struct packed_rrset_data*)
865                         rrset->entry.data;
866                 if(d->trust != rrset_trust_add_noAA && 
867                         d->trust != rrset_trust_add_AA && 
868                         (qtype == LDNS_RR_TYPE_DS || 
869                                 (d->trust != rrset_trust_auth_noAA 
870                                 && d->trust != rrset_trust_auth_AA) )) {
871                         struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
872                         if(msg) {
873                                 lock_rw_unlock(&rrset->entry.lock);
874                                 return msg;
875                         }
876                 }
877                 lock_rw_unlock(&rrset->entry.lock);
878         }
879
880         /* stop downwards cache search on NXDOMAIN.
881          * Empty nonterminals are NOERROR, so an NXDOMAIN for foo
882          * means bla.foo also does not exist.  The DNSSEC proofs are
883          * the same.  We search upwards for NXDOMAINs. */
884         if(env->cfg->harden_below_nxdomain)
885             while(!dname_is_root(k.qname)) {
886                 dname_remove_label(&k.qname, &k.qname_len);
887                 h = query_info_hash(&k, flags);
888                 e = slabhash_lookup(env->msg_cache, h, &k, 0);
889                 if(!e && k.qtype != LDNS_RR_TYPE_A &&
890                         env->cfg->qname_minimisation) {
891                         k.qtype = LDNS_RR_TYPE_A;
892                         h = query_info_hash(&k, flags);
893                         e = slabhash_lookup(env->msg_cache, h, &k, 0);
894                 }
895                 if(e) {
896                         struct reply_info* data = (struct reply_info*)e->data;
897                         struct dns_msg* msg;
898                         if(FLAGS_GET_RCODE(data->flags) == LDNS_RCODE_NXDOMAIN
899                           && data->security == sec_status_secure
900                           && (msg=tomsg(env, &k, data, region, now, scratch))){
901                                 lock_rw_unlock(&e->lock);
902                                 msg->qinfo.qname=qname;
903                                 msg->qinfo.qname_len=qnamelen;
904                                 /* check that DNSSEC really works out */
905                                 msg->rep->security = sec_status_unchecked;
906                                 return msg;
907                         }
908                         lock_rw_unlock(&e->lock);
909                 }
910                 k.qtype = qtype;
911             }
912
913         /* fill common RR types for ANY response to avoid requery */
914         if(qtype == LDNS_RR_TYPE_ANY) {
915                 return fill_any(env, qname, qnamelen, qtype, qclass, region);
916         }
917
918         return NULL;
919 }
920
921 int
922 dns_cache_store(struct module_env* env, struct query_info* msgqinf,
923         struct reply_info* msgrep, int is_referral, time_t leeway, int pside,
924         struct regional* region, uint32_t flags)
925 {
926         struct reply_info* rep = NULL;
927         /* alloc, malloc properly (not in region, like msg is) */
928         rep = reply_info_copy(msgrep, env->alloc, NULL);
929         if(!rep)
930                 return 0;
931         /* ttl must be relative ;i.e. 0..86400 not  time(0)+86400.
932          * the env->now is added to message and RRsets in this routine. */
933         /* the leeway is used to invalidate other rrsets earlier */
934
935         if(is_referral) {
936                 /* store rrsets */
937                 struct rrset_ref ref;
938                 size_t i;
939                 for(i=0; i<rep->rrset_count; i++) {
940                         packed_rrset_ttl_add((struct packed_rrset_data*)
941                                 rep->rrsets[i]->entry.data, *env->now);
942                         ref.key = rep->rrsets[i];
943                         ref.id = rep->rrsets[i]->id;
944                         /*ignore ret: it was in the cache, ref updated */
945                         /* no leeway for typeNS */
946                         (void)rrset_cache_update(env->rrset_cache, &ref, 
947                                 env->alloc, *env->now + 
948                                 ((ntohs(ref.key->rk.type)==LDNS_RR_TYPE_NS
949                                  && !pside) ? 0:leeway));
950                 }
951                 free(rep);
952                 return 1;
953         } else {
954                 /* store msg, and rrsets */
955                 struct query_info qinf;
956                 hashvalue_type h;
957
958                 qinf = *msgqinf;
959                 qinf.qname = memdup(msgqinf->qname, msgqinf->qname_len);
960                 if(!qinf.qname) {
961                         reply_info_parsedelete(rep, env->alloc);
962                         return 0;
963                 }
964                 /* fixup flags to be sensible for a reply based on the cache */
965                 /* this module means that RA is available. It is an answer QR. 
966                  * Not AA from cache. Not CD in cache (depends on client bit). */
967                 rep->flags |= (BIT_RA | BIT_QR);
968                 rep->flags &= ~(BIT_AA | BIT_CD);
969                 h = query_info_hash(&qinf, (uint16_t)flags);
970                 dns_cache_store_msg(env, &qinf, h, rep, leeway, pside, msgrep,
971                         flags, region);
972                 /* qname is used inside query_info_entrysetup, and set to 
973                  * NULL. If it has not been used, free it. free(0) is safe. */
974                 free(qinf.qname);
975         }
976         return 1;
977 }
978
979 int 
980 dns_cache_prefetch_adjust(struct module_env* env, struct query_info* qinfo,
981         time_t adjust, uint16_t flags)
982 {
983         struct msgreply_entry* msg;
984         msg = msg_cache_lookup(env, qinfo->qname, qinfo->qname_len,
985                 qinfo->qtype, qinfo->qclass, flags, *env->now, 1);
986         if(msg) {
987                 struct reply_info* rep = (struct reply_info*)msg->entry.data;
988                 if(rep) {
989                         rep->prefetch_ttl += adjust;
990                         lock_rw_unlock(&msg->entry.lock);
991                         return 1;
992                 }
993                 lock_rw_unlock(&msg->entry.lock);
994         }
995         return 0;
996 }