]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/unbound/services/cache/dns.c
MFH (r266114, r266138): upgrade to latest ldns and unbound
[FreeBSD/stable/10.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 "ldns/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_t 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, time_t now, int wr)
188 {
189         struct lruhash_entry* e;
190         struct query_info k;
191         hashvalue_t h;
192
193         k.qname = qname;
194         k.qname_len = qnamelen;
195         k.qtype = qtype;
196         k.qclass = qclass;
197         h = query_info_hash(&k);
198         e = slabhash_lookup(env->msg_cache, h, &k, wr);
199
200         if(!e) return NULL;
201         if( now > ((struct reply_info*)e->data)->ttl ) {
202                 lock_rw_unlock(&e->lock);
203                 return NULL;
204         }
205         return (struct msgreply_entry*)e->key;
206 }
207
208 /** find and add A and AAAA records for nameservers in delegpt */
209 static int
210 find_add_addrs(struct module_env* env, uint16_t qclass, 
211         struct regional* region, struct delegpt* dp, time_t now, 
212         struct dns_msg** msg)
213 {
214         struct delegpt_ns* ns;
215         struct msgreply_entry* neg;
216         struct ub_packed_rrset_key* akey;
217         for(ns = dp->nslist; ns; ns = ns->next) {
218                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
219                         ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
220                 if(akey) {
221                         if(!delegpt_add_rrset_A(dp, region, akey, 0)) {
222                                 lock_rw_unlock(&akey->entry.lock);
223                                 return 0;
224                         }
225                         if(msg)
226                                 addr_to_additional(akey, region, *msg, now);
227                         lock_rw_unlock(&akey->entry.lock);
228                 } else {
229                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
230                                 LDNS_RR_TYPE_A, qclass, now, 0);
231                         if(neg) {
232                                 delegpt_add_neg_msg(dp, neg);
233                                 lock_rw_unlock(&neg->entry.lock);
234                         }
235                 }
236                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
237                         ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
238                 if(akey) {
239                         if(!delegpt_add_rrset_AAAA(dp, region, akey, 0)) {
240                                 lock_rw_unlock(&akey->entry.lock);
241                                 return 0;
242                         }
243                         if(msg)
244                                 addr_to_additional(akey, region, *msg, now);
245                         lock_rw_unlock(&akey->entry.lock);
246                 } else {
247                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
248                                 LDNS_RR_TYPE_AAAA, qclass, now, 0);
249                         if(neg) {
250                                 delegpt_add_neg_msg(dp, neg);
251                                 lock_rw_unlock(&neg->entry.lock);
252                         }
253                 }
254         }
255         return 1;
256 }
257
258 /** find and add A and AAAA records for missing nameservers in delegpt */
259 int
260 cache_fill_missing(struct module_env* env, uint16_t qclass, 
261         struct regional* region, struct delegpt* dp)
262 {
263         struct delegpt_ns* ns;
264         struct msgreply_entry* neg;
265         struct ub_packed_rrset_key* akey;
266         time_t now = *env->now;
267         for(ns = dp->nslist; ns; ns = ns->next) {
268                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
269                         ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
270                 if(akey) {
271                         if(!delegpt_add_rrset_A(dp, region, akey, ns->lame)) {
272                                 lock_rw_unlock(&akey->entry.lock);
273                                 return 0;
274                         }
275                         log_nametypeclass(VERB_ALGO, "found in cache",
276                                 ns->name, LDNS_RR_TYPE_A, qclass);
277                         lock_rw_unlock(&akey->entry.lock);
278                 } else {
279                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
280                                 LDNS_RR_TYPE_A, qclass, now, 0);
281                         if(neg) {
282                                 delegpt_add_neg_msg(dp, neg);
283                                 lock_rw_unlock(&neg->entry.lock);
284                         }
285                 }
286                 akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
287                         ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
288                 if(akey) {
289                         if(!delegpt_add_rrset_AAAA(dp, region, akey, ns->lame)) {
290                                 lock_rw_unlock(&akey->entry.lock);
291                                 return 0;
292                         }
293                         log_nametypeclass(VERB_ALGO, "found in cache",
294                                 ns->name, LDNS_RR_TYPE_AAAA, qclass);
295                         lock_rw_unlock(&akey->entry.lock);
296                 } else {
297                         neg = msg_cache_lookup(env, ns->name, ns->namelen,
298                                 LDNS_RR_TYPE_AAAA, qclass, now, 0);
299                         if(neg) {
300                                 delegpt_add_neg_msg(dp, neg);
301                                 lock_rw_unlock(&neg->entry.lock);
302                         }
303                 }
304         }
305         return 1;
306 }
307
308 /** find and add DS or NSEC to delegation msg */
309 static void
310 find_add_ds(struct module_env* env, struct regional* region, 
311         struct dns_msg* msg, struct delegpt* dp, time_t now)
312 {
313         /* Lookup the DS or NSEC at the delegation point. */
314         struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
315                 env->rrset_cache, dp->name, dp->namelen, LDNS_RR_TYPE_DS, 
316                 msg->qinfo.qclass, 0, now, 0);
317         if(!rrset) {
318                 /* NOTE: this won't work for alternate NSEC schemes 
319                  *      (opt-in, NSEC3) */
320                 rrset = rrset_cache_lookup(env->rrset_cache, dp->name, 
321                         dp->namelen, LDNS_RR_TYPE_NSEC, msg->qinfo.qclass, 
322                         0, now, 0);
323                 /* Note: the PACKED_RRSET_NSEC_AT_APEX flag is not used.
324                  * since this is a referral, we need the NSEC at the parent
325                  * side of the zone cut, not the NSEC at apex side. */
326                 if(rrset && nsec_has_type(rrset, LDNS_RR_TYPE_DS)) {
327                         lock_rw_unlock(&rrset->entry.lock);
328                         rrset = NULL; /* discard wrong NSEC */
329                 }
330         }
331         if(rrset) {
332                 /* add it to auth section. This is the second rrset. */
333                 if((msg->rep->rrsets[msg->rep->rrset_count] = 
334                         packed_rrset_copy_region(rrset, region, now))) {
335                         msg->rep->ns_numrrsets++;
336                         msg->rep->rrset_count++;
337                 }
338                 lock_rw_unlock(&rrset->entry.lock);
339         }
340 }
341
342 struct dns_msg*
343 dns_msg_create(uint8_t* qname, size_t qnamelen, uint16_t qtype, 
344         uint16_t qclass, struct regional* region, size_t capacity)
345 {
346         struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
347                 sizeof(struct dns_msg));
348         if(!msg)
349                 return NULL;
350         msg->qinfo.qname = regional_alloc_init(region, qname, qnamelen);
351         if(!msg->qinfo.qname)
352                 return NULL;
353         msg->qinfo.qname_len = qnamelen;
354         msg->qinfo.qtype = qtype;
355         msg->qinfo.qclass = qclass;
356         /* non-packed reply_info, because it needs to grow the array */
357         msg->rep = (struct reply_info*)regional_alloc_zero(region, 
358                 sizeof(struct reply_info)-sizeof(struct rrset_ref));
359         if(!msg->rep)
360                 return NULL;
361         msg->rep->flags = BIT_QR; /* with QR, no AA */
362         msg->rep->qdcount = 1;
363         msg->rep->rrsets = (struct ub_packed_rrset_key**)
364                 regional_alloc(region, 
365                 capacity*sizeof(struct ub_packed_rrset_key*));
366         if(!msg->rep->rrsets)
367                 return NULL;
368         return msg;
369 }
370
371 int
372 dns_msg_authadd(struct dns_msg* msg, struct regional* region, 
373         struct ub_packed_rrset_key* rrset, time_t now)
374 {
375         if(!(msg->rep->rrsets[msg->rep->rrset_count++] = 
376                 packed_rrset_copy_region(rrset, region, now)))
377                 return 0;
378         msg->rep->ns_numrrsets++;
379         return 1;
380 }
381
382 struct delegpt* 
383 dns_cache_find_delegation(struct module_env* env, uint8_t* qname, 
384         size_t qnamelen, uint16_t qtype, uint16_t qclass, 
385         struct regional* region, struct dns_msg** msg, time_t now)
386 {
387         /* try to find closest NS rrset */
388         struct ub_packed_rrset_key* nskey;
389         struct packed_rrset_data* nsdata;
390         struct delegpt* dp;
391
392         nskey = find_closest_of_type(env, qname, qnamelen, qclass, now,
393                 LDNS_RR_TYPE_NS, 0);
394         if(!nskey) /* hope the caller has hints to prime or something */
395                 return NULL;
396         nsdata = (struct packed_rrset_data*)nskey->entry.data;
397         /* got the NS key, create delegation point */
398         dp = delegpt_create(region);
399         if(!dp || !delegpt_set_name(dp, region, nskey->rk.dname)) {
400                 lock_rw_unlock(&nskey->entry.lock);
401                 log_err("find_delegation: out of memory");
402                 return NULL;
403         }
404         /* create referral message */
405         if(msg) {
406                 /* allocate the array to as much as we could need:
407                  *      NS rrset + DS/NSEC rrset +
408                  *      A rrset for every NS RR
409                  *      AAAA rrset for every NS RR
410                  */
411                 *msg = dns_msg_create(qname, qnamelen, qtype, qclass, region, 
412                         2 + nsdata->count*2);
413                 if(!*msg || !dns_msg_authadd(*msg, region, nskey, now)) {
414                         lock_rw_unlock(&nskey->entry.lock);
415                         log_err("find_delegation: out of memory");
416                         return NULL;
417                 }
418         }
419         if(!delegpt_rrset_add_ns(dp, region, nskey, 0))
420                 log_err("find_delegation: addns out of memory");
421         lock_rw_unlock(&nskey->entry.lock); /* first unlock before next lookup*/
422         /* find and add DS/NSEC (if any) */
423         if(msg)
424                 find_add_ds(env, region, *msg, dp, now);
425         /* find and add A entries */
426         if(!find_add_addrs(env, qclass, region, dp, now, msg))
427                 log_err("find_delegation: addrs out of memory");
428         return dp;
429 }
430
431 /** allocate dns_msg from query_info and reply_info */
432 static struct dns_msg*
433 gen_dns_msg(struct regional* region, struct query_info* q, size_t num)
434 {
435         struct dns_msg* msg = (struct dns_msg*)regional_alloc(region, 
436                 sizeof(struct dns_msg));
437         if(!msg)
438                 return NULL;
439         memcpy(&msg->qinfo, q, sizeof(struct query_info));
440         msg->qinfo.qname = regional_alloc_init(region, q->qname, q->qname_len);
441         if(!msg->qinfo.qname)
442                 return NULL;
443         /* allocate replyinfo struct and rrset key array separately */
444         msg->rep = (struct reply_info*)regional_alloc(region,
445                 sizeof(struct reply_info) - sizeof(struct rrset_ref));
446         if(!msg->rep)
447                 return NULL;
448         msg->rep->rrsets = (struct ub_packed_rrset_key**)
449                 regional_alloc(region,
450                 num * sizeof(struct ub_packed_rrset_key*));
451         if(!msg->rep->rrsets)
452                 return NULL;
453         return msg;
454 }
455
456 /** generate dns_msg from cached message */
457 static struct dns_msg*
458 tomsg(struct module_env* env, struct query_info* q, struct reply_info* r, 
459         struct regional* region, time_t now, struct regional* scratch)
460 {
461         struct dns_msg* msg;
462         size_t i;
463         if(now > r->ttl)
464                 return NULL;
465         msg = gen_dns_msg(region, q, r->rrset_count);
466         if(!msg)
467                 return NULL;
468         msg->rep->flags = r->flags;
469         msg->rep->qdcount = r->qdcount;
470         msg->rep->ttl = r->ttl - now;
471         if(r->prefetch_ttl > now)
472                 msg->rep->prefetch_ttl = r->prefetch_ttl - now;
473         else    msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
474         msg->rep->security = r->security;
475         msg->rep->an_numrrsets = r->an_numrrsets;
476         msg->rep->ns_numrrsets = r->ns_numrrsets;
477         msg->rep->ar_numrrsets = r->ar_numrrsets;
478         msg->rep->rrset_count = r->rrset_count;
479         msg->rep->authoritative = r->authoritative;
480         if(!rrset_array_lock(r->ref, r->rrset_count, now))
481                 return NULL;
482         if(r->an_numrrsets > 0 && (r->rrsets[0]->rk.type == htons(
483                 LDNS_RR_TYPE_CNAME) || r->rrsets[0]->rk.type == htons(
484                 LDNS_RR_TYPE_DNAME)) && !reply_check_cname_chain(r)) {
485                 /* cname chain is now invalid, reconstruct msg */
486                 rrset_array_unlock(r->ref, r->rrset_count);
487                 return NULL;
488         }
489         if(r->security == sec_status_secure && !reply_all_rrsets_secure(r)) {
490                 /* message rrsets have changed status, revalidate */
491                 rrset_array_unlock(r->ref, r->rrset_count);
492                 return NULL;
493         }
494         for(i=0; i<msg->rep->rrset_count; i++) {
495                 msg->rep->rrsets[i] = packed_rrset_copy_region(r->rrsets[i], 
496                         region, now);
497                 if(!msg->rep->rrsets[i]) {
498                         rrset_array_unlock(r->ref, r->rrset_count);
499                         return NULL;
500                 }
501         }
502         rrset_array_unlock_touch(env->rrset_cache, scratch, r->ref, 
503                 r->rrset_count);
504         return msg;
505 }
506
507 /** synthesize RRset-only response from cached RRset item */
508 static struct dns_msg*
509 rrset_msg(struct ub_packed_rrset_key* rrset, struct regional* region, 
510         time_t now, struct query_info* q)
511 {
512         struct dns_msg* msg;
513         struct packed_rrset_data* d = (struct packed_rrset_data*)
514                 rrset->entry.data;
515         if(now > d->ttl)
516                 return NULL;
517         msg = gen_dns_msg(region, q, 1); /* only the CNAME (or other) RRset */
518         if(!msg)
519                 return NULL;
520         msg->rep->flags = BIT_QR; /* reply, no AA, no error */
521         msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
522         msg->rep->qdcount = 1;
523         msg->rep->ttl = d->ttl - now;
524         msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
525         msg->rep->security = sec_status_unchecked;
526         msg->rep->an_numrrsets = 1;
527         msg->rep->ns_numrrsets = 0;
528         msg->rep->ar_numrrsets = 0;
529         msg->rep->rrset_count = 1;
530         msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
531         if(!msg->rep->rrsets[0]) /* copy CNAME */
532                 return NULL;
533         return msg;
534 }
535
536 /** synthesize DNAME+CNAME response from cached DNAME item */
537 static struct dns_msg*
538 synth_dname_msg(struct ub_packed_rrset_key* rrset, struct regional* region, 
539         time_t now, struct query_info* q)
540 {
541         struct dns_msg* msg;
542         struct ub_packed_rrset_key* ck;
543         struct packed_rrset_data* newd, *d = (struct packed_rrset_data*)
544                 rrset->entry.data;
545         uint8_t* newname, *dtarg = NULL;
546         size_t newlen, dtarglen;
547         if(now > d->ttl)
548                 return NULL;
549         /* only allow validated (with DNSSEC) DNAMEs used from cache 
550          * for insecure DNAMEs, query again. */
551         if(d->security != sec_status_secure)
552                 return NULL;
553         msg = gen_dns_msg(region, q, 2); /* DNAME + CNAME RRset */
554         if(!msg)
555                 return NULL;
556         msg->rep->flags = BIT_QR; /* reply, no AA, no error */
557         msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
558         msg->rep->qdcount = 1;
559         msg->rep->ttl = d->ttl - now;
560         msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
561         msg->rep->security = sec_status_unchecked;
562         msg->rep->an_numrrsets = 1;
563         msg->rep->ns_numrrsets = 0;
564         msg->rep->ar_numrrsets = 0;
565         msg->rep->rrset_count = 1;
566         msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
567         if(!msg->rep->rrsets[0]) /* copy DNAME */
568                 return NULL;
569         /* synth CNAME rrset */
570         get_cname_target(rrset, &dtarg, &dtarglen);
571         if(!dtarg)
572                 return NULL;
573         newlen = q->qname_len + dtarglen - rrset->rk.dname_len;
574         if(newlen > LDNS_MAX_DOMAINLEN) {
575                 msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
576                 return msg;
577         }
578         newname = (uint8_t*)regional_alloc(region, newlen);
579         if(!newname)
580                 return NULL;
581         /* new name is concatenation of qname front (without DNAME owner)
582          * and DNAME target name */
583         memcpy(newname, q->qname, q->qname_len-rrset->rk.dname_len);
584         memmove(newname+(q->qname_len-rrset->rk.dname_len), dtarg, dtarglen);
585         /* create rest of CNAME rrset */
586         ck = (struct ub_packed_rrset_key*)regional_alloc(region, 
587                 sizeof(struct ub_packed_rrset_key));
588         if(!ck)
589                 return NULL;
590         memset(&ck->entry, 0, sizeof(ck->entry));
591         msg->rep->rrsets[1] = ck;
592         ck->entry.key = ck;
593         ck->rk.type = htons(LDNS_RR_TYPE_CNAME);
594         ck->rk.rrset_class = rrset->rk.rrset_class;
595         ck->rk.flags = 0;
596         ck->rk.dname = regional_alloc_init(region, q->qname, q->qname_len);
597         if(!ck->rk.dname)
598                 return NULL;
599         ck->rk.dname_len = q->qname_len;
600         ck->entry.hash = rrset_key_hash(&ck->rk);
601         newd = (struct packed_rrset_data*)regional_alloc_zero(region,
602                 sizeof(struct packed_rrset_data) + sizeof(size_t) + 
603                 sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t) 
604                 + newlen);
605         if(!newd)
606                 return NULL;
607         ck->entry.data = newd;
608         newd->ttl = 0; /* 0 for synthesized CNAME TTL */
609         newd->count = 1;
610         newd->rrsig_count = 0;
611         newd->trust = rrset_trust_ans_noAA;
612         newd->rr_len = (size_t*)((uint8_t*)newd + 
613                 sizeof(struct packed_rrset_data));
614         newd->rr_len[0] = newlen + sizeof(uint16_t);
615         packed_rrset_ptr_fixup(newd);
616         newd->rr_ttl[0] = newd->ttl;
617         msg->rep->ttl = newd->ttl;
618         msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(newd->ttl);
619         sldns_write_uint16(newd->rr_data[0], newlen);
620         memmove(newd->rr_data[0] + sizeof(uint16_t), newname, newlen);
621         msg->rep->an_numrrsets ++;
622         msg->rep->rrset_count ++;
623         return msg;
624 }
625
626 struct dns_msg* 
627 dns_cache_lookup(struct module_env* env,
628         uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
629         struct regional* region, struct regional* scratch)
630 {
631         struct lruhash_entry* e;
632         struct query_info k;
633         hashvalue_t h;
634         time_t now = *env->now;
635         struct ub_packed_rrset_key* rrset;
636
637         /* lookup first, this has both NXdomains and ANSWER responses */
638         k.qname = qname;
639         k.qname_len = qnamelen;
640         k.qtype = qtype;
641         k.qclass = qclass;
642         h = query_info_hash(&k);
643         e = slabhash_lookup(env->msg_cache, h, &k, 0);
644         if(e) {
645                 struct msgreply_entry* key = (struct msgreply_entry*)e->key;
646                 struct reply_info* data = (struct reply_info*)e->data;
647                 struct dns_msg* msg = tomsg(env, &key->key, data, region, now, 
648                         scratch);
649                 if(msg) {
650                         lock_rw_unlock(&e->lock);
651                         return msg;
652                 }
653                 /* could be msg==NULL; due to TTL or not all rrsets available */
654                 lock_rw_unlock(&e->lock);
655         }
656
657         /* see if a DNAME exists. Checked for first, to enforce that DNAMEs
658          * are more important, the CNAME is resynthesized and thus 
659          * consistent with the DNAME */
660         if( (rrset=find_closest_of_type(env, qname, qnamelen, qclass, now,
661                 LDNS_RR_TYPE_DNAME, 1))) {
662                 /* synthesize a DNAME+CNAME message based on this */
663                 struct dns_msg* msg = synth_dname_msg(rrset, region, now, &k);
664                 if(msg) {
665                         lock_rw_unlock(&rrset->entry.lock);
666                         return msg;
667                 }
668                 lock_rw_unlock(&rrset->entry.lock);
669         }
670
671         /* see if we have CNAME for this domain,
672          * but not for DS records (which are part of the parent) */
673         if( qtype != LDNS_RR_TYPE_DS &&
674            (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen, 
675                 LDNS_RR_TYPE_CNAME, qclass, 0, now, 0))) {
676                 struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
677                 if(msg) {
678                         lock_rw_unlock(&rrset->entry.lock);
679                         return msg;
680                 }
681                 lock_rw_unlock(&rrset->entry.lock);
682         }
683
684         /* construct DS, DNSKEY, DLV messages from rrset cache. */
685         if((qtype == LDNS_RR_TYPE_DS || qtype == LDNS_RR_TYPE_DNSKEY ||
686                 qtype == LDNS_RR_TYPE_DLV) &&
687                 (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen, 
688                 qtype, qclass, 0, now, 0))) {
689                 /* if the rrset is from the additional section, and the
690                  * signatures have fallen off, then do not synthesize a msg
691                  * instead, allow a full query for signed results to happen.
692                  * Forego all rrset data from additional section, because
693                  * some signatures may not be present and cause validation
694                  * failure.
695                  */
696                 struct packed_rrset_data *d = (struct packed_rrset_data*)
697                         rrset->entry.data;
698                 if(d->trust != rrset_trust_add_noAA && 
699                         d->trust != rrset_trust_add_AA && 
700                         (qtype == LDNS_RR_TYPE_DS || 
701                                 (d->trust != rrset_trust_auth_noAA 
702                                 && d->trust != rrset_trust_auth_AA) )) {
703                         struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
704                         if(msg) {
705                                 lock_rw_unlock(&rrset->entry.lock);
706                                 return msg;
707                         }
708                 }
709                 lock_rw_unlock(&rrset->entry.lock);
710         }
711
712         /* stop downwards cache search on NXDOMAIN.
713          * Empty nonterminals are NOERROR, so an NXDOMAIN for foo
714          * means bla.foo also does not exist.  The DNSSEC proofs are
715          * the same.  We search upwards for NXDOMAINs. */
716         if(env->cfg->harden_below_nxdomain)
717             while(!dname_is_root(k.qname)) {
718                 dname_remove_label(&k.qname, &k.qname_len);
719                 h = query_info_hash(&k);
720                 e = slabhash_lookup(env->msg_cache, h, &k, 0);
721                 if(e) {
722                         struct reply_info* data = (struct reply_info*)e->data;
723                         struct dns_msg* msg;
724                         if(FLAGS_GET_RCODE(data->flags) == LDNS_RCODE_NXDOMAIN
725                           && data->security == sec_status_secure
726                           && (msg=tomsg(env, &k, data, region, now, scratch))){
727                                 lock_rw_unlock(&e->lock);
728                                 msg->qinfo.qname=qname;
729                                 msg->qinfo.qname_len=qnamelen;
730                                 /* check that DNSSEC really works out */
731                                 msg->rep->security = sec_status_unchecked;
732                                 return msg;
733                         }
734                         lock_rw_unlock(&e->lock);
735                 }
736         }
737
738         return NULL;
739 }
740
741 int 
742 dns_cache_store(struct module_env* env, struct query_info* msgqinf,
743         struct reply_info* msgrep, int is_referral, time_t leeway, int pside,
744         struct regional* region)
745 {
746         struct reply_info* rep = NULL;
747         /* alloc, malloc properly (not in region, like msg is) */
748         rep = reply_info_copy(msgrep, env->alloc, NULL);
749         if(!rep)
750                 return 0;
751         /* ttl must be relative ;i.e. 0..86400 not  time(0)+86400. 
752          * the env->now is added to message and RRsets in this routine. */
753         /* the leeway is used to invalidate other rrsets earlier */
754
755         if(is_referral) {
756                 /* store rrsets */
757                 struct rrset_ref ref;
758                 size_t i;
759                 for(i=0; i<rep->rrset_count; i++) {
760                         packed_rrset_ttl_add((struct packed_rrset_data*)
761                                 rep->rrsets[i]->entry.data, *env->now);
762                         ref.key = rep->rrsets[i];
763                         ref.id = rep->rrsets[i]->id;
764                         /*ignore ret: it was in the cache, ref updated */
765                         /* no leeway for typeNS */
766                         (void)rrset_cache_update(env->rrset_cache, &ref, 
767                                 env->alloc, *env->now + 
768                                 ((ntohs(ref.key->rk.type)==LDNS_RR_TYPE_NS
769                                  && !pside) ? 0:leeway));
770                 }
771                 free(rep);
772                 return 1;
773         } else {
774                 /* store msg, and rrsets */
775                 struct query_info qinf;
776                 hashvalue_t h;
777
778                 qinf = *msgqinf;
779                 qinf.qname = memdup(msgqinf->qname, msgqinf->qname_len);
780                 if(!qinf.qname) {
781                         reply_info_parsedelete(rep, env->alloc);
782                         return 0;
783                 }
784                 /* fixup flags to be sensible for a reply based on the cache */
785                 /* this module means that RA is available. It is an answer QR. 
786                  * Not AA from cache. Not CD in cache (depends on client bit). */
787                 rep->flags |= (BIT_RA | BIT_QR);
788                 rep->flags &= ~(BIT_AA | BIT_CD);
789                 h = query_info_hash(&qinf);
790                 dns_cache_store_msg(env, &qinf, h, rep, leeway, pside, msgrep,
791                         region);
792                 /* qname is used inside query_info_entrysetup, and set to 
793                  * NULL. If it has not been used, free it. free(0) is safe. */
794                 free(qinf.qname);
795         }
796         return 1;
797 }