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