Coverage Report

Created: 2026-03-12 07:06

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