Coverage Report

Created: 2025-10-10 06:37

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
    if((rrset = rrset_cache_lookup(env->rrset_cache, qname, 
236
0
      qnamelen, searchtype, qclass, 0, now, 0))) {
237
0
      uint8_t* origqname = qname;
238
0
      size_t origqnamelen = qnamelen;
239
0
      if(!noexpiredabove)
240
0
        return rrset;
241
      /* if expiretop set, do not look above it, but
242
       * qname is equal, so the just found result is also
243
       * the nonexpired above part. */
244
0
      if(expiretop && qnamelen == expiretoplen &&
245
0
        query_dname_compare(qname, expiretop)==0)
246
0
        return rrset;
247
      /* check for expiry, but we have to let go of the rrset
248
       * for the lock ordering */
249
0
      lock_rw_unlock(&rrset->entry.lock);
250
      /* the rrset_cache_expired_above function always takes
251
       * off one label (if qnamelen>0) and returns the final
252
       * qname where it searched, so we can continue from
253
       * there turning the O N*N search into O N. */
254
0
      if(!rrset_cache_expired_above(env->rrset_cache, &qname,
255
0
        &qnamelen, searchtype, qclass, now, expiretop,
256
0
        expiretoplen)) {
257
        /* we want to return rrset, but it may be
258
         * gone from cache, if so, just loop like
259
         * it was not in the cache in the first place.
260
         */
261
0
        if((rrset = rrset_cache_lookup(env->
262
0
          rrset_cache, origqname, origqnamelen,
263
0
          searchtype, qclass, 0, now, 0))) {
264
0
          return rrset;
265
0
        }
266
0
      }
267
0
      log_nametypeclass(VERB_ALGO, "ignoring rrset because expired rrsets exist above it", origqname, searchtype, qclass);
268
0
      continue;
269
0
    }
270
271
    /* snip off front label */
272
0
    lablen = *qname;
273
0
    qname += lablen + 1;
274
0
    qnamelen -= lablen + 1;
275
0
  }
276
0
  return NULL;
277
0
}
278
279
/** add addr to additional section */
280
static void
281
addr_to_additional(struct ub_packed_rrset_key* rrset, struct regional* region,
282
  struct dns_msg* msg, time_t now)
283
0
{
284
0
  if((msg->rep->rrsets[msg->rep->rrset_count] = 
285
0
    packed_rrset_copy_region(rrset, region, now))) {
286
0
    struct packed_rrset_data* d = rrset->entry.data;
287
0
    msg->rep->ar_numrrsets++;
288
0
    msg->rep->rrset_count++;
289
0
    UPDATE_TTL_FROM_RRSET(msg->rep->ttl, d->ttl);
290
0
  }
291
0
}
292
293
/** lookup message in message cache */
294
struct msgreply_entry* 
295
msg_cache_lookup(struct module_env* env, uint8_t* qname, size_t qnamelen, 
296
  uint16_t qtype, uint16_t qclass, uint16_t flags, time_t now, int wr)
297
0
{
298
0
  struct lruhash_entry* e;
299
0
  struct query_info k;
300
0
  hashvalue_type h;
301
302
0
  k.qname = qname;
303
0
  k.qname_len = qnamelen;
304
0
  k.qtype = qtype;
305
0
  k.qclass = qclass;
306
0
  k.local_alias = NULL;
307
0
  h = query_info_hash(&k, flags);
308
0
  e = slabhash_lookup(env->msg_cache, h, &k, wr);
309
310
0
  if(!e) return NULL;
311
0
  if( now > ((struct reply_info*)e->data)->ttl ) {
312
0
    lock_rw_unlock(&e->lock);
313
0
    return NULL;
314
0
  }
315
0
  return (struct msgreply_entry*)e->key;
316
0
}
317
318
/** find and add A and AAAA records for nameservers in delegpt */
319
static int
320
find_add_addrs(struct module_env* env, uint16_t qclass, 
321
  struct regional* region, struct delegpt* dp, time_t now, 
322
  struct dns_msg** msg)
323
0
{
324
0
  struct delegpt_ns* ns;
325
0
  struct msgreply_entry* neg;
326
0
  struct ub_packed_rrset_key* akey;
327
0
  for(ns = dp->nslist; ns; ns = ns->next) {
328
0
    akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
329
0
      ns->namelen, LDNS_RR_TYPE_A, qclass, 0, now, 0);
330
0
    if(akey) {
331
0
      if(!delegpt_add_rrset_A(dp, region, akey, 0, NULL)) {
332
0
        lock_rw_unlock(&akey->entry.lock);
333
0
        return 0;
334
0
      }
335
0
      if(msg)
336
0
        addr_to_additional(akey, region, *msg, now);
337
0
      lock_rw_unlock(&akey->entry.lock);
338
0
    } else {
339
      /* BIT_CD on false because delegpt lookup does
340
       * not use dns64 translation */
341
0
      neg = msg_cache_lookup(env, ns->name, ns->namelen,
342
0
        LDNS_RR_TYPE_A, qclass, 0, now, 0);
343
0
      if(neg) {
344
0
        delegpt_add_neg_msg(dp, neg);
345
0
        lock_rw_unlock(&neg->entry.lock);
346
0
      }
347
0
    }
348
0
    akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
349
0
      ns->namelen, LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
350
0
    if(akey) {
351
0
      if(!delegpt_add_rrset_AAAA(dp, region, akey, 0, NULL)) {
352
0
        lock_rw_unlock(&akey->entry.lock);
353
0
        return 0;
354
0
      }
355
0
      if(msg)
356
0
        addr_to_additional(akey, region, *msg, now);
357
0
      lock_rw_unlock(&akey->entry.lock);
358
0
    } else {
359
      /* BIT_CD on false because delegpt lookup does
360
       * not use dns64 translation */
361
0
      neg = msg_cache_lookup(env, ns->name, ns->namelen,
362
0
        LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
363
      /* Because recursion for lookup uses BIT_CD, check
364
       * for that so it stops the recursion lookup, if a
365
       * negative answer is cached. Because the cache uses
366
       * the CD flag for type AAAA. */
367
0
      if(!neg)
368
0
        neg = msg_cache_lookup(env, ns->name, ns->namelen,
369
0
          LDNS_RR_TYPE_AAAA, qclass, BIT_CD, now, 0);
370
0
      if(neg) {
371
0
        delegpt_add_neg_msg(dp, neg);
372
0
        lock_rw_unlock(&neg->entry.lock);
373
0
      }
374
0
    }
375
0
  }
376
0
  return 1;
377
0
}
378
379
/** find and add A and AAAA records for missing nameservers in delegpt */
380
int
381
cache_fill_missing(struct module_env* env, uint16_t qclass, 
382
  struct regional* region, struct delegpt* dp, uint32_t flags)
383
0
{
384
0
  struct delegpt_ns* ns;
385
0
  struct msgreply_entry* neg;
386
0
  struct ub_packed_rrset_key* akey;
387
0
  time_t now = *env->now;
388
0
  for(ns = dp->nslist; ns; ns = ns->next) {
389
0
    if(ns->cache_lookup_count > ITERATOR_NAME_CACHELOOKUP_MAX)
390
0
      continue;
391
0
    ns->cache_lookup_count++;
392
0
    akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
393
0
      ns->namelen, LDNS_RR_TYPE_A, qclass, flags, now, 0);
394
0
    if(akey) {
395
0
      if(!delegpt_add_rrset_A(dp, region, akey, ns->lame,
396
0
        NULL)) {
397
0
        lock_rw_unlock(&akey->entry.lock);
398
0
        return 0;
399
0
      }
400
0
      log_nametypeclass(VERB_ALGO, "found in cache",
401
0
        ns->name, LDNS_RR_TYPE_A, qclass);
402
0
      lock_rw_unlock(&akey->entry.lock);
403
0
    } else {
404
      /* BIT_CD on false because delegpt lookup does
405
       * not use dns64 translation */
406
0
      neg = msg_cache_lookup(env, ns->name, ns->namelen,
407
0
        LDNS_RR_TYPE_A, qclass, 0, now, 0);
408
0
      if(neg) {
409
0
        delegpt_add_neg_msg(dp, neg);
410
0
        lock_rw_unlock(&neg->entry.lock);
411
0
      }
412
0
    }
413
0
    akey = rrset_cache_lookup(env->rrset_cache, ns->name, 
414
0
      ns->namelen, LDNS_RR_TYPE_AAAA, qclass, flags, now, 0);
415
0
    if(akey) {
416
0
      if(!delegpt_add_rrset_AAAA(dp, region, akey, ns->lame,
417
0
        NULL)) {
418
0
        lock_rw_unlock(&akey->entry.lock);
419
0
        return 0;
420
0
      }
421
0
      log_nametypeclass(VERB_ALGO, "found in cache",
422
0
        ns->name, LDNS_RR_TYPE_AAAA, qclass);
423
0
      lock_rw_unlock(&akey->entry.lock);
424
0
    } else {
425
      /* BIT_CD on false because delegpt lookup does
426
       * not use dns64 translation */
427
0
      neg = msg_cache_lookup(env, ns->name, ns->namelen,
428
0
        LDNS_RR_TYPE_AAAA, qclass, 0, now, 0);
429
      /* Because recursion for lookup uses BIT_CD, check
430
       * for that so it stops the recursion lookup, if a
431
       * negative answer is cached. Because the cache uses
432
       * the CD flag for type AAAA. */
433
0
      if(!neg)
434
0
        neg = msg_cache_lookup(env, ns->name, ns->namelen,
435
0
          LDNS_RR_TYPE_AAAA, qclass, BIT_CD, now, 0);
436
0
      if(neg) {
437
0
        delegpt_add_neg_msg(dp, neg);
438
0
        lock_rw_unlock(&neg->entry.lock);
439
0
      }
440
0
    }
441
0
  }
442
0
  return 1;
443
0
}
444
445
/** find and add DS or NSEC to delegation msg */
446
static void
447
find_add_ds(struct module_env* env, struct regional* region, 
448
  struct dns_msg* msg, struct delegpt* dp, time_t now)
449
0
{
450
  /* Lookup the DS or NSEC at the delegation point. */
451
0
  struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
452
0
    env->rrset_cache, dp->name, dp->namelen, LDNS_RR_TYPE_DS, 
453
0
    msg->qinfo.qclass, 0, now, 0);
454
0
  if(!rrset) {
455
    /* NOTE: this won't work for alternate NSEC schemes 
456
     *  (opt-in, NSEC3) */
457
0
    rrset = rrset_cache_lookup(env->rrset_cache, dp->name, 
458
0
      dp->namelen, LDNS_RR_TYPE_NSEC, msg->qinfo.qclass, 
459
0
      0, now, 0);
460
    /* Note: the PACKED_RRSET_NSEC_AT_APEX flag is not used.
461
     * since this is a referral, we need the NSEC at the parent
462
     * side of the zone cut, not the NSEC at apex side. */
463
0
    if(rrset && nsec_has_type(rrset, LDNS_RR_TYPE_DS)) {
464
0
      lock_rw_unlock(&rrset->entry.lock);
465
0
      rrset = NULL; /* discard wrong NSEC */
466
0
    }
467
0
  }
468
0
  if(rrset) {
469
    /* add it to auth section. This is the second rrset. */
470
0
    if((msg->rep->rrsets[msg->rep->rrset_count] = 
471
0
      packed_rrset_copy_region(rrset, region, now))) {
472
0
      struct packed_rrset_data* d = rrset->entry.data;
473
0
      msg->rep->ns_numrrsets++;
474
0
      msg->rep->rrset_count++;
475
0
      UPDATE_TTL_FROM_RRSET(msg->rep->ttl, d->ttl);
476
0
    }
477
0
    lock_rw_unlock(&rrset->entry.lock);
478
0
  }
479
0
}
480
481
struct dns_msg*
482
dns_msg_create(uint8_t* qname, size_t qnamelen, uint16_t qtype, 
483
  uint16_t qclass, struct regional* region, size_t capacity)
484
0
{
485
0
  struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
486
0
    sizeof(struct dns_msg));
487
0
  if(!msg)
488
0
    return NULL;
489
0
  msg->qinfo.qname = regional_alloc_init(region, qname, qnamelen);
490
0
  if(!msg->qinfo.qname)
491
0
    return NULL;
492
0
  msg->qinfo.qname_len = qnamelen;
493
0
  msg->qinfo.qtype = qtype;
494
0
  msg->qinfo.qclass = qclass;
495
0
  msg->qinfo.local_alias = NULL;
496
  /* non-packed reply_info, because it needs to grow the array */
497
0
  msg->rep = (struct reply_info*)regional_alloc_zero(region, 
498
0
    sizeof(struct reply_info)-sizeof(struct rrset_ref));
499
0
  if(!msg->rep)
500
0
    return NULL;
501
0
  if(capacity > RR_COUNT_MAX)
502
0
    return NULL; /* integer overflow protection */
503
0
  msg->rep->flags = BIT_QR; /* with QR, no AA */
504
0
  msg->rep->qdcount = 1;
505
0
  msg->rep->ttl = MAX_TTL; /* will be updated (brought down) while we add
506
          * rrsets to the message */
507
0
  msg->rep->reason_bogus = LDNS_EDE_NONE;
508
0
  msg->rep->rrsets = (struct ub_packed_rrset_key**)
509
0
    regional_alloc(region, 
510
0
    capacity*sizeof(struct ub_packed_rrset_key*));
511
0
  if(!msg->rep->rrsets)
512
0
    return NULL;
513
0
  return msg;
514
0
}
515
516
int
517
dns_msg_authadd(struct dns_msg* msg, struct regional* region,
518
  struct ub_packed_rrset_key* rrset, time_t now)
519
0
{
520
0
  struct packed_rrset_data* d = rrset->entry.data;
521
0
  if(!(msg->rep->rrsets[msg->rep->rrset_count++] =
522
0
    packed_rrset_copy_region(rrset, region, now)))
523
0
    return 0;
524
0
  msg->rep->ns_numrrsets++;
525
0
  UPDATE_TTL_FROM_RRSET(msg->rep->ttl, d->ttl);
526
0
  return 1;
527
0
}
528
529
int
530
dns_msg_ansadd(struct dns_msg* msg, struct regional* region,
531
  struct ub_packed_rrset_key* rrset, time_t now)
532
0
{
533
0
  struct packed_rrset_data* d = rrset->entry.data;
534
0
  if(!(msg->rep->rrsets[msg->rep->rrset_count++] =
535
0
    packed_rrset_copy_region(rrset, region, now)))
536
0
    return 0;
537
0
  msg->rep->an_numrrsets++;
538
0
  UPDATE_TTL_FROM_RRSET(msg->rep->ttl, d->ttl);
539
0
  return 1;
540
0
}
541
542
struct delegpt* 
543
dns_cache_find_delegation(struct module_env* env, uint8_t* qname, 
544
  size_t qnamelen, uint16_t qtype, uint16_t qclass, 
545
  struct regional* region, struct dns_msg** msg, time_t now,
546
  int noexpiredabove, uint8_t* expiretop, size_t expiretoplen)
547
0
{
548
  /* try to find closest NS rrset */
549
0
  struct ub_packed_rrset_key* nskey;
550
0
  struct packed_rrset_data* nsdata;
551
0
  struct delegpt* dp;
552
553
0
  nskey = find_closest_of_type(env, qname, qnamelen, qclass, now,
554
0
    LDNS_RR_TYPE_NS, 0, noexpiredabove, expiretop, expiretoplen);
555
0
  if(!nskey) /* hope the caller has hints to prime or something */
556
0
    return NULL;
557
0
  nsdata = (struct packed_rrset_data*)nskey->entry.data;
558
  /* got the NS key, create delegation point */
559
0
  dp = delegpt_create(region);
560
0
  if(!dp || !delegpt_set_name(dp, region, nskey->rk.dname)) {
561
0
    lock_rw_unlock(&nskey->entry.lock);
562
0
    log_err("find_delegation: out of memory");
563
0
    return NULL;
564
0
  }
565
  /* create referral message */
566
0
  if(msg) {
567
    /* allocate the array to as much as we could need:
568
     *  NS rrset + DS/NSEC rrset +
569
     *  A rrset for every NS RR
570
     *  AAAA rrset for every NS RR
571
     */
572
0
    *msg = dns_msg_create(qname, qnamelen, qtype, qclass, region, 
573
0
      2 + nsdata->count*2);
574
0
    if(!*msg || !dns_msg_authadd(*msg, region, nskey, now)) {
575
0
      lock_rw_unlock(&nskey->entry.lock);
576
0
      log_err("find_delegation: out of memory");
577
0
      return NULL;
578
0
    }
579
0
  }
580
0
  if(!delegpt_rrset_add_ns(dp, region, nskey, 0))
581
0
    log_err("find_delegation: addns out of memory");
582
0
  lock_rw_unlock(&nskey->entry.lock); /* first unlock before next lookup*/
583
  /* find and add DS/NSEC (if any) */
584
0
  if(msg)
585
0
    find_add_ds(env, region, *msg, dp, now);
586
  /* find and add A entries */
587
0
  if(!find_add_addrs(env, qclass, region, dp, now, msg))
588
0
    log_err("find_delegation: addrs out of memory");
589
0
  return dp;
590
0
}
591
592
/** allocate dns_msg from query_info and reply_info */
593
static struct dns_msg*
594
gen_dns_msg(struct regional* region, struct query_info* q, size_t num)
595
0
{
596
0
  struct dns_msg* msg = (struct dns_msg*)regional_alloc(region, 
597
0
    sizeof(struct dns_msg));
598
0
  if(!msg)
599
0
    return NULL;
600
0
  memcpy(&msg->qinfo, q, sizeof(struct query_info));
601
0
  msg->qinfo.qname = regional_alloc_init(region, q->qname, q->qname_len);
602
0
  if(!msg->qinfo.qname)
603
0
    return NULL;
604
  /* allocate replyinfo struct and rrset key array separately */
605
0
  msg->rep = (struct reply_info*)regional_alloc(region,
606
0
    sizeof(struct reply_info) - sizeof(struct rrset_ref));
607
0
  if(!msg->rep)
608
0
    return NULL;
609
0
  msg->rep->ttl = MAX_TTL;
610
0
  msg->rep->reason_bogus = LDNS_EDE_NONE;
611
0
  msg->rep->reason_bogus_str = NULL;
612
0
  if(num > RR_COUNT_MAX)
613
0
    return NULL; /* integer overflow protection */
614
0
  msg->rep->rrsets = (struct ub_packed_rrset_key**)
615
0
    regional_alloc(region,
616
0
    num * sizeof(struct ub_packed_rrset_key*));
617
0
  if(!msg->rep->rrsets)
618
0
    return NULL;
619
0
  return msg;
620
0
}
621
622
struct dns_msg*
623
tomsg(struct module_env* env, struct query_info* q, struct reply_info* r,
624
  struct regional* region, time_t now, int allow_expired,
625
  struct regional* scratch)
626
0
{
627
0
  struct dns_msg* msg;
628
0
  size_t i;
629
0
  int is_expired = 0;
630
0
  time_t now_control = now;
631
0
  if(TTL_IS_EXPIRED(r->ttl, now)) {
632
    /* Check if we are allowed to serve expired */
633
0
    if(!allow_expired || !reply_info_can_answer_expired(r, now))
634
0
      return NULL;
635
    /* Change the current time so we can pass the below TTL checks
636
     * when serving expired data. */
637
0
    now_control = 0;
638
0
    is_expired = 1;
639
0
  }
640
641
0
  msg = gen_dns_msg(region, q, r->rrset_count);
642
0
  if(!msg) return NULL;
643
0
  msg->rep->flags = r->flags;
644
0
  msg->rep->qdcount = r->qdcount;
645
0
  msg->rep->security = r->security;
646
0
  msg->rep->an_numrrsets = r->an_numrrsets;
647
0
  msg->rep->ns_numrrsets = r->ns_numrrsets;
648
0
  msg->rep->ar_numrrsets = r->ar_numrrsets;
649
0
  msg->rep->rrset_count = r->rrset_count;
650
0
  msg->rep->authoritative = r->authoritative;
651
0
  msg->rep->reason_bogus = r->reason_bogus;
652
0
  if(r->reason_bogus_str) {
653
0
    msg->rep->reason_bogus_str = regional_strdup(region, r->reason_bogus_str);
654
0
  }
655
656
0
  if(!rrset_array_lock(r->ref, r->rrset_count, now_control)) {
657
0
    return NULL;
658
0
  }
659
0
  if(r->an_numrrsets > 0 && (r->rrsets[0]->rk.type == htons(
660
0
    LDNS_RR_TYPE_CNAME) || r->rrsets[0]->rk.type == htons(
661
0
    LDNS_RR_TYPE_DNAME)) && !reply_check_cname_chain(q, r)) {
662
    /* cname chain is now invalid, reconstruct msg */
663
0
    rrset_array_unlock(r->ref, r->rrset_count);
664
0
    return NULL;
665
0
  }
666
0
  if(r->security == sec_status_secure && !reply_all_rrsets_secure(r)) {
667
    /* message rrsets have changed status, revalidate */
668
0
    rrset_array_unlock(r->ref, r->rrset_count);
669
0
    return NULL;
670
0
  }
671
0
  for(i=0; i<msg->rep->rrset_count; i++) {
672
0
    struct packed_rrset_data* d;
673
0
    msg->rep->rrsets[i] = packed_rrset_copy_region(r->rrsets[i],
674
0
      region, now);
675
0
    if(!msg->rep->rrsets[i]) {
676
0
      rrset_array_unlock(r->ref, r->rrset_count);
677
0
      return NULL;
678
0
    }
679
0
    d = msg->rep->rrsets[i]->entry.data;
680
0
    UPDATE_TTL_FROM_RRSET(msg->rep->ttl, d->ttl);
681
0
  }
682
0
  if(msg->rep->rrset_count < 1) {
683
0
    msg->rep->ttl = is_expired
684
0
      ?SERVE_EXPIRED_REPLY_TTL
685
0
      :r->ttl - now;
686
0
    if(r->prefetch_ttl > now)
687
0
      msg->rep->prefetch_ttl = r->prefetch_ttl - now;
688
0
    else
689
0
      msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
690
0
  } else {
691
    /* msg->rep->ttl has been updated through the RRSets above */
692
0
    msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
693
0
  }
694
0
  msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
695
0
  msg->rep->serve_expired_norec_ttl = 0;
696
0
  if(env)
697
0
    rrset_array_unlock_touch(env->rrset_cache, scratch, r->ref, 
698
0
    r->rrset_count);
699
0
  else
700
0
    rrset_array_unlock(r->ref, r->rrset_count);
701
0
  return msg;
702
0
}
703
704
struct dns_msg*
705
dns_msg_deepcopy_region(struct dns_msg* origin, struct regional* region)
706
0
{
707
0
  size_t i;
708
0
  struct dns_msg* res = NULL;
709
0
  res = gen_dns_msg(region, &origin->qinfo, origin->rep->rrset_count);
710
0
  if(!res) return NULL;
711
0
  *res->rep = *origin->rep;
712
0
  if(origin->rep->reason_bogus_str) {
713
0
    res->rep->reason_bogus_str = regional_strdup(region,
714
0
      origin->rep->reason_bogus_str);
715
0
  }
716
0
  for(i=0; i<res->rep->rrset_count; i++) {
717
0
    res->rep->rrsets[i] = packed_rrset_copy_region(
718
0
      origin->rep->rrsets[i], region, 0);
719
0
    if(!res->rep->rrsets[i]) {
720
0
      return NULL;
721
0
    }
722
0
  }
723
0
  return res;
724
0
}
725
726
/** synthesize RRset-only response from cached RRset item */
727
static struct dns_msg*
728
rrset_msg(struct ub_packed_rrset_key* rrset, struct regional* region, 
729
  time_t now, struct query_info* q)
730
0
{
731
0
  struct dns_msg* msg;
732
0
  struct packed_rrset_data* d = (struct packed_rrset_data*)
733
0
    rrset->entry.data;
734
0
  if(TTL_IS_EXPIRED(d->ttl, now))
735
0
    return NULL;
736
0
  msg = gen_dns_msg(region, q, 1); /* only the CNAME (or other) RRset */
737
0
  if(!msg)
738
0
    return NULL;
739
0
  msg->rep->flags = BIT_QR; /* reply, no AA, no error */
740
0
        msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
741
0
  msg->rep->qdcount = 1;
742
0
  msg->rep->ttl = d->ttl - now;
743
0
  msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
744
0
  msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
745
0
  msg->rep->serve_expired_norec_ttl = 0;
746
0
  msg->rep->security = sec_status_unchecked;
747
0
  msg->rep->an_numrrsets = 1;
748
0
  msg->rep->ns_numrrsets = 0;
749
0
  msg->rep->ar_numrrsets = 0;
750
0
  msg->rep->rrset_count = 1;
751
0
  msg->rep->reason_bogus = LDNS_EDE_NONE;
752
0
  msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
753
0
  if(!msg->rep->rrsets[0]) /* copy CNAME */
754
0
    return NULL;
755
0
  return msg;
756
0
}
757
758
/** synthesize DNAME+CNAME response from cached DNAME item */
759
static struct dns_msg*
760
synth_dname_msg(struct ub_packed_rrset_key* rrset, struct regional* region, 
761
  time_t now, struct query_info* q, enum sec_status* sec_status)
762
0
{
763
0
  struct dns_msg* msg;
764
0
  struct ub_packed_rrset_key* ck;
765
0
  struct packed_rrset_data* newd, *d = (struct packed_rrset_data*)
766
0
    rrset->entry.data;
767
0
  uint8_t* newname, *dtarg = NULL;
768
0
  size_t newlen, dtarglen;
769
0
  if(TTL_IS_EXPIRED(d->ttl, now))
770
0
    return NULL;
771
  /* only allow validated (with DNSSEC) DNAMEs used from cache 
772
   * for insecure DNAMEs, query again. */
773
0
  *sec_status = d->security;
774
  /* return sec status, so the status of the CNAME can be checked
775
   * by the calling routine. */
776
0
  msg = gen_dns_msg(region, q, 2); /* DNAME + CNAME RRset */
777
0
  if(!msg)
778
0
    return NULL;
779
0
  msg->rep->flags = BIT_QR; /* reply, no AA, no error */
780
0
        msg->rep->authoritative = 0; /* reply stored in cache can't be authoritative */
781
0
  msg->rep->qdcount = 1;
782
0
  msg->rep->ttl = d->ttl - now;
783
0
  msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
784
0
  msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
785
0
  msg->rep->serve_expired_norec_ttl = 0;
786
0
  msg->rep->security = sec_status_unchecked;
787
0
  msg->rep->an_numrrsets = 1;
788
0
  msg->rep->ns_numrrsets = 0;
789
0
  msg->rep->ar_numrrsets = 0;
790
0
  msg->rep->rrset_count = 1;
791
0
  msg->rep->reason_bogus = LDNS_EDE_NONE;
792
0
  msg->rep->rrsets[0] = packed_rrset_copy_region(rrset, region, now);
793
0
  if(!msg->rep->rrsets[0]) /* copy DNAME */
794
0
    return NULL;
795
  /* synth CNAME rrset */
796
0
  get_cname_target(rrset, &dtarg, &dtarglen);
797
0
  if(!dtarg)
798
0
    return NULL;
799
0
  newlen = q->qname_len + dtarglen - rrset->rk.dname_len;
800
0
  if(newlen > LDNS_MAX_DOMAINLEN) {
801
0
    msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
802
0
    return msg;
803
0
  }
804
0
  newname = (uint8_t*)regional_alloc(region, newlen);
805
0
  if(!newname)
806
0
    return NULL;
807
  /* new name is concatenation of qname front (without DNAME owner)
808
   * and DNAME target name */
809
0
  memcpy(newname, q->qname, q->qname_len-rrset->rk.dname_len);
810
0
  memmove(newname+(q->qname_len-rrset->rk.dname_len), dtarg, dtarglen);
811
  /* create rest of CNAME rrset */
812
0
  ck = (struct ub_packed_rrset_key*)regional_alloc(region, 
813
0
    sizeof(struct ub_packed_rrset_key));
814
0
  if(!ck)
815
0
    return NULL;
816
0
  memset(&ck->entry, 0, sizeof(ck->entry));
817
0
  msg->rep->rrsets[1] = ck;
818
0
  ck->entry.key = ck;
819
0
  ck->rk.type = htons(LDNS_RR_TYPE_CNAME);
820
0
  ck->rk.rrset_class = rrset->rk.rrset_class;
821
0
  ck->rk.flags = 0;
822
0
  ck->rk.dname = regional_alloc_init(region, q->qname, q->qname_len);
823
0
  if(!ck->rk.dname)
824
0
    return NULL;
825
0
  ck->rk.dname_len = q->qname_len;
826
0
  ck->entry.hash = rrset_key_hash(&ck->rk);
827
0
  newd = (struct packed_rrset_data*)regional_alloc_zero(region,
828
0
    sizeof(struct packed_rrset_data) + sizeof(size_t) + 
829
0
    sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t) 
830
0
    + newlen);
831
0
  if(!newd)
832
0
    return NULL;
833
0
  ck->entry.data = newd;
834
0
  newd->ttl = d->ttl - now; /* RFC6672: synth CNAME TTL == DNAME TTL */
835
0
  newd->count = 1;
836
0
  newd->rrsig_count = 0;
837
0
  newd->trust = rrset_trust_ans_noAA;
838
0
  newd->rr_len = (size_t*)((uint8_t*)newd + 
839
0
    sizeof(struct packed_rrset_data));
840
0
  newd->rr_len[0] = newlen + sizeof(uint16_t);
841
0
  packed_rrset_ptr_fixup(newd);
842
0
  newd->rr_ttl[0] = newd->ttl;
843
0
  msg->rep->ttl = newd->ttl;
844
0
  msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(newd->ttl);
845
0
  msg->rep->serve_expired_ttl = newd->ttl + SERVE_EXPIRED_TTL;
846
0
  sldns_write_uint16(newd->rr_data[0], newlen);
847
0
  memmove(newd->rr_data[0] + sizeof(uint16_t), newname, newlen);
848
0
  msg->rep->an_numrrsets ++;
849
0
  msg->rep->rrset_count ++;
850
0
  return msg;
851
0
}
852
853
/** Fill TYPE_ANY response with some data from cache */
854
static struct dns_msg*
855
fill_any(struct module_env* env,
856
  uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
857
  struct regional* region)
858
0
{
859
0
  time_t now = *env->now;
860
0
  struct dns_msg* msg = NULL;
861
0
  uint16_t lookup[] = {LDNS_RR_TYPE_A, LDNS_RR_TYPE_AAAA,
862
0
    LDNS_RR_TYPE_MX, LDNS_RR_TYPE_SOA, LDNS_RR_TYPE_NS,
863
0
    LDNS_RR_TYPE_DNAME, 0};
864
0
  int i, num=6; /* number of RR types to look up */
865
0
  log_assert(lookup[num] == 0);
866
867
0
  if(env->cfg->deny_any) {
868
    /* return empty message */
869
0
    msg = dns_msg_create(qname, qnamelen, qtype, qclass,
870
0
      region, 0);
871
0
    if(!msg) {
872
0
      return NULL;
873
0
    }
874
    /* set NOTIMPL for RFC 8482 */
875
0
    msg->rep->flags |= LDNS_RCODE_NOTIMPL;
876
0
    msg->rep->security = sec_status_indeterminate;
877
0
    msg->rep->ttl = 1; /* empty NOTIMPL response will never be
878
            * updated with rrsets, set TTL to 1 */
879
0
    return msg;
880
0
  }
881
882
0
  for(i=0; i<num; i++) {
883
    /* look up this RR for inclusion in type ANY response */
884
0
    struct ub_packed_rrset_key* rrset = rrset_cache_lookup(
885
0
      env->rrset_cache, qname, qnamelen, lookup[i],
886
0
      qclass, 0, now, 0);
887
0
    struct packed_rrset_data *d;
888
0
    if(!rrset)
889
0
      continue;
890
891
    /* only if rrset from answer section */
892
0
    d = (struct packed_rrset_data*)rrset->entry.data;
893
0
    if(d->trust == rrset_trust_add_noAA ||
894
0
      d->trust == rrset_trust_auth_noAA ||
895
0
      d->trust == rrset_trust_add_AA ||
896
0
      d->trust == rrset_trust_auth_AA) {
897
0
      lock_rw_unlock(&rrset->entry.lock);
898
0
      continue;
899
0
    }
900
901
    /* create msg if none */
902
0
    if(!msg) {
903
0
      msg = dns_msg_create(qname, qnamelen, qtype, qclass,
904
0
        region, (size_t)(num-i));
905
0
      if(!msg) {
906
0
        lock_rw_unlock(&rrset->entry.lock);
907
0
        return NULL;
908
0
      }
909
0
    }
910
911
    /* add RRset to response */
912
0
    if(!dns_msg_ansadd(msg, region, rrset, now)) {
913
0
      lock_rw_unlock(&rrset->entry.lock);
914
0
      return NULL;
915
0
    }
916
0
    lock_rw_unlock(&rrset->entry.lock);
917
0
  }
918
0
  return msg;
919
0
}
920
921
struct dns_msg* 
922
dns_cache_lookup(struct module_env* env,
923
  uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
924
  uint16_t flags, struct regional* region, struct regional* scratch,
925
  int no_partial, uint8_t* dpname, size_t dpnamelen)
926
0
{
927
0
  struct lruhash_entry* e;
928
0
  struct query_info k;
929
0
  hashvalue_type h;
930
0
  time_t now = *env->now;
931
0
  struct ub_packed_rrset_key* rrset;
932
933
  /* lookup first, this has both NXdomains and ANSWER responses */
934
0
  k.qname = qname;
935
0
  k.qname_len = qnamelen;
936
0
  k.qtype = qtype;
937
0
  k.qclass = qclass;
938
0
  k.local_alias = NULL;
939
0
  h = query_info_hash(&k, flags);
940
0
  e = slabhash_lookup(env->msg_cache, h, &k, 0);
941
0
  if(e) {
942
0
    struct msgreply_entry* key = (struct msgreply_entry*)e->key;
943
0
    struct reply_info* data = (struct reply_info*)e->data;
944
0
    struct dns_msg* msg = tomsg(env, &key->key, data, region, now, 0,
945
0
      scratch);
946
0
    if(msg) {
947
0
      lock_rw_unlock(&e->lock);
948
0
      return msg;
949
0
    }
950
    /* could be msg==NULL; due to TTL or not all rrsets available */
951
0
    lock_rw_unlock(&e->lock);
952
0
  }
953
954
  /* see if a DNAME exists. Checked for first, to enforce that DNAMEs
955
   * are more important, the CNAME is resynthesized and thus 
956
   * consistent with the DNAME */
957
0
  if(!no_partial &&
958
0
    (rrset=find_closest_of_type(env, qname, qnamelen, qclass, now,
959
0
    LDNS_RR_TYPE_DNAME, 1, 0, NULL, 0))) {
960
    /* synthesize a DNAME+CNAME message based on this */
961
0
    enum sec_status sec_status = sec_status_unchecked;
962
0
    struct dns_msg* msg = synth_dname_msg(rrset, region, now, &k,
963
0
      &sec_status);
964
0
    if(msg) {
965
0
      struct ub_packed_rrset_key* cname_rrset;
966
0
      lock_rw_unlock(&rrset->entry.lock);
967
      /* now, after unlocking the DNAME rrset lock,
968
       * check the sec_status, and see if we need to look
969
       * up the CNAME record associated before it can
970
       * be used */
971
      /* normally, only secure DNAMEs allowed from cache*/
972
0
      if(sec_status == sec_status_secure)
973
0
        return msg;
974
      /* but if we have a CNAME cached with this name, then we
975
       * have previously already allowed this name to pass.
976
       * the next cache lookup is going to fetch that CNAME itself,
977
       * but it is better to have the (unsigned)DNAME + CNAME in
978
       * that case */
979
0
      cname_rrset = rrset_cache_lookup(
980
0
        env->rrset_cache, qname, qnamelen,
981
0
        LDNS_RR_TYPE_CNAME, qclass, 0, now, 0);
982
0
      if(cname_rrset) {
983
        /* CNAME already synthesized by
984
         * synth_dname_msg routine, so we can
985
         * straight up return the msg */
986
0
        lock_rw_unlock(&cname_rrset->entry.lock);
987
0
        return msg;
988
0
      }
989
0
    } else {
990
0
      lock_rw_unlock(&rrset->entry.lock);
991
0
    }
992
0
  }
993
994
  /* see if we have CNAME for this domain,
995
   * but not for DS records (which are part of the parent) */
996
0
  if(!no_partial && qtype != LDNS_RR_TYPE_DS &&
997
0
     (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen, 
998
0
    LDNS_RR_TYPE_CNAME, qclass, 0, now, 0))) {
999
0
    uint8_t* wc = NULL;
1000
0
    size_t wl;
1001
    /* if the rrset is not a wildcard expansion, with wcname */
1002
    /* because, if we return that CNAME rrset on its own, it is
1003
     * missing the NSEC or NSEC3 proof */
1004
0
    if(!(val_rrset_wildcard(rrset, &wc, &wl) && wc != NULL)) {
1005
0
      struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
1006
0
      if(msg) {
1007
0
        lock_rw_unlock(&rrset->entry.lock);
1008
0
        return msg;
1009
0
      }
1010
0
    }
1011
0
    lock_rw_unlock(&rrset->entry.lock);
1012
0
  }
1013
1014
  /* construct DS, DNSKEY messages from rrset cache. */
1015
0
  if((qtype == LDNS_RR_TYPE_DS || qtype == LDNS_RR_TYPE_DNSKEY) &&
1016
0
    (rrset=rrset_cache_lookup(env->rrset_cache, qname, qnamelen, 
1017
0
    qtype, qclass, 0, now, 0))) {
1018
    /* if the rrset is from the additional section, and the
1019
     * signatures have fallen off, then do not synthesize a msg
1020
     * instead, allow a full query for signed results to happen.
1021
     * Forego all rrset data from additional section, because
1022
     * some signatures may not be present and cause validation
1023
     * failure.
1024
     */
1025
0
    struct packed_rrset_data *d = (struct packed_rrset_data*)
1026
0
      rrset->entry.data;
1027
0
    if(d->trust != rrset_trust_add_noAA && 
1028
0
      d->trust != rrset_trust_add_AA && 
1029
0
      (qtype == LDNS_RR_TYPE_DS || 
1030
0
        (d->trust != rrset_trust_auth_noAA 
1031
0
        && d->trust != rrset_trust_auth_AA) )) {
1032
0
      struct dns_msg* msg = rrset_msg(rrset, region, now, &k);
1033
0
      if(msg) {
1034
0
        lock_rw_unlock(&rrset->entry.lock);
1035
0
        return msg;
1036
0
      }
1037
0
    }
1038
0
    lock_rw_unlock(&rrset->entry.lock);
1039
0
  }
1040
1041
  /* stop downwards cache search on NXDOMAIN.
1042
   * Empty nonterminals are NOERROR, so an NXDOMAIN for foo
1043
   * means bla.foo also does not exist.  The DNSSEC proofs are
1044
   * the same.  We search upwards for NXDOMAINs. */
1045
0
  if(env->cfg->harden_below_nxdomain) {
1046
0
    while(!dname_is_root(k.qname)) {
1047
0
      if(dpname && dpnamelen
1048
0
        && !dname_subdomain_c(k.qname, dpname))
1049
0
        break; /* no synth nxdomain above the stub */
1050
0
      dname_remove_label(&k.qname, &k.qname_len);
1051
0
      h = query_info_hash(&k, flags);
1052
0
      e = slabhash_lookup(env->msg_cache, h, &k, 0);
1053
0
      if(!e && k.qtype != LDNS_RR_TYPE_A &&
1054
0
        env->cfg->qname_minimisation) {
1055
0
        k.qtype = LDNS_RR_TYPE_A;
1056
0
        h = query_info_hash(&k, flags);
1057
0
        e = slabhash_lookup(env->msg_cache, h, &k, 0);
1058
0
      }
1059
0
      if(e) {
1060
0
        struct reply_info* data = (struct reply_info*)e->data;
1061
0
        struct dns_msg* msg;
1062
0
        if(FLAGS_GET_RCODE(data->flags) == LDNS_RCODE_NXDOMAIN
1063
0
          && data->security == sec_status_secure
1064
0
          && (data->an_numrrsets == 0 ||
1065
0
            ntohs(data->rrsets[0]->rk.type) != LDNS_RR_TYPE_CNAME)
1066
0
          && (msg=tomsg(env, &k, data, region, now, 0, scratch))) {
1067
0
          lock_rw_unlock(&e->lock);
1068
0
          msg->qinfo.qname=qname;
1069
0
          msg->qinfo.qname_len=qnamelen;
1070
          /* check that DNSSEC really works out */
1071
0
          msg->rep->security = sec_status_unchecked;
1072
0
          iter_scrub_nxdomain(msg);
1073
0
          return msg;
1074
0
        }
1075
0
        lock_rw_unlock(&e->lock);
1076
0
      }
1077
0
      k.qtype = qtype;
1078
0
    }
1079
0
  }
1080
1081
  /* fill common RR types for ANY response to avoid requery */
1082
0
  if(qtype == LDNS_RR_TYPE_ANY) {
1083
0
    return fill_any(env, qname, qnamelen, qtype, qclass, region);
1084
0
  }
1085
1086
0
  return NULL;
1087
0
}
1088
1089
int
1090
dns_cache_store(struct module_env* env, struct query_info* msgqinf,
1091
  struct reply_info* msgrep, int is_referral, time_t leeway, int pside,
1092
  struct regional* region, uint32_t flags, time_t qstarttime,
1093
  int is_valrec)
1094
0
{
1095
0
  struct reply_info* rep = NULL;
1096
0
  if(SERVE_EXPIRED) {
1097
    /* We are serving expired records. Before caching, check if a
1098
     * useful expired record exists. */
1099
0
    struct msgreply_entry* e = msg_cache_lookup(env,
1100
0
      msgqinf->qname, msgqinf->qname_len, msgqinf->qtype,
1101
0
      msgqinf->qclass, flags, 0, 1);
1102
0
    if(e) {
1103
0
      struct reply_info* cached = e->entry.data;
1104
0
      if(TTL_IS_EXPIRED(cached->ttl, *env->now)
1105
0
        && reply_info_could_use_expired(cached, *env->now)
1106
        /* If we are validating make sure only
1107
         * validating modules can update such messages.
1108
         * In that case don't cache it and let a
1109
         * subsequent module handle the caching. For
1110
         * example, the iterator should not replace an
1111
         * expired secure answer with a fresh unchecked
1112
         * one and let the validator manage caching. */
1113
0
        && cached->security != sec_status_bogus
1114
0
        && (env->need_to_validate &&
1115
0
        msgrep->security == sec_status_unchecked)
1116
        /* Exceptions to that rule are:
1117
         * o recursions that don't need validation but
1118
         *   need to update the cache for coherence
1119
         *   (delegation information while iterating,
1120
         *   DNSKEY and DS lookups from validator)
1121
         * o explicit RRSIG queries that are not
1122
         *   validated. */
1123
0
        && !is_valrec
1124
0
        && msgqinf->qtype != LDNS_RR_TYPE_RRSIG) {
1125
0
        if((int)FLAGS_GET_RCODE(msgrep->flags) !=
1126
0
          LDNS_RCODE_NOERROR &&
1127
0
          (int)FLAGS_GET_RCODE(msgrep->flags) !=
1128
0
          LDNS_RCODE_NXDOMAIN) {
1129
          /* The current response has an
1130
           * erroneous rcode. Adjust norec time
1131
           * so that additional lookups are not
1132
           * performed for some time. */
1133
0
          verbose(VERB_ALGO, "set "
1134
0
            "serve-expired-norec-ttl for "
1135
0
            "response in cache");
1136
0
          cached->serve_expired_norec_ttl =
1137
0
            NORR_TTL + *env->now;
1138
0
          if(env->cfg->serve_expired_ttl_reset &&
1139
0
              cached->serve_expired_ttl
1140
0
              < *env->now +
1141
0
              env->cfg->serve_expired_ttl) {
1142
            /* Reset serve-expired-ttl for
1143
             * valid response in cache. */
1144
0
            verbose(VERB_ALGO, "reset "
1145
0
              "serve-expired-ttl "
1146
0
              "for response in cache");
1147
0
            cached->serve_expired_ttl =
1148
0
                *env->now +
1149
0
                env->cfg->serve_expired_ttl;
1150
0
          }
1151
0
        }
1152
0
        verbose(VERB_ALGO, "a validated expired entry "
1153
0
          "could be overwritten, skip caching "
1154
0
          "the new message at this stage");
1155
0
        lock_rw_unlock(&e->entry.lock);
1156
0
        return 1;
1157
0
      }
1158
0
      lock_rw_unlock(&e->entry.lock);
1159
0
    }
1160
0
  }
1161
  /* alloc, malloc properly (not in region, like msg is) */
1162
0
  rep = reply_info_copy(msgrep, env->alloc, NULL);
1163
0
  if(!rep)
1164
0
    return 0;
1165
  /* ttl must be relative ;i.e. 0..86400 not  time(0)+86400.
1166
   * the env->now is added to message and RRsets in this routine. */
1167
  /* the leeway is used to invalidate other rrsets earlier */
1168
0
  if(is_referral) {
1169
    /* store rrsets */
1170
0
    struct rrset_ref ref;
1171
0
    size_t i;
1172
0
    for(i=0; i<rep->rrset_count; i++) {
1173
0
      packed_rrset_ttl_add((struct packed_rrset_data*)
1174
0
        rep->rrsets[i]->entry.data, *env->now);
1175
0
      ref.key = rep->rrsets[i];
1176
0
      ref.id = rep->rrsets[i]->id;
1177
      /*ignore ret: it was in the cache, ref updated */
1178
      /* no leeway for typeNS */
1179
0
      (void)rrset_cache_update(env->rrset_cache, &ref, 
1180
0
        env->alloc,
1181
0
        ((ntohs(ref.key->rk.type)==LDNS_RR_TYPE_NS
1182
0
         && !pside) ? qstarttime:*env->now + leeway));
1183
0
    }
1184
0
    reply_info_delete(rep, NULL);
1185
0
    return 1;
1186
0
  } else {
1187
    /* store msg, and rrsets */
1188
0
    struct query_info qinf;
1189
0
    hashvalue_type h;
1190
1191
0
    qinf = *msgqinf;
1192
0
    qinf.qname = memdup(msgqinf->qname, msgqinf->qname_len);
1193
0
    if(!qinf.qname) {
1194
0
      reply_info_parsedelete(rep, env->alloc);
1195
0
      return 0;
1196
0
    }
1197
    /* fixup flags to be sensible for a reply based on the cache */
1198
    /* this module means that RA is available. It is an answer QR. 
1199
     * Not AA from cache. Not CD in cache (depends on client bit). */
1200
0
    rep->flags |= (BIT_RA | BIT_QR);
1201
0
    rep->flags &= ~(BIT_AA | BIT_CD);
1202
0
    h = query_info_hash(&qinf, (uint16_t)flags);
1203
0
    dns_cache_store_msg(env, &qinf, h, rep, leeway, pside, msgrep,
1204
0
      flags, region, qstarttime);
1205
    /* qname is used inside query_info_entrysetup, and set to 
1206
     * NULL. If it has not been used, free it. free(0) is safe. */
1207
0
    free(qinf.qname);
1208
0
  }
1209
0
  return 1;
1210
0
}
1211
1212
int 
1213
dns_cache_prefetch_adjust(struct module_env* env, struct query_info* qinfo,
1214
        time_t adjust, uint16_t flags)
1215
0
{
1216
0
  struct msgreply_entry* msg;
1217
0
  msg = msg_cache_lookup(env, qinfo->qname, qinfo->qname_len,
1218
0
    qinfo->qtype, qinfo->qclass, flags, *env->now, 1);
1219
0
  if(msg) {
1220
0
    struct reply_info* rep = (struct reply_info*)msg->entry.data;
1221
0
    if(rep) {
1222
0
      rep->prefetch_ttl += adjust;
1223
0
      lock_rw_unlock(&msg->entry.lock);
1224
0
      return 1;
1225
0
    }
1226
0
    lock_rw_unlock(&msg->entry.lock);
1227
0
  }
1228
0
  return 0;
1229
0
}