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