Coverage Report

Created: 2025-08-29 06:30

/src/unbound/iterator/iterator.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * iterator/iterator.c - iterative resolver DNS query response module
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 a module that performs recursive iterative DNS query
40
 * processing.
41
 */
42
43
#include "config.h"
44
#include "iterator/iterator.h"
45
#include "iterator/iter_utils.h"
46
#include "iterator/iter_hints.h"
47
#include "iterator/iter_fwd.h"
48
#include "iterator/iter_donotq.h"
49
#include "iterator/iter_delegpt.h"
50
#include "iterator/iter_resptype.h"
51
#include "iterator/iter_scrub.h"
52
#include "iterator/iter_priv.h"
53
#include "validator/val_neg.h"
54
#include "services/cache/dns.h"
55
#include "services/cache/rrset.h"
56
#include "services/cache/infra.h"
57
#include "services/authzone.h"
58
#include "util/module.h"
59
#include "util/netevent.h"
60
#include "util/net_help.h"
61
#include "util/regional.h"
62
#include "util/data/dname.h"
63
#include "util/data/msgencode.h"
64
#include "util/fptr_wlist.h"
65
#include "util/config_file.h"
66
#include "util/random.h"
67
#include "sldns/rrdef.h"
68
#include "sldns/wire2str.h"
69
#include "sldns/str2wire.h"
70
#include "sldns/parseutil.h"
71
#include "sldns/sbuffer.h"
72
73
/* number of packets */
74
int MAX_GLOBAL_QUOTA = 200;
75
/* in msec */
76
int UNKNOWN_SERVER_NICENESS = 376;
77
/* in msec */
78
int USEFUL_SERVER_TOP_TIMEOUT = 120000;
79
/* Equals USEFUL_SERVER_TOP_TIMEOUT*4 */
80
int BLACKLIST_PENALTY = (120000*4);
81
/** Timeout when only a single probe query per IP is allowed. */
82
int PROBE_MAXRTO = PROBE_MAXRTO_DEFAULT; /* in msec */
83
84
static void target_count_increase_nx(struct iter_qstate* iq, int num);
85
86
int 
87
iter_init(struct module_env* env, int id)
88
0
{
89
0
  struct iter_env* iter_env = (struct iter_env*)calloc(1,
90
0
    sizeof(struct iter_env));
91
0
  if(!iter_env) {
92
0
    log_err("malloc failure");
93
0
    return 0;
94
0
  }
95
0
  env->modinfo[id] = (void*)iter_env;
96
97
0
  lock_basic_init(&iter_env->queries_ratelimit_lock);
98
0
  lock_protect(&iter_env->queries_ratelimit_lock,
99
0
      &iter_env->num_queries_ratelimited,
100
0
    sizeof(iter_env->num_queries_ratelimited));
101
102
0
  if(!iter_apply_cfg(iter_env, env->cfg)) {
103
0
    log_err("iterator: could not apply configuration settings.");
104
0
    return 0;
105
0
  }
106
107
0
  return 1;
108
0
}
109
110
void 
111
iter_deinit(struct module_env* env, int id)
112
0
{
113
0
  struct iter_env* iter_env;
114
0
  if(!env || !env->modinfo[id])
115
0
    return;
116
0
  iter_env = (struct iter_env*)env->modinfo[id];
117
0
  lock_basic_destroy(&iter_env->queries_ratelimit_lock);
118
0
  free(iter_env->target_fetch_policy);
119
0
  priv_delete(iter_env->priv);
120
0
  donotq_delete(iter_env->donotq);
121
0
  caps_white_delete(iter_env->caps_white);
122
0
  free(iter_env);
123
0
  env->modinfo[id] = NULL;
124
0
}
125
126
/** new query for iterator */
127
static int
128
iter_new(struct module_qstate* qstate, int id)
129
0
{
130
0
  struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
131
0
    qstate->region, sizeof(struct iter_qstate));
132
0
  qstate->minfo[id] = iq;
133
0
  if(!iq) 
134
0
    return 0;
135
0
  memset(iq, 0, sizeof(*iq));
136
0
  iq->state = INIT_REQUEST_STATE;
137
0
  iq->final_state = FINISHED_STATE;
138
0
  iq->an_prepend_list = NULL;
139
0
  iq->an_prepend_last = NULL;
140
0
  iq->ns_prepend_list = NULL;
141
0
  iq->ns_prepend_last = NULL;
142
0
  iq->dp = NULL;
143
0
  iq->depth = 0;
144
0
  iq->num_target_queries = 0;
145
0
  iq->num_current_queries = 0;
146
0
  iq->query_restart_count = 0;
147
0
  iq->referral_count = 0;
148
0
  iq->sent_count = 0;
149
0
  iq->ratelimit_ok = 0;
150
0
  iq->target_count = NULL;
151
0
  iq->dp_target_count = 0;
152
0
  iq->wait_priming_stub = 0;
153
0
  iq->refetch_glue = 0;
154
0
  iq->dnssec_expected = 0;
155
0
  iq->dnssec_lame_query = 0;
156
0
  iq->chase_flags = qstate->query_flags;
157
  /* Start with the (current) qname. */
158
0
  iq->qchase = qstate->qinfo;
159
0
  outbound_list_init(&iq->outlist);
160
0
  iq->minimise_count = 0;
161
0
  iq->timeout_count = 0;
162
0
  if (qstate->env->cfg->qname_minimisation)
163
0
    iq->minimisation_state = INIT_MINIMISE_STATE;
164
0
  else
165
0
    iq->minimisation_state = DONOT_MINIMISE_STATE;
166
  
167
0
  memset(&iq->qinfo_out, 0, sizeof(struct query_info));
168
0
  return 1;
169
0
}
170
171
/**
172
 * Transition to the next state. This can be used to advance a currently
173
 * processing event. It cannot be used to reactivate a forEvent.
174
 *
175
 * @param iq: iterator query state
176
 * @param nextstate The state to transition to.
177
 * @return true. This is so this can be called as the return value for the
178
 *         actual process*State() methods. (Transitioning to the next state
179
 *         implies further processing).
180
 */
181
static int
182
next_state(struct iter_qstate* iq, enum iter_state nextstate)
183
0
{
184
  /* If transitioning to a "response" state, make sure that there is a
185
   * response */
186
0
  if(iter_state_is_responsestate(nextstate)) {
187
0
    if(iq->response == NULL) {
188
0
      log_err("transitioning to response state sans "
189
0
        "response.");
190
0
    }
191
0
  }
192
0
  iq->state = nextstate;
193
0
  return 1;
194
0
}
195
196
/**
197
 * Transition an event to its final state. Final states always either return
198
 * a result up the module chain, or reactivate a dependent event. Which
199
 * final state to transition to is set in the module state for the event when
200
 * it was created, and depends on the original purpose of the event.
201
 *
202
 * The response is stored in the qstate->buf buffer.
203
 *
204
 * @param iq: iterator query state
205
 * @return false. This is so this method can be used as the return value for
206
 *         the processState methods. (Transitioning to the final state
207
 */
208
static int
209
final_state(struct iter_qstate* iq)
210
0
{
211
0
  return next_state(iq, iq->final_state);
212
0
}
213
214
/**
215
 * Callback routine to handle errors in parent query states
216
 * @param qstate: query state that failed.
217
 * @param id: module id.
218
 * @param super: super state.
219
 */
220
static void
221
error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
222
0
{
223
0
  struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
224
0
  struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
225
226
0
  if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
227
0
    qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
228
    /* mark address as failed. */
229
0
    struct delegpt_ns* dpns = NULL;
230
0
    super_iq->num_target_queries--; 
231
0
    if(super_iq->dp)
232
0
      dpns = delegpt_find_ns(super_iq->dp, 
233
0
        qstate->qinfo.qname, qstate->qinfo.qname_len);
234
0
    if(!dpns) {
235
      /* not interested */
236
      /* this can happen, for eg. qname minimisation asked
237
       * for an NXDOMAIN to be validated, and used qtype
238
       * A for that, and the error of that, the name, is
239
       * not listed in super_iq->dp */
240
0
      verbose(VERB_ALGO, "subq error, but not interested");
241
0
      log_query_info(VERB_ALGO, "superq", &super->qinfo);
242
0
      return;
243
0
    } else {
244
      /* see if the failure did get (parent-lame) info */
245
0
      if(!cache_fill_missing(super->env, super_iq->qchase.qclass,
246
0
        super->region, super_iq->dp, 0))
247
0
        log_err("out of memory adding missing");
248
0
    }
249
0
    delegpt_mark_neg(dpns, qstate->qinfo.qtype);
250
0
    if((dpns->got4 == 2 || (!ie->supports_ipv4 && !ie->nat64.use_nat64)) &&
251
0
      (dpns->got6 == 2 || !ie->supports_ipv6)) {
252
0
      dpns->resolved = 1; /* mark as failed */
253
0
      target_count_increase_nx(super_iq, 1);
254
0
    }
255
0
  }
256
0
  if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
257
    /* prime failed to get delegation */
258
0
    super_iq->dp = NULL;
259
0
  }
260
  /* evaluate targets again */
261
0
  super_iq->state = QUERYTARGETS_STATE; 
262
  /* super becomes runnable, and will process this change */
263
0
}
264
265
/**
266
 * Return an error to the client
267
 * @param qstate: our query state
268
 * @param id: module id
269
 * @param rcode: error code (DNS errcode).
270
 * @return: 0 for use by caller, to make notation easy, like:
271
 *  return error_response(..). 
272
 */
273
static int
274
error_response(struct module_qstate* qstate, int id, int rcode)
275
0
{
276
0
  verbose(VERB_QUERY, "return error response %s", 
277
0
    sldns_lookup_by_id(sldns_rcodes, rcode)?
278
0
    sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
279
0
  qstate->return_rcode = rcode;
280
0
  qstate->return_msg = NULL;
281
0
  qstate->ext_state[id] = module_finished;
282
0
  return 0;
283
0
}
284
285
/**
286
 * Return an error to the client and cache the error code in the
287
 * message cache (so per qname, qtype, qclass).
288
 * @param qstate: our query state
289
 * @param id: module id
290
 * @param rcode: error code (DNS errcode).
291
 * @return: 0 for use by caller, to make notation easy, like:
292
 *  return error_response(..). 
293
 */
294
static int
295
error_response_cache(struct module_qstate* qstate, int id, int rcode)
296
0
{
297
0
  struct reply_info err;
298
0
  struct msgreply_entry* msg;
299
0
  if(qstate->no_cache_store) {
300
0
    return error_response(qstate, id, rcode);
301
0
  }
302
0
  if(qstate->prefetch_leeway > NORR_TTL) {
303
0
    verbose(VERB_ALGO, "error response for prefetch in cache");
304
    /* attempt to adjust the cache entry prefetch */
305
0
    if(dns_cache_prefetch_adjust(qstate->env, &qstate->qinfo,
306
0
      NORR_TTL, qstate->query_flags))
307
0
      return error_response(qstate, id, rcode);
308
    /* if that fails (not in cache), fall through to store err */
309
0
  }
310
0
  if((msg=msg_cache_lookup(qstate->env,
311
0
    qstate->qinfo.qname, qstate->qinfo.qname_len,
312
0
    qstate->qinfo.qtype, qstate->qinfo.qclass,
313
0
    qstate->query_flags, 0,
314
0
    qstate->env->cfg->serve_expired)) != NULL) {
315
0
    struct reply_info* rep = (struct reply_info*)msg->entry.data;
316
0
    if(qstate->env->cfg->serve_expired && rep) {
317
0
      if(qstate->env->cfg->serve_expired_ttl_reset &&
318
0
        *qstate->env->now + qstate->env->cfg->serve_expired_ttl
319
0
        > rep->serve_expired_ttl) {
320
0
        verbose(VERB_ALGO, "reset serve-expired-ttl for "
321
0
          "response in cache");
322
0
        rep->serve_expired_ttl = *qstate->env->now +
323
0
          qstate->env->cfg->serve_expired_ttl;
324
0
      }
325
0
      verbose(VERB_ALGO, "set serve-expired-norec-ttl for "
326
0
        "response in cache");
327
0
      rep->serve_expired_norec_ttl = NORR_TTL +
328
0
        *qstate->env->now;
329
0
    }
330
0
    if(rep && (FLAGS_GET_RCODE(rep->flags) ==
331
0
      LDNS_RCODE_NOERROR ||
332
0
      FLAGS_GET_RCODE(rep->flags) ==
333
0
      LDNS_RCODE_NXDOMAIN ||
334
0
      FLAGS_GET_RCODE(rep->flags) ==
335
0
      LDNS_RCODE_YXDOMAIN) &&
336
0
      (qstate->env->cfg->serve_expired ||
337
0
      *qstate->env->now <= rep->ttl)) {
338
      /* we have a good entry, don't overwrite */
339
0
      lock_rw_unlock(&msg->entry.lock);
340
0
      return error_response(qstate, id, rcode);
341
0
    }
342
0
    lock_rw_unlock(&msg->entry.lock);
343
    /* nothing interesting is cached (already error response or
344
     * expired good record when we don't serve expired), so this
345
     * servfail cache entry is useful (stops waste of time on this
346
     * servfail NORR_TTL) */
347
0
  }
348
  /* store in cache */
349
0
  memset(&err, 0, sizeof(err));
350
0
  err.flags = (uint16_t)(BIT_QR | BIT_RA);
351
0
  FLAGS_SET_RCODE(err.flags, rcode);
352
0
  err.qdcount = 1;
353
0
  err.ttl = NORR_TTL;
354
0
  err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
355
0
  err.serve_expired_ttl = NORR_TTL;
356
  /* do not waste time trying to validate this servfail */
357
0
  err.security = sec_status_indeterminate;
358
0
  verbose(VERB_ALGO, "store error response in message cache");
359
0
  iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL,
360
0
    qstate->query_flags, qstate->qstarttime, qstate->is_valrec);
361
0
  return error_response(qstate, id, rcode);
362
0
}
363
364
/** check if prepend item is duplicate item */
365
static int
366
prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
367
  struct ub_packed_rrset_key* dup)
368
0
{
369
0
  size_t i;
370
0
  for(i=0; i<to; i++) {
371
0
    if(sets[i]->rk.type == dup->rk.type &&
372
0
      sets[i]->rk.rrset_class == dup->rk.rrset_class &&
373
0
      sets[i]->rk.dname_len == dup->rk.dname_len &&
374
0
      query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
375
0
      == 0)
376
0
      return 1;
377
0
  }
378
0
  return 0;
379
0
}
380
381
/** prepend the prepend list in the answer and authority section of dns_msg */
382
static int
383
iter_prepend(struct iter_qstate* iq, struct dns_msg* msg, 
384
  struct regional* region)
385
0
{
386
0
  struct iter_prep_list* p;
387
0
  struct ub_packed_rrset_key** sets;
388
0
  size_t num_an = 0, num_ns = 0;;
389
0
  for(p = iq->an_prepend_list; p; p = p->next)
390
0
    num_an++;
391
0
  for(p = iq->ns_prepend_list; p; p = p->next)
392
0
    num_ns++;
393
0
  if(num_an + num_ns == 0)
394
0
    return 1;
395
0
  verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
396
0
  if(num_an > RR_COUNT_MAX || num_ns > RR_COUNT_MAX ||
397
0
    msg->rep->rrset_count > RR_COUNT_MAX) return 0; /* overflow */
398
0
  sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
399
0
    sizeof(struct ub_packed_rrset_key*));
400
0
  if(!sets) 
401
0
    return 0;
402
  /* ANSWER section */
403
0
  num_an = 0;
404
0
  for(p = iq->an_prepend_list; p; p = p->next) {
405
0
    sets[num_an++] = p->rrset;
406
0
    if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl) {
407
0
      msg->rep->ttl = ub_packed_rrset_ttl(p->rrset);
408
0
      msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
409
0
      msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
410
0
    }
411
0
  }
412
0
  memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
413
0
    sizeof(struct ub_packed_rrset_key*));
414
  /* AUTH section */
415
0
  num_ns = 0;
416
0
  for(p = iq->ns_prepend_list; p; p = p->next) {
417
0
    if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
418
0
      num_ns, p->rrset) || prepend_is_duplicate(
419
0
      msg->rep->rrsets+msg->rep->an_numrrsets, 
420
0
      msg->rep->ns_numrrsets, p->rrset))
421
0
      continue;
422
0
    sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
423
0
    if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl) {
424
0
      msg->rep->ttl = ub_packed_rrset_ttl(p->rrset);
425
0
      msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
426
0
      msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
427
0
    }
428
0
  }
429
0
  memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns, 
430
0
    msg->rep->rrsets + msg->rep->an_numrrsets, 
431
0
    (msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
432
0
    sizeof(struct ub_packed_rrset_key*));
433
434
  /* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
435
   * this is what recursors should give. */
436
0
  msg->rep->rrset_count += num_an + num_ns;
437
0
  msg->rep->an_numrrsets += num_an;
438
0
  msg->rep->ns_numrrsets += num_ns;
439
0
  msg->rep->rrsets = sets;
440
0
  return 1;
441
0
}
442
443
/**
444
 * Find rrset in ANSWER prepend list.
445
 * to avoid duplicate DNAMEs when a DNAME is traversed twice.
446
 * @param iq: iterator query state.
447
 * @param rrset: rrset to add.
448
 * @return false if not found
449
 */
450
static int
451
iter_find_rrset_in_prepend_answer(struct iter_qstate* iq,
452
  struct ub_packed_rrset_key* rrset)
453
0
{
454
0
  struct iter_prep_list* p = iq->an_prepend_list;
455
0
  while(p) {
456
0
    if(ub_rrset_compare(p->rrset, rrset) == 0 &&
457
0
      rrsetdata_equal((struct packed_rrset_data*)p->rrset
458
0
      ->entry.data, (struct packed_rrset_data*)rrset
459
0
      ->entry.data))
460
0
      return 1;
461
0
    p = p->next;
462
0
  }
463
0
  return 0;
464
0
}
465
466
/**
467
 * Add rrset to ANSWER prepend list
468
 * @param qstate: query state.
469
 * @param iq: iterator query state.
470
 * @param rrset: rrset to add.
471
 * @return false on failure (malloc).
472
 */
473
static int
474
iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
475
  struct ub_packed_rrset_key* rrset)
476
0
{
477
0
  struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
478
0
    qstate->region, sizeof(struct iter_prep_list));
479
0
  if(!p)
480
0
    return 0;
481
0
  p->rrset = rrset;
482
0
  p->next = NULL;
483
  /* add at end */
484
0
  if(iq->an_prepend_last)
485
0
    iq->an_prepend_last->next = p;
486
0
  else  iq->an_prepend_list = p;
487
0
  iq->an_prepend_last = p;
488
0
  return 1;
489
0
}
490
491
/**
492
 * Add rrset to AUTHORITY prepend list
493
 * @param qstate: query state.
494
 * @param iq: iterator query state.
495
 * @param rrset: rrset to add.
496
 * @return false on failure (malloc).
497
 */
498
static int
499
iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
500
  struct ub_packed_rrset_key* rrset)
501
0
{
502
0
  struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
503
0
    qstate->region, sizeof(struct iter_prep_list));
504
0
  if(!p)
505
0
    return 0;
506
0
  p->rrset = rrset;
507
0
  p->next = NULL;
508
  /* add at end */
509
0
  if(iq->ns_prepend_last)
510
0
    iq->ns_prepend_last->next = p;
511
0
  else  iq->ns_prepend_list = p;
512
0
  iq->ns_prepend_last = p;
513
0
  return 1;
514
0
}
515
516
/**
517
 * Given a CNAME response (defined as a response containing a CNAME or DNAME
518
 * that does not answer the request), process the response, modifying the
519
 * state as necessary. This follows the CNAME/DNAME chain and returns the
520
 * final query name.
521
 *
522
 * sets the new query name, after following the CNAME/DNAME chain.
523
 * @param qstate: query state.
524
 * @param iq: iterator query state.
525
 * @param msg: the response.
526
 * @param mname: returned target new query name.
527
 * @param mname_len: length of mname.
528
 * @return false on (malloc) error.
529
 */
530
static int
531
handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
532
        struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
533
0
{
534
0
  size_t i;
535
  /* Start with the (current) qname. */
536
0
  *mname = iq->qchase.qname;
537
0
  *mname_len = iq->qchase.qname_len;
538
539
  /* Iterate over the ANSWER rrsets in order, looking for CNAMEs and 
540
   * DNAMES. */
541
0
  for(i=0; i<msg->rep->an_numrrsets; i++) {
542
0
    struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
543
    /* If there is a (relevant) DNAME, add it to the list.
544
     * We always expect there to be CNAME that was generated 
545
     * by this DNAME following, so we don't process the DNAME 
546
     * directly.  */
547
0
    if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
548
0
      dname_strict_subdomain_c(*mname, r->rk.dname) &&
549
0
      !iter_find_rrset_in_prepend_answer(iq, r)) {
550
0
      if(!iter_add_prepend_answer(qstate, iq, r))
551
0
        return 0;
552
0
      continue;
553
0
    }
554
555
0
    if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
556
0
      query_dname_compare(*mname, r->rk.dname) == 0 &&
557
0
      !iter_find_rrset_in_prepend_answer(iq, r)) {
558
      /* Add this relevant CNAME rrset to the prepend list.*/
559
0
      if(!iter_add_prepend_answer(qstate, iq, r))
560
0
        return 0;
561
0
      get_cname_target(r, mname, mname_len);
562
0
    }
563
564
    /* Other rrsets in the section are ignored. */
565
0
  }
566
  /* add authority rrsets to authority prepend, for wildcarded CNAMEs */
567
0
  for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
568
0
    msg->rep->ns_numrrsets; i++) {
569
0
    struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
570
    /* only add NSEC/NSEC3, as they may be needed for validation */
571
0
    if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
572
0
      ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
573
0
      if(!iter_add_prepend_auth(qstate, iq, r))
574
0
        return 0;
575
0
    }
576
0
  }
577
0
  return 1;
578
0
}
579
580
/** fill fail address for later recovery */
581
static void
582
fill_fail_addr(struct iter_qstate* iq, struct sockaddr_storage* addr,
583
  socklen_t addrlen)
584
0
{
585
0
  if(addrlen == 0) {
586
0
    iq->fail_addr_type = 0;
587
0
    return;
588
0
  }
589
0
  if(((struct sockaddr_in*)addr)->sin_family == AF_INET) {
590
0
    iq->fail_addr_type = 4;
591
0
    memcpy(&iq->fail_addr.in,
592
0
      &((struct sockaddr_in*)addr)->sin_addr,
593
0
      sizeof(iq->fail_addr.in));
594
0
  }
595
0
#ifdef AF_INET6
596
0
  else if(((struct sockaddr_in*)addr)->sin_family == AF_INET6) {
597
0
    iq->fail_addr_type = 6;
598
0
    memcpy(&iq->fail_addr.in6,
599
0
      &((struct sockaddr_in6*)addr)->sin6_addr,
600
0
      sizeof(iq->fail_addr.in6));
601
0
  }
602
0
#endif
603
0
  else {
604
0
    iq->fail_addr_type = 0;
605
0
  }
606
0
}
607
608
/** print fail addr to string */
609
static void
610
print_fail_addr(struct iter_qstate* iq, char* buf, size_t len)
611
0
{
612
0
  if(iq->fail_addr_type == 4) {
613
0
    if(inet_ntop(AF_INET, &iq->fail_addr.in, buf,
614
0
      (socklen_t)len) == 0)
615
0
      (void)strlcpy(buf, "(inet_ntop error)", len);
616
0
  }
617
0
#ifdef AF_INET6
618
0
  else if(iq->fail_addr_type == 6) {
619
0
    if(inet_ntop(AF_INET6, &iq->fail_addr.in6, buf,
620
0
      (socklen_t)len) == 0)
621
0
      (void)strlcpy(buf, "(inet_ntop error)", len);
622
0
  }
623
0
#endif
624
0
  else
625
0
    (void)strlcpy(buf, "", len);
626
0
}
627
628
/** add response specific error information for log servfail */
629
static void
630
errinf_reply(struct module_qstate* qstate, struct iter_qstate* iq)
631
0
{
632
0
  if(qstate->env->cfg->val_log_level < 2 && !qstate->env->cfg->log_servfail)
633
0
    return;
634
0
  if((qstate->reply && qstate->reply->remote_addrlen != 0) ||
635
0
    (iq->fail_addr_type != 0)) {
636
0
    char from[256], frm[512];
637
0
    if(qstate->reply && qstate->reply->remote_addrlen != 0)
638
0
      addr_to_str(&qstate->reply->remote_addr,
639
0
        qstate->reply->remote_addrlen, from,
640
0
        sizeof(from));
641
0
    else
642
0
      print_fail_addr(iq, from, sizeof(from));
643
0
    snprintf(frm, sizeof(frm), "from %s", from);
644
0
    errinf(qstate, frm);
645
0
  }
646
0
  if(iq->scrub_failures || iq->parse_failures) {
647
0
    if(iq->scrub_failures)
648
0
      errinf(qstate, "upstream response failed scrub");
649
0
    if(iq->parse_failures)
650
0
      errinf(qstate, "could not parse upstream response");
651
0
  } else if(iq->response == NULL && iq->timeout_count != 0) {
652
0
    errinf(qstate, "upstream server timeout");
653
0
  } else if(iq->response == NULL) {
654
0
    errinf(qstate, "no server to query");
655
0
    if(iq->dp) {
656
0
      if(iq->dp->target_list == NULL)
657
0
        errinf(qstate, "no addresses for nameservers");
658
0
      else  errinf(qstate, "nameserver addresses not usable");
659
0
      if(iq->dp->nslist == NULL)
660
0
        errinf(qstate, "have no nameserver names");
661
0
      if(iq->dp->bogus)
662
0
        errinf(qstate, "NS record was dnssec bogus");
663
0
    }
664
0
  }
665
0
  if(iq->response && iq->response->rep) {
666
0
    if(FLAGS_GET_RCODE(iq->response->rep->flags) != 0) {
667
0
      char rcode[256], rc[32];
668
0
      (void)sldns_wire2str_rcode_buf(
669
0
        FLAGS_GET_RCODE(iq->response->rep->flags),
670
0
        rc, sizeof(rc));
671
0
      snprintf(rcode, sizeof(rcode), "got %s", rc);
672
0
      errinf(qstate, rcode);
673
0
    } else {
674
      /* rcode NOERROR */
675
0
      if(iq->response->rep->an_numrrsets == 0) {
676
0
        errinf(qstate, "nodata answer");
677
0
      }
678
0
    }
679
0
  }
680
0
}
681
682
/** see if last resort is possible - does config allow queries to parent */
683
static int
684
can_have_last_resort(struct module_env* env, uint8_t* nm, size_t ATTR_UNUSED(nmlen),
685
  uint16_t qclass, int* have_dp, struct delegpt** retdp,
686
  struct regional* region)
687
0
{
688
0
  struct delegpt* dp = NULL;
689
0
  int nolock = 0;
690
  /* do not process a last resort (the parent side) if a stub
691
   * or forward is configured, because we do not want to go 'above'
692
   * the configured servers */
693
0
  if(!dname_is_root(nm) &&
694
0
    (dp = hints_find(env->hints, nm, qclass, nolock)) &&
695
    /* has_parent side is turned off for stub_first, where we
696
     * are allowed to go to the parent */
697
0
    dp->has_parent_side_NS) {
698
0
    if(retdp) *retdp = delegpt_copy(dp, region);
699
0
    lock_rw_unlock(&env->hints->lock);
700
0
    if(have_dp) *have_dp = 1;
701
0
    return 0;
702
0
  }
703
0
  if(dp) {
704
0
    lock_rw_unlock(&env->hints->lock);
705
0
    dp = NULL;
706
0
  }
707
0
  if((dp = forwards_find(env->fwds, nm, qclass, nolock)) &&
708
    /* has_parent_side is turned off for forward_first, where
709
     * we are allowed to go to the parent */
710
0
    dp->has_parent_side_NS) {
711
0
    if(retdp) *retdp = delegpt_copy(dp, region);
712
0
    lock_rw_unlock(&env->fwds->lock);
713
0
    if(have_dp) *have_dp = 1;
714
0
    return 0;
715
0
  }
716
  /* lock_() calls are macros that could be nothing, surround in {} */
717
0
  if(dp) { lock_rw_unlock(&env->fwds->lock); }
718
0
  return 1;
719
0
}
720
721
/** see if target name is caps-for-id whitelisted */
722
static int
723
is_caps_whitelisted(struct iter_env* ie, struct iter_qstate* iq)
724
0
{
725
0
  if(!ie->caps_white) return 0; /* no whitelist, or no capsforid */
726
0
  return name_tree_lookup(ie->caps_white, iq->qchase.qname,
727
0
    iq->qchase.qname_len, dname_count_labels(iq->qchase.qname),
728
0
    iq->qchase.qclass) != NULL;
729
0
}
730
731
/**
732
 * Create target count structure for this query. This is always explicitly
733
 * created for the parent query.
734
 */
735
static void
736
target_count_create(struct iter_qstate* iq)
737
0
{
738
0
  if(!iq->target_count) {
739
0
    iq->target_count = (int*)calloc(TARGET_COUNT_MAX, sizeof(int));
740
    /* if calloc fails we simply do not track this number */
741
0
    if(iq->target_count) {
742
0
      iq->target_count[TARGET_COUNT_REF] = 1;
743
0
      iq->nxns_dp = (uint8_t**)calloc(1, sizeof(uint8_t*));
744
0
    }
745
0
  }
746
0
}
747
748
static void
749
target_count_increase(struct iter_qstate* iq, int num)
750
0
{
751
0
  target_count_create(iq);
752
0
  if(iq->target_count)
753
0
    iq->target_count[TARGET_COUNT_QUERIES] += num;
754
0
  iq->dp_target_count++;
755
0
}
756
757
static void
758
target_count_increase_nx(struct iter_qstate* iq, int num)
759
0
{
760
0
  target_count_create(iq);
761
0
  if(iq->target_count)
762
0
    iq->target_count[TARGET_COUNT_NX] += num;
763
0
}
764
765
static void
766
target_count_increase_global_quota(struct iter_qstate* iq, int num)
767
0
{
768
0
  target_count_create(iq);
769
0
  if(iq->target_count)
770
0
    iq->target_count[TARGET_COUNT_GLOBAL_QUOTA] += num;
771
0
}
772
773
/**
774
 * Generate a subrequest.
775
 * Generate a local request event. Local events are tied to this module, and
776
 * have a corresponding (first tier) event that is waiting for this event to
777
 * resolve to continue.
778
 *
779
 * @param qname The query name for this request.
780
 * @param qnamelen length of qname
781
 * @param qtype The query type for this request.
782
 * @param qclass The query class for this request.
783
 * @param qstate The event that is generating this event.
784
 * @param id: module id.
785
 * @param iq: The iterator state that is generating this event.
786
 * @param initial_state The initial response state (normally this
787
 *          is QUERY_RESP_STATE, unless it is known that the request won't
788
 *          need iterative processing
789
 * @param finalstate The final state for the response to this request.
790
 * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
791
 *  not need initialisation.
792
 * @param v: if true, validation is done on the subquery.
793
 * @param detached: true if this qstate should not attach to the subquery
794
 * @return false on error (malloc).
795
 */
796
static int
797
generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype, 
798
  uint16_t qclass, struct module_qstate* qstate, int id,
799
  struct iter_qstate* iq, enum iter_state initial_state, 
800
  enum iter_state finalstate, struct module_qstate** subq_ret, int v,
801
  int detached)
802
0
{
803
0
  struct module_qstate* subq = NULL;
804
0
  struct iter_qstate* subiq = NULL;
805
0
  uint16_t qflags = 0; /* OPCODE QUERY, no flags */
806
0
  struct query_info qinf;
807
0
  int prime = (finalstate == PRIME_RESP_STATE)?1:0;
808
0
  int valrec = 0;
809
0
  qinf.qname = qname;
810
0
  qinf.qname_len = qnamelen;
811
0
  qinf.qtype = qtype;
812
0
  qinf.qclass = qclass;
813
0
  qinf.local_alias = NULL;
814
815
  /* RD should be set only when sending the query back through the INIT
816
   * state. */
817
0
  if(initial_state == INIT_REQUEST_STATE)
818
0
    qflags |= BIT_RD;
819
  /* We set the CD flag so we can send this through the "head" of 
820
   * the resolution chain, which might have a validator. We are 
821
   * uninterested in validating things not on the direct resolution 
822
   * path.  */
823
0
  if(!v) {
824
0
    qflags |= BIT_CD;
825
0
    valrec = 1;
826
0
  }
827
  
828
0
  if(detached) {
829
0
    struct mesh_state* sub = NULL;
830
0
    fptr_ok(fptr_whitelist_modenv_add_sub(
831
0
      qstate->env->add_sub));
832
0
    if(!(*qstate->env->add_sub)(qstate, &qinf,
833
0
      qflags, prime, valrec, &subq, &sub)){
834
0
      return 0;
835
0
    }
836
0
  }
837
0
  else {
838
    /* attach subquery, lookup existing or make a new one */
839
0
    fptr_ok(fptr_whitelist_modenv_attach_sub(
840
0
      qstate->env->attach_sub));
841
0
    if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime,
842
0
      valrec, &subq)) {
843
0
      return 0;
844
0
    }
845
0
  }
846
0
  *subq_ret = subq;
847
0
  if(subq) {
848
    /* initialise the new subquery */
849
0
    subq->curmod = id;
850
0
    subq->ext_state[id] = module_state_initial;
851
0
    subq->minfo[id] = regional_alloc(subq->region, 
852
0
      sizeof(struct iter_qstate));
853
0
    if(!subq->minfo[id]) {
854
0
      log_err("init subq: out of memory");
855
0
      fptr_ok(fptr_whitelist_modenv_kill_sub(
856
0
        qstate->env->kill_sub));
857
0
      (*qstate->env->kill_sub)(subq);
858
0
      return 0;
859
0
    }
860
0
    subiq = (struct iter_qstate*)subq->minfo[id];
861
0
    memset(subiq, 0, sizeof(*subiq));
862
0
    subiq->num_target_queries = 0;
863
0
    target_count_create(iq);
864
0
    subiq->target_count = iq->target_count;
865
0
    if(iq->target_count) {
866
0
      iq->target_count[TARGET_COUNT_REF] ++; /* extra reference */
867
0
      subiq->nxns_dp = iq->nxns_dp;
868
0
    }
869
0
    subiq->dp_target_count = 0;
870
0
    subiq->num_current_queries = 0;
871
0
    subiq->depth = iq->depth+1;
872
0
    outbound_list_init(&subiq->outlist);
873
0
    subiq->state = initial_state;
874
0
    subiq->final_state = finalstate;
875
0
    subiq->qchase = subq->qinfo;
876
0
    subiq->chase_flags = subq->query_flags;
877
0
    subiq->refetch_glue = 0;
878
0
    if(qstate->env->cfg->qname_minimisation)
879
0
      subiq->minimisation_state = INIT_MINIMISE_STATE;
880
0
    else
881
0
      subiq->minimisation_state = DONOT_MINIMISE_STATE;
882
0
    memset(&subiq->qinfo_out, 0, sizeof(struct query_info));
883
0
  }
884
0
  return 1;
885
0
}
886
887
/**
888
 * Generate and send a root priming request.
889
 * @param qstate: the qtstate that triggered the need to prime.
890
 * @param iq: iterator query state.
891
 * @param id: module id.
892
 * @param qclass: the class to prime.
893
 * @return 0 on failure
894
 */
895
static int
896
prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
897
  uint16_t qclass)
898
0
{
899
0
  struct delegpt* dp;
900
0
  struct module_qstate* subq;
901
0
  int nolock = 0;
902
0
  verbose(VERB_DETAIL, "priming . %s NS", 
903
0
    sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
904
0
    sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
905
0
  dp = hints_find_root(qstate->env->hints, qclass, nolock);
906
0
  if(!dp) {
907
0
    verbose(VERB_ALGO, "Cannot prime due to lack of hints");
908
0
    return 0;
909
0
  }
910
  /* Priming requests start at the QUERYTARGETS state, skipping 
911
   * the normal INIT state logic (which would cause an infloop). */
912
0
  if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS, 
913
0
    qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
914
0
    &subq, 0, 0)) {
915
0
    lock_rw_unlock(&qstate->env->hints->lock);
916
0
    verbose(VERB_ALGO, "could not prime root");
917
0
    return 0;
918
0
  }
919
0
  if(subq) {
920
0
    struct iter_qstate* subiq = 
921
0
      (struct iter_qstate*)subq->minfo[id];
922
    /* Set the initial delegation point to the hint.
923
     * copy dp, it is now part of the root prime query. 
924
     * dp was part of in the fixed hints structure. */
925
0
    subiq->dp = delegpt_copy(dp, subq->region);
926
0
    lock_rw_unlock(&qstate->env->hints->lock);
927
0
    if(!subiq->dp) {
928
0
      log_err("out of memory priming root, copydp");
929
0
      fptr_ok(fptr_whitelist_modenv_kill_sub(
930
0
        qstate->env->kill_sub));
931
0
      (*qstate->env->kill_sub)(subq);
932
0
      return 0;
933
0
    }
934
    /* there should not be any target queries. */
935
0
    subiq->num_target_queries = 0; 
936
0
    subiq->dnssec_expected = iter_indicates_dnssec(
937
0
      qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
938
0
  } else {
939
0
    lock_rw_unlock(&qstate->env->hints->lock);
940
0
  }
941
  
942
  /* this module stops, our submodule starts, and does the query. */
943
0
  qstate->ext_state[id] = module_wait_subquery;
944
0
  return 1;
945
0
}
946
947
/**
948
 * Generate and process a stub priming request. This method tests for the
949
 * need to prime a stub zone, so it is safe to call for every request.
950
 *
951
 * @param qstate: the qtstate that triggered the need to prime.
952
 * @param iq: iterator query state.
953
 * @param id: module id.
954
 * @param qname: request name.
955
 * @param qclass: request class.
956
 * @return true if a priming subrequest was made, false if not. The will only
957
 *         issue a priming request if it detects an unprimed stub.
958
 *         Uses value of 2 to signal during stub-prime in root-prime situation
959
 *         that a noprime-stub is available and resolution can continue.
960
 */
961
static int
962
prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
963
  uint8_t* qname, uint16_t qclass)
964
0
{
965
  /* Lookup the stub hint. This will return null if the stub doesn't 
966
   * need to be re-primed. */
967
0
  struct iter_hints_stub* stub;
968
0
  struct delegpt* stub_dp;
969
0
  struct module_qstate* subq;
970
0
  int nolock = 0;
971
972
0
  if(!qname) return 0;
973
0
  stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp,
974
0
    nolock);
975
  /* The stub (if there is one) does not need priming. */
976
0
  if(!stub) return 0;
977
0
  stub_dp = stub->dp;
978
  /* if we have an auth_zone dp, and stub is equal, don't prime stub
979
   * yet, unless we want to fallback and avoid the auth_zone */
980
0
  if(!iq->auth_zone_avoid && iq->dp && iq->dp->auth_dp && 
981
0
    query_dname_compare(iq->dp->name, stub_dp->name) == 0) {
982
0
    lock_rw_unlock(&qstate->env->hints->lock);
983
0
    return 0;
984
0
  }
985
986
  /* is it a noprime stub (always use) */
987
0
  if(stub->noprime) {
988
0
    int r = 0;
989
0
    if(iq->dp == NULL) r = 2;
990
    /* copy the dp out of the fixed hints structure, so that
991
     * it can be changed when servicing this query */
992
0
    iq->dp = delegpt_copy(stub_dp, qstate->region);
993
0
    lock_rw_unlock(&qstate->env->hints->lock);
994
0
    if(!iq->dp) {
995
0
      log_err("out of memory priming stub");
996
0
      errinf(qstate, "malloc failure, priming stub");
997
0
      (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
998
0
      return 1; /* return 1 to make module stop, with error */
999
0
    }
1000
0
    log_nametypeclass(VERB_DETAIL, "use stub", iq->dp->name,
1001
0
      LDNS_RR_TYPE_NS, qclass);
1002
0
    return r;
1003
0
  }
1004
1005
  /* Otherwise, we need to (re)prime the stub. */
1006
0
  log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name, 
1007
0
    LDNS_RR_TYPE_NS, qclass);
1008
1009
  /* Stub priming events start at the QUERYTARGETS state to avoid the
1010
   * redundant INIT state processing. */
1011
0
  if(!generate_sub_request(stub_dp->name, stub_dp->namelen, 
1012
0
    LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
1013
0
    QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0, 0)) {
1014
0
    lock_rw_unlock(&qstate->env->hints->lock);
1015
0
    verbose(VERB_ALGO, "could not prime stub");
1016
0
    errinf(qstate, "could not generate lookup for stub prime");
1017
0
    (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1018
0
    return 1; /* return 1 to make module stop, with error */
1019
0
  }
1020
0
  if(subq) {
1021
0
    struct iter_qstate* subiq = 
1022
0
      (struct iter_qstate*)subq->minfo[id];
1023
1024
    /* Set the initial delegation point to the hint. */
1025
    /* make copy to avoid use of stub dp by different qs/threads */
1026
0
    subiq->dp = delegpt_copy(stub_dp, subq->region);
1027
0
    lock_rw_unlock(&qstate->env->hints->lock);
1028
0
    if(!subiq->dp) {
1029
0
      log_err("out of memory priming stub, copydp");
1030
0
      fptr_ok(fptr_whitelist_modenv_kill_sub(
1031
0
        qstate->env->kill_sub));
1032
0
      (*qstate->env->kill_sub)(subq);
1033
0
      errinf(qstate, "malloc failure, in stub prime");
1034
0
      (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1035
0
      return 1; /* return 1 to make module stop, with error */
1036
0
    }
1037
    /* there should not be any target queries -- although there 
1038
     * wouldn't be anyway, since stub hints never have 
1039
     * missing targets. */
1040
0
    subiq->num_target_queries = 0; 
1041
0
    subiq->wait_priming_stub = 1;
1042
0
    subiq->dnssec_expected = iter_indicates_dnssec(
1043
0
      qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
1044
0
  } else {
1045
0
    lock_rw_unlock(&qstate->env->hints->lock);
1046
0
  }
1047
  
1048
  /* this module stops, our submodule starts, and does the query. */
1049
0
  qstate->ext_state[id] = module_wait_subquery;
1050
0
  return 1;
1051
0
}
1052
1053
/**
1054
 * Generate a delegation point for an auth zone (unless cached dp is better)
1055
 * false on alloc failure.
1056
 */
1057
static int
1058
auth_zone_delegpt(struct module_qstate* qstate, struct iter_qstate* iq,
1059
  uint8_t* delname, size_t delnamelen)
1060
0
{
1061
0
  struct auth_zone* z;
1062
0
  if(iq->auth_zone_avoid)
1063
0
    return 1;
1064
0
  if(!delname) {
1065
0
    delname = iq->qchase.qname;
1066
0
    delnamelen = iq->qchase.qname_len;
1067
0
  }
1068
0
  lock_rw_rdlock(&qstate->env->auth_zones->lock);
1069
0
  z = auth_zones_find_zone(qstate->env->auth_zones, delname, delnamelen,
1070
0
    qstate->qinfo.qclass);
1071
0
  if(!z) {
1072
0
    lock_rw_unlock(&qstate->env->auth_zones->lock);
1073
0
    return 1;
1074
0
  }
1075
0
  lock_rw_rdlock(&z->lock);
1076
0
  lock_rw_unlock(&qstate->env->auth_zones->lock);
1077
0
  if(z->for_upstream) {
1078
0
    if(iq->dp && query_dname_compare(z->name, iq->dp->name) == 0
1079
0
      && iq->dp->auth_dp && qstate->blacklist &&
1080
0
      z->fallback_enabled) {
1081
      /* cache is blacklisted and fallback, and we
1082
       * already have an auth_zone dp */
1083
0
      if(verbosity>=VERB_ALGO) {
1084
0
        char buf[LDNS_MAX_DOMAINLEN];
1085
0
        dname_str(z->name, buf);
1086
0
        verbose(VERB_ALGO, "auth_zone %s "
1087
0
          "fallback because cache blacklisted",
1088
0
          buf);
1089
0
      }
1090
0
      lock_rw_unlock(&z->lock);
1091
0
      iq->dp = NULL;
1092
0
      return 1;
1093
0
    }
1094
0
    if(iq->dp==NULL || dname_subdomain_c(z->name, iq->dp->name)) {
1095
0
      struct delegpt* dp;
1096
0
      if(qstate->blacklist && z->fallback_enabled) {
1097
        /* cache is blacklisted because of a DNSSEC
1098
         * validation failure, and the zone allows
1099
         * fallback to the internet, query there. */
1100
0
        if(verbosity>=VERB_ALGO) {
1101
0
          char buf[LDNS_MAX_DOMAINLEN];
1102
0
          dname_str(z->name, buf);
1103
0
          verbose(VERB_ALGO, "auth_zone %s "
1104
0
            "fallback because cache blacklisted",
1105
0
            buf);
1106
0
        }
1107
0
        lock_rw_unlock(&z->lock);
1108
0
        return 1;
1109
0
      }
1110
0
      dp = (struct delegpt*)regional_alloc_zero(
1111
0
        qstate->region, sizeof(*dp));
1112
0
      if(!dp) {
1113
0
        log_err("alloc failure");
1114
0
        if(z->fallback_enabled) {
1115
0
          lock_rw_unlock(&z->lock);
1116
0
          return 1; /* just fallback */
1117
0
        }
1118
0
        lock_rw_unlock(&z->lock);
1119
0
        errinf(qstate, "malloc failure");
1120
0
        return 0;
1121
0
      }
1122
0
      dp->name = regional_alloc_init(qstate->region,
1123
0
        z->name, z->namelen);
1124
0
      if(!dp->name) {
1125
0
        log_err("alloc failure");
1126
0
        if(z->fallback_enabled) {
1127
0
          lock_rw_unlock(&z->lock);
1128
0
          return 1; /* just fallback */
1129
0
        }
1130
0
        lock_rw_unlock(&z->lock);
1131
0
        errinf(qstate, "malloc failure");
1132
0
        return 0;
1133
0
      }
1134
0
      dp->namelen = z->namelen;
1135
0
      dp->namelabs = z->namelabs;
1136
0
      dp->auth_dp = 1;
1137
0
      iq->dp = dp;
1138
0
    }
1139
0
  }
1140
1141
0
  lock_rw_unlock(&z->lock);
1142
0
  return 1;
1143
0
}
1144
1145
/**
1146
 * Generate A and AAAA checks for glue that is in-zone for the referral
1147
 * we just got to obtain authoritative information on the addresses.
1148
 *
1149
 * @param qstate: the qtstate that triggered the need to prime.
1150
 * @param iq: iterator query state.
1151
 * @param id: module id.
1152
 */
1153
static void
1154
generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq, 
1155
  int id)
1156
0
{
1157
0
  struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
1158
0
  struct module_qstate* subq;
1159
0
  size_t i;
1160
0
  struct reply_info* rep = iq->response->rep;
1161
0
  struct ub_packed_rrset_key* s;
1162
0
  log_assert(iq->dp);
1163
1164
0
  if(iq->depth == ie->max_dependency_depth)
1165
0
    return;
1166
  /* walk through additional, and check if in-zone,
1167
   * only relevant A, AAAA are left after scrub anyway */
1168
0
  for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
1169
0
    s = rep->rrsets[i];
1170
    /* check *ALL* addresses that are transmitted in additional*/
1171
    /* is it an address ? */
1172
0
    if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
1173
0
      ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
1174
0
      continue;
1175
0
    }
1176
    /* is this query the same as the A/AAAA check for it */
1177
0
    if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
1178
0
      qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
1179
0
      query_dname_compare(qstate->qinfo.qname, 
1180
0
        s->rk.dname)==0 &&
1181
0
      (qstate->query_flags&BIT_RD) && 
1182
0
      !(qstate->query_flags&BIT_CD))
1183
0
      continue;
1184
1185
    /* generate subrequest for it */
1186
0
    log_nametypeclass(VERB_ALGO, "schedule addr fetch", 
1187
0
      s->rk.dname, ntohs(s->rk.type), 
1188
0
      ntohs(s->rk.rrset_class));
1189
0
    if(!generate_sub_request(s->rk.dname, s->rk.dname_len, 
1190
0
      ntohs(s->rk.type), ntohs(s->rk.rrset_class),
1191
0
      qstate, id, iq,
1192
0
      INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) {
1193
0
      verbose(VERB_ALGO, "could not generate addr check");
1194
0
      return;
1195
0
    }
1196
    /* ignore subq - not need for more init */
1197
0
  }
1198
0
}
1199
1200
/**
1201
 * Generate a NS check request to obtain authoritative information
1202
 * on an NS rrset.
1203
 *
1204
 * @param qstate: the qstate that triggered the need to prime.
1205
 * @param iq: iterator query state.
1206
 * @param id: module id.
1207
 */
1208
static void
1209
generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1210
0
{
1211
0
  struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
1212
0
  struct module_qstate* subq;
1213
0
  log_assert(iq->dp);
1214
1215
0
  if(iq->depth == ie->max_dependency_depth)
1216
0
    return;
1217
0
  if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen,
1218
0
    iq->qchase.qclass, NULL, NULL, NULL))
1219
0
    return;
1220
  /* is this query the same as the nscheck? */
1221
0
  if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
1222
0
    query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
1223
0
    (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
1224
    /* spawn off A, AAAA queries for in-zone glue to check */
1225
0
    generate_a_aaaa_check(qstate, iq, id);
1226
0
    return;
1227
0
  }
1228
  /* no need to get the NS record for DS, it is above the zonecut */
1229
0
  if(qstate->qinfo.qtype == LDNS_RR_TYPE_DS)
1230
0
    return;
1231
1232
0
  log_nametypeclass(VERB_ALGO, "schedule ns fetch", 
1233
0
    iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1234
0
  if(!generate_sub_request(iq->dp->name, iq->dp->namelen, 
1235
0
    LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1236
0
    INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) {
1237
0
    verbose(VERB_ALGO, "could not generate ns check");
1238
0
    return;
1239
0
  }
1240
0
  if(subq) {
1241
0
    struct iter_qstate* subiq = 
1242
0
      (struct iter_qstate*)subq->minfo[id];
1243
1244
    /* make copy to avoid use of stub dp by different qs/threads */
1245
    /* refetch glue to start higher up the tree */
1246
0
    subiq->refetch_glue = 1;
1247
0
    subiq->dp = delegpt_copy(iq->dp, subq->region);
1248
0
    if(!subiq->dp) {
1249
0
      log_err("out of memory generating ns check, copydp");
1250
0
      fptr_ok(fptr_whitelist_modenv_kill_sub(
1251
0
        qstate->env->kill_sub));
1252
0
      (*qstate->env->kill_sub)(subq);
1253
0
      return;
1254
0
    }
1255
0
  }
1256
0
}
1257
1258
/**
1259
 * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
1260
 * just got in a referral (where we have dnssec_expected, thus have trust
1261
 * anchors above it).  Note that right after calling this routine the
1262
 * iterator detached subqueries (because of following the referral), and thus
1263
 * the DNSKEY query becomes detached, its return stored in the cache for
1264
 * later lookup by the validator.  This cache lookup by the validator avoids
1265
 * the roundtrip incurred by the DNSKEY query.  The DNSKEY query is now
1266
 * performed at about the same time the original query is sent to the domain,
1267
 * thus the two answers are likely to be returned at about the same time,
1268
 * saving a roundtrip from the validated lookup.
1269
 *
1270
 * @param qstate: the qtstate that triggered the need to prime.
1271
 * @param iq: iterator query state.
1272
 * @param id: module id.
1273
 */
1274
static void
1275
generate_dnskey_prefetch(struct module_qstate* qstate, 
1276
  struct iter_qstate* iq, int id)
1277
0
{
1278
0
  struct module_qstate* subq;
1279
0
  log_assert(iq->dp);
1280
1281
  /* is this query the same as the prefetch? */
1282
0
  if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
1283
0
    query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
1284
0
    (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
1285
0
    return;
1286
0
  }
1287
  /* we do not generate this prefetch when the query list is full,
1288
   * the query is fetched, if needed, when the validator wants it.
1289
   * At that time the validator waits for it, after spawning it.
1290
   * This means there is one state that uses cpu and a socket, the
1291
   * spawned while this one waits, and not several at the same time,
1292
   * if we had created the lookup here. And this helps to keep
1293
   * the total load down, but the query still succeeds to resolve. */
1294
0
  if(mesh_jostle_exceeded(qstate->env->mesh))
1295
0
    return;
1296
1297
  /* if the DNSKEY is in the cache this lookup will stop quickly */
1298
0
  log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch", 
1299
0
    iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
1300
0
  if(!generate_sub_request(iq->dp->name, iq->dp->namelen, 
1301
0
    LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
1302
0
    INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) {
1303
    /* we'll be slower, but it'll work */
1304
0
    verbose(VERB_ALGO, "could not generate dnskey prefetch");
1305
0
    return;
1306
0
  }
1307
0
  if(subq) {
1308
0
    struct iter_qstate* subiq = 
1309
0
      (struct iter_qstate*)subq->minfo[id];
1310
    /* this qstate has the right delegation for the dnskey lookup*/
1311
    /* make copy to avoid use of stub dp by different qs/threads */
1312
0
    subiq->dp = delegpt_copy(iq->dp, subq->region);
1313
    /* if !subiq->dp, it'll start from the cache, no problem */
1314
0
  }
1315
0
}
1316
1317
/**
1318
 * See if the query needs forwarding.
1319
 * 
1320
 * @param qstate: query state.
1321
 * @param iq: iterator query state.
1322
 * @return true if the request is forwarded, false if not.
1323
 *  If returns true but, iq->dp is NULL then a malloc failure occurred.
1324
 */
1325
static int
1326
forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
1327
0
{
1328
0
  struct delegpt* dp;
1329
0
  uint8_t* delname = iq->qchase.qname;
1330
0
  size_t delnamelen = iq->qchase.qname_len;
1331
0
  int nolock = 0;
1332
0
  if(iq->refetch_glue && iq->dp) {
1333
0
    delname = iq->dp->name;
1334
0
    delnamelen = iq->dp->namelen;
1335
0
  }
1336
  /* strip one label off of DS query to lookup higher for it */
1337
0
  if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
1338
0
    && !dname_is_root(iq->qchase.qname))
1339
0
    dname_remove_label(&delname, &delnamelen);
1340
0
  dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass,
1341
0
    nolock);
1342
0
  if(!dp) return 0;
1343
  /* send recursion desired to forward addr */
1344
0
  iq->chase_flags |= BIT_RD; 
1345
0
  iq->dp = delegpt_copy(dp, qstate->region);
1346
0
  lock_rw_unlock(&qstate->env->fwds->lock);
1347
  /* iq->dp checked by caller */
1348
0
  verbose(VERB_ALGO, "forwarding request");
1349
0
  return 1;
1350
0
}
1351
1352
/** 
1353
 * Process the initial part of the request handling. This state roughly
1354
 * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
1355
 * (find the best servers to ask).
1356
 *
1357
 * Note that all requests start here, and query restarts revisit this state.
1358
 *
1359
 * This state either generates: 1) a response, from cache or error, 2) a
1360
 * priming event, or 3) forwards the request to the next state (init2,
1361
 * generally).
1362
 *
1363
 * @param qstate: query state.
1364
 * @param iq: iterator query state.
1365
 * @param ie: iterator shared global environment.
1366
 * @param id: module id.
1367
 * @return true if the event needs more request processing immediately,
1368
 *         false if not.
1369
 */
1370
static int
1371
processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
1372
  struct iter_env* ie, int id)
1373
0
{
1374
0
  uint8_t dpname_storage[LDNS_MAX_DOMAINLEN+1];
1375
0
  uint8_t* delname, *dpname=NULL;
1376
0
  size_t delnamelen, dpnamelen=0;
1377
0
  struct dns_msg* msg = NULL;
1378
1379
0
  log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
1380
  /* check effort */
1381
1382
  /* We enforce a maximum number of query restarts. This is primarily a
1383
   * cheap way to prevent CNAME loops. */
1384
0
  if(iq->query_restart_count > ie->max_query_restarts) {
1385
0
    verbose(VERB_QUERY, "request has exceeded the maximum number"
1386
0
      " of query restarts with %d", iq->query_restart_count);
1387
0
    errinf(qstate, "request has exceeded the maximum number "
1388
0
      "restarts (eg. indirections)");
1389
0
    if(iq->qchase.qname)
1390
0
      errinf_dname(qstate, "stop at", iq->qchase.qname);
1391
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1392
0
  }
1393
1394
  /* We enforce a maximum recursion/dependency depth -- in general, 
1395
   * this is unnecessary for dependency loops (although it will 
1396
   * catch those), but it provides a sensible limit to the amount 
1397
   * of work required to answer a given query. */
1398
0
  verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
1399
0
  if(iq->depth > ie->max_dependency_depth) {
1400
0
    verbose(VERB_QUERY, "request has exceeded the maximum "
1401
0
      "dependency depth with depth of %d", iq->depth);
1402
0
    errinf(qstate, "request has exceeded the maximum dependency "
1403
0
      "depth (eg. nameserver lookup recursion)");
1404
0
    return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1405
0
  }
1406
1407
  /* If the request is qclass=ANY, setup to generate each class */
1408
0
  if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
1409
0
    iq->qchase.qclass = 0;
1410
0
    return next_state(iq, COLLECT_CLASS_STATE);
1411
0
  }
1412
1413
  /*
1414
   * If we are restricted by a forward-zone or a stub-zone, we
1415
   * can't re-fetch glue for this delegation point.
1416
   * we won’t try to re-fetch glue if the iq->dp is null.
1417
   */
1418
0
  if (iq->refetch_glue &&
1419
0
          iq->dp &&
1420
0
          !can_have_last_resort(qstate->env, iq->dp->name,
1421
0
               iq->dp->namelen, iq->qchase.qclass, NULL, NULL, NULL)) {
1422
0
      iq->refetch_glue = 0;
1423
0
  }
1424
1425
  /* Resolver Algorithm Step 1 -- Look for the answer in local data. */
1426
1427
  /* This either results in a query restart (CNAME cache response), a
1428
   * terminating response (ANSWER), or a cache miss (null). */
1429
1430
  /* Check RPZ for override */
1431
0
  if(qstate->env->auth_zones) {
1432
    /* apply rpz qname triggers, like after cname */
1433
0
    struct dns_msg* forged_response =
1434
0
      rpz_callback_from_iterator_cname(qstate, iq);
1435
0
    if(forged_response) {
1436
0
      uint8_t* sname = 0;
1437
0
      size_t slen = 0;
1438
0
      int count = 0;
1439
0
      while(forged_response && reply_find_rrset_section_an(
1440
0
        forged_response->rep, iq->qchase.qname,
1441
0
        iq->qchase.qname_len, LDNS_RR_TYPE_CNAME,
1442
0
        iq->qchase.qclass) &&
1443
0
        iq->qchase.qtype != LDNS_RR_TYPE_CNAME &&
1444
0
        count++ < ie->max_query_restarts) {
1445
        /* another cname to follow */
1446
0
        if(!handle_cname_response(qstate, iq, forged_response,
1447
0
          &sname, &slen)) {
1448
0
          errinf(qstate, "malloc failure, CNAME info");
1449
0
          return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1450
0
        }
1451
0
        iq->qchase.qname = sname;
1452
0
        iq->qchase.qname_len = slen;
1453
0
        forged_response =
1454
0
          rpz_callback_from_iterator_cname(qstate, iq);
1455
0
      }
1456
0
      if(forged_response != NULL) {
1457
0
        qstate->ext_state[id] = module_finished;
1458
0
        qstate->return_rcode = LDNS_RCODE_NOERROR;
1459
0
        qstate->return_msg = forged_response;
1460
0
        iq->response = forged_response;
1461
0
        next_state(iq, FINISHED_STATE);
1462
0
        if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
1463
0
          log_err("rpz: after cached cname, prepend rrsets: out of memory");
1464
0
          return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1465
0
        }
1466
0
        qstate->return_msg->qinfo = qstate->qinfo;
1467
0
        return 0;
1468
0
      }
1469
      /* Follow the CNAME response */
1470
0
      iq->dp = NULL;
1471
0
      iq->refetch_glue = 0;
1472
0
      iq->query_restart_count++;
1473
0
      iq->sent_count = 0;
1474
0
      iq->dp_target_count = 0;
1475
0
      sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1476
0
      if(qstate->env->cfg->qname_minimisation)
1477
0
        iq->minimisation_state = INIT_MINIMISE_STATE;
1478
0
      return next_state(iq, INIT_REQUEST_STATE);
1479
0
    }
1480
0
  }
1481
1482
0
  if (iter_stub_fwd_no_cache(qstate, &iq->qchase, &dpname, &dpnamelen,
1483
0
    dpname_storage, sizeof(dpname_storage))) {
1484
    /* Asked to not query cache. */
1485
0
    verbose(VERB_ALGO, "no-cache set, going to the network");
1486
0
    qstate->no_cache_lookup = 1;
1487
0
    qstate->no_cache_store = 1;
1488
0
    msg = NULL;
1489
0
  } else if(qstate->blacklist) {
1490
    /* if cache, or anything else, was blacklisted then
1491
     * getting older results from cache is a bad idea, no cache */
1492
0
    verbose(VERB_ALGO, "cache blacklisted, going to the network");
1493
0
    msg = NULL;
1494
0
  } else if(!qstate->no_cache_lookup) {
1495
0
    msg = dns_cache_lookup(qstate->env, iq->qchase.qname, 
1496
0
      iq->qchase.qname_len, iq->qchase.qtype, 
1497
0
      iq->qchase.qclass, qstate->query_flags,
1498
0
      qstate->region, qstate->env->scratch, 0, dpname,
1499
0
      dpnamelen);
1500
0
    if(!msg && qstate->env->neg_cache &&
1501
0
      iter_qname_indicates_dnssec(qstate->env, &iq->qchase)) {
1502
      /* lookup in negative cache; may result in
1503
       * NOERROR/NODATA or NXDOMAIN answers that need validation */
1504
0
      msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
1505
0
        qstate->region, qstate->env->rrset_cache,
1506
0
        qstate->env->scratch_buffer, 
1507
0
        *qstate->env->now, 1/*add SOA*/, NULL, 
1508
0
        qstate->env->cfg);
1509
0
    }
1510
    /* item taken from cache does not match our query name, thus
1511
     * security needs to be re-examined later */
1512
0
    if(msg && query_dname_compare(qstate->qinfo.qname,
1513
0
      iq->qchase.qname) != 0)
1514
0
      msg->rep->security = sec_status_unchecked;
1515
0
  }
1516
0
  if(msg) {
1517
    /* handle positive cache response */
1518
0
    enum response_type type = response_type_from_cache(msg, 
1519
0
      &iq->qchase);
1520
0
    if(verbosity >= VERB_ALGO) {
1521
0
      log_dns_msg("msg from cache lookup", &msg->qinfo, 
1522
0
        msg->rep);
1523
0
      verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d", 
1524
0
        (int)msg->rep->ttl, 
1525
0
        (int)msg->rep->prefetch_ttl);
1526
0
    }
1527
1528
0
    if(type == RESPONSE_TYPE_CNAME) {
1529
0
      uint8_t* sname = 0;
1530
0
      size_t slen = 0;
1531
0
      verbose(VERB_ALGO, "returning CNAME response from "
1532
0
        "cache");
1533
0
      if(!handle_cname_response(qstate, iq, msg, 
1534
0
        &sname, &slen)) {
1535
0
        errinf(qstate, "failed to prepend CNAME "
1536
0
          "components, malloc failure");
1537
0
        return error_response(qstate, id, 
1538
0
          LDNS_RCODE_SERVFAIL);
1539
0
      }
1540
0
      iq->qchase.qname = sname;
1541
0
      iq->qchase.qname_len = slen;
1542
      /* This *is* a query restart, even if it is a cheap 
1543
       * one. */
1544
0
      iq->dp = NULL;
1545
0
      iq->refetch_glue = 0;
1546
0
      iq->query_restart_count++;
1547
0
      iq->sent_count = 0;
1548
0
      iq->dp_target_count = 0;
1549
0
      sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1550
0
      if(qstate->env->cfg->qname_minimisation)
1551
0
        iq->minimisation_state = INIT_MINIMISE_STATE;
1552
0
      return next_state(iq, INIT_REQUEST_STATE);
1553
0
    }
1554
    /* if from cache, NULL, else insert 'cache IP' len=0 */
1555
0
    if(qstate->reply_origin)
1556
0
      sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1557
0
    if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_SERVFAIL)
1558
0
      errinf(qstate, "SERVFAIL in cache");
1559
    /* it is an answer, response, to final state */
1560
0
    verbose(VERB_ALGO, "returning answer from cache.");
1561
0
    iq->response = msg;
1562
0
    return final_state(iq);
1563
0
  }
1564
1565
  /* attempt to forward the request */
1566
0
  if(forward_request(qstate, iq))
1567
0
  {
1568
0
    if(!iq->dp) {
1569
0
      log_err("alloc failure for forward dp");
1570
0
      errinf(qstate, "malloc failure for forward zone");
1571
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1572
0
    }
1573
0
    if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
1574
0
      qstate->region, iq->dp, 0)) {
1575
0
      errinf(qstate, "malloc failure, copy extra info into delegation point");
1576
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1577
0
    }
1578
0
    if((qstate->query_flags&BIT_RD)==0) {
1579
      /* If the server accepts RD=0 queries and forwards
1580
       * with RD=1, then if the server is listed as an NS
1581
       * entry, it starts query loops. Stop that loop by
1582
       * disallowing the query. The RD=0 was previously used
1583
       * to check the cache with allow_snoop. For stubs,
1584
       * the iterator pass would have primed the stub and
1585
       * then cached information can be used for further
1586
       * queries. */
1587
0
      verbose(VERB_ALGO, "cannot forward RD=0 query, to stop query loops");
1588
0
      errinf(qstate, "cannot forward RD=0 query");
1589
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1590
0
    }
1591
0
    iq->refetch_glue = 0;
1592
0
    iq->minimisation_state = DONOT_MINIMISE_STATE;
1593
    /* the request has been forwarded.
1594
     * forwarded requests need to be immediately sent to the 
1595
     * next state, QUERYTARGETS. */
1596
0
    return next_state(iq, QUERYTARGETS_STATE);
1597
0
  }
1598
1599
  /* Resolver Algorithm Step 2 -- find the "best" servers. */
1600
1601
  /* first, adjust for DS queries. To avoid the grandparent problem, 
1602
   * we just look for the closest set of server to the parent of qname.
1603
   * When re-fetching glue we also need to ask the parent.
1604
   */
1605
0
  if(iq->refetch_glue) {
1606
0
    if(!iq->dp) {
1607
0
      log_err("internal or malloc fail: no dp for refetch");
1608
0
      errinf(qstate, "malloc failure, for delegation info");
1609
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1610
0
    }
1611
0
    delname = iq->dp->name;
1612
0
    delnamelen = iq->dp->namelen;
1613
0
  } else {
1614
0
    delname = iq->qchase.qname;
1615
0
    delnamelen = iq->qchase.qname_len;
1616
0
  }
1617
0
  if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1618
0
     (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway
1619
0
     && can_have_last_resort(qstate->env, delname, delnamelen, iq->qchase.qclass, NULL, NULL, NULL))) {
1620
    /* remove first label from delname, root goes to hints,
1621
     * but only to fetch glue, not for qtype=DS. */
1622
    /* also when prefetching an NS record, fetch it again from
1623
     * its parent, just as if it expired, so that you do not
1624
     * get stuck on an older nameserver that gives old NSrecords */
1625
0
    if(dname_is_root(delname) && (iq->refetch_glue ||
1626
0
      (iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1627
0
      qstate->prefetch_leeway)))
1628
0
      delname = NULL; /* go to root priming */
1629
0
    else  dname_remove_label(&delname, &delnamelen);
1630
0
  }
1631
  /* delname is the name to lookup a delegation for. If NULL rootprime */
1632
0
  while(1) {
1633
    
1634
    /* Lookup the delegation in the cache. If null, then the 
1635
     * cache needs to be primed for the qclass. */
1636
0
    if(delname)
1637
0
         iq->dp = dns_cache_find_delegation(qstate->env, delname, 
1638
0
      delnamelen, iq->qchase.qtype, iq->qchase.qclass, 
1639
0
      qstate->region, &iq->deleg_msg,
1640
0
      *qstate->env->now+qstate->prefetch_leeway, 1,
1641
0
      dpname, dpnamelen);
1642
0
    else iq->dp = NULL;
1643
1644
    /* If the cache has returned nothing, then we have a 
1645
     * root priming situation. */
1646
0
    if(iq->dp == NULL) {
1647
0
      int r;
1648
0
      int nolock = 0;
1649
      /* if under auth zone, no prime needed */
1650
0
      if(!auth_zone_delegpt(qstate, iq, delname, delnamelen))
1651
0
        return error_response(qstate, id, 
1652
0
          LDNS_RCODE_SERVFAIL);
1653
0
      if(iq->dp) /* use auth zone dp */
1654
0
        return next_state(iq, INIT_REQUEST_2_STATE);
1655
      /* if there is a stub, then no root prime needed */
1656
0
      r = prime_stub(qstate, iq, id, delname,
1657
0
        iq->qchase.qclass);
1658
0
      if(r == 2)
1659
0
        break; /* got noprime-stub-zone, continue */
1660
0
      else if(r)
1661
0
        return 0; /* stub prime request made */
1662
0
      if(forwards_lookup_root(qstate->env->fwds,
1663
0
        iq->qchase.qclass, nolock)) {
1664
0
        lock_rw_unlock(&qstate->env->fwds->lock);
1665
        /* forward zone root, no root prime needed */
1666
        /* fill in some dp - safety belt */
1667
0
        iq->dp = hints_find_root(qstate->env->hints,
1668
0
          iq->qchase.qclass, nolock);
1669
0
        if(!iq->dp) {
1670
0
          log_err("internal error: no hints dp");
1671
0
          errinf(qstate, "no hints for this class");
1672
0
          return error_response_cache(qstate, id,
1673
0
            LDNS_RCODE_SERVFAIL);
1674
0
        }
1675
0
        iq->dp = delegpt_copy(iq->dp, qstate->region);
1676
0
        lock_rw_unlock(&qstate->env->hints->lock);
1677
0
        if(!iq->dp) {
1678
0
          log_err("out of memory in safety belt");
1679
0
          errinf(qstate, "malloc failure, in safety belt");
1680
0
          return error_response(qstate, id, 
1681
0
            LDNS_RCODE_SERVFAIL);
1682
0
        }
1683
0
        return next_state(iq, INIT_REQUEST_2_STATE);
1684
0
      }
1685
      /* Note that the result of this will set a new
1686
       * DelegationPoint based on the result of priming. */
1687
0
      if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1688
0
        return error_response(qstate, id, 
1689
0
          LDNS_RCODE_REFUSED);
1690
1691
      /* priming creates and sends a subordinate query, with 
1692
       * this query as the parent. So further processing for 
1693
       * this event will stop until reactivated by the 
1694
       * results of priming. */
1695
0
      return 0;
1696
0
    }
1697
0
    if(!iq->ratelimit_ok && qstate->prefetch_leeway)
1698
0
      iq->ratelimit_ok = 1; /* allow prefetches, this keeps
1699
      otherwise valid data in the cache */
1700
1701
    /* see if this dp not useless.
1702
     * It is useless if:
1703
     *  o all NS items are required glue.
1704
     *    or the query is for NS item that is required glue.
1705
     *  o no addresses are provided.
1706
     *  o RD qflag is on.
1707
     * Instead, go up one level, and try to get even further
1708
     * If the root was useless, use safety belt information.
1709
     * Only check cache returns, because replies for servers
1710
     * could be useless but lead to loops (bumping into the
1711
     * same server reply) if useless-checked.
1712
     */
1713
0
    if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags,
1714
0
      iq->dp, ie->supports_ipv4, ie->supports_ipv6,
1715
0
      ie->nat64.use_nat64)) {
1716
0
      int have_dp = 0;
1717
0
      if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, &have_dp, &iq->dp, qstate->region)) {
1718
0
        if(have_dp) {
1719
0
          verbose(VERB_QUERY, "cache has stub "
1720
0
            "or fwd but no addresses, "
1721
0
            "fallback to config");
1722
0
          if(have_dp && !iq->dp) {
1723
0
            log_err("out of memory in "
1724
0
              "stub/fwd fallback");
1725
0
            errinf(qstate, "malloc failure, for fallback to config");
1726
0
            return error_response(qstate,
1727
0
                id, LDNS_RCODE_SERVFAIL);
1728
0
          }
1729
0
          break;
1730
0
        }
1731
0
        verbose(VERB_ALGO, "useless dp "
1732
0
          "but cannot go up, servfail");
1733
0
        delegpt_log(VERB_ALGO, iq->dp);
1734
0
        errinf(qstate, "no useful nameservers, "
1735
0
          "and cannot go up");
1736
0
        errinf_dname(qstate, "for zone", iq->dp->name);
1737
0
        return error_response(qstate, id, 
1738
0
          LDNS_RCODE_SERVFAIL);
1739
0
      }
1740
0
      if(dname_is_root(iq->dp->name)) {
1741
        /* use safety belt */
1742
0
        int nolock = 0;
1743
0
        verbose(VERB_QUERY, "Cache has root NS but "
1744
0
        "no addresses. Fallback to the safety belt.");
1745
0
        iq->dp = hints_find_root(qstate->env->hints,
1746
0
          iq->qchase.qclass, nolock);
1747
        /* note deleg_msg is from previous lookup,
1748
         * but RD is on, so it is not used */
1749
0
        if(!iq->dp) {
1750
0
          log_err("internal error: no hints dp");
1751
0
          return error_response(qstate, id, 
1752
0
            LDNS_RCODE_REFUSED);
1753
0
        }
1754
0
        iq->dp = delegpt_copy(iq->dp, qstate->region);
1755
0
        lock_rw_unlock(&qstate->env->hints->lock);
1756
0
        if(!iq->dp) {
1757
0
          log_err("out of memory in safety belt");
1758
0
          errinf(qstate, "malloc failure, in safety belt, for root");
1759
0
          return error_response(qstate, id, 
1760
0
            LDNS_RCODE_SERVFAIL);
1761
0
        }
1762
0
        break;
1763
0
      } else {
1764
0
        verbose(VERB_ALGO, 
1765
0
          "cache delegation was useless:");
1766
0
        delegpt_log(VERB_ALGO, iq->dp);
1767
        /* go up */
1768
0
        delname = iq->dp->name;
1769
0
        delnamelen = iq->dp->namelen;
1770
0
        dname_remove_label(&delname, &delnamelen);
1771
0
      }
1772
0
    } else break;
1773
0
  }
1774
1775
0
  verbose(VERB_ALGO, "cache delegation returns delegpt");
1776
0
  delegpt_log(VERB_ALGO, iq->dp);
1777
1778
  /* Otherwise, set the current delegation point and move on to the 
1779
   * next state. */
1780
0
  return next_state(iq, INIT_REQUEST_2_STATE);
1781
0
}
1782
1783
/** 
1784
 * Process the second part of the initial request handling. This state
1785
 * basically exists so that queries that generate root priming events have
1786
 * the same init processing as ones that do not. Request events that reach
1787
 * this state must have a valid currentDelegationPoint set.
1788
 *
1789
 * This part is primarily handling stub zone priming. Events that reach this
1790
 * state must have a current delegation point.
1791
 *
1792
 * @param qstate: query state.
1793
 * @param iq: iterator query state.
1794
 * @param id: module id.
1795
 * @return true if the event needs more request processing immediately,
1796
 *         false if not.
1797
 */
1798
static int
1799
processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1800
  int id)
1801
0
{
1802
0
  uint8_t* delname;
1803
0
  size_t delnamelen;
1804
0
  log_query_info(VERB_QUERY, "resolving (init part 2): ", 
1805
0
    &qstate->qinfo);
1806
1807
0
  delname = iq->qchase.qname;
1808
0
  delnamelen = iq->qchase.qname_len;
1809
0
  if(iq->refetch_glue) {
1810
0
    struct iter_hints_stub* stub;
1811
0
    int nolock = 0;
1812
0
    if(!iq->dp) {
1813
0
      log_err("internal or malloc fail: no dp for refetch");
1814
0
      errinf(qstate, "malloc failure, no delegation info");
1815
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1816
0
    }
1817
    /* Do not send queries above stub, do not set delname to dp if
1818
     * this is above stub without stub-first. */
1819
0
    stub = hints_lookup_stub(
1820
0
      qstate->env->hints, iq->qchase.qname, iq->qchase.qclass,
1821
0
      iq->dp, nolock);
1822
0
    if(!stub || !stub->dp->has_parent_side_NS || 
1823
0
      dname_subdomain_c(iq->dp->name, stub->dp->name)) {
1824
0
      delname = iq->dp->name;
1825
0
      delnamelen = iq->dp->namelen;
1826
0
    }
1827
    /* lock_() calls are macros that could be nothing, surround in {} */
1828
0
    if(stub) { lock_rw_unlock(&qstate->env->hints->lock); }
1829
0
  }
1830
0
  if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1831
0
    if(!dname_is_root(delname))
1832
0
      dname_remove_label(&delname, &delnamelen);
1833
0
    iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1834
0
  }
1835
1836
  /* see if we have an auth zone to answer from, improves dp from cache
1837
   * (if any dp from cache) with auth zone dp, if that is lower */
1838
0
  if(!auth_zone_delegpt(qstate, iq, delname, delnamelen))
1839
0
    return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1840
1841
  /* Check to see if we need to prime a stub zone. */
1842
0
  if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1843
    /* A priming sub request was made */
1844
0
    return 0;
1845
0
  }
1846
1847
  /* most events just get forwarded to the next state. */
1848
0
  return next_state(iq, INIT_REQUEST_3_STATE);
1849
0
}
1850
1851
/** 
1852
 * Process the third part of the initial request handling. This state exists
1853
 * as a separate state so that queries that generate stub priming events
1854
 * will get the tail end of the init process but not repeat the stub priming
1855
 * check.
1856
 *
1857
 * @param qstate: query state.
1858
 * @param iq: iterator query state.
1859
 * @param id: module id.
1860
 * @return true, advancing the event to the QUERYTARGETS_STATE.
1861
 */
1862
static int
1863
processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq, 
1864
  int id)
1865
0
{
1866
0
  log_query_info(VERB_QUERY, "resolving (init part 3): ", 
1867
0
    &qstate->qinfo);
1868
  /* if the cache reply dp equals a validation anchor or msg has DS,
1869
   * then DNSSEC RRSIGs are expected in the reply */
1870
0
  iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp, 
1871
0
    iq->deleg_msg, iq->qchase.qclass);
1872
1873
  /* If the RD flag wasn't set, then we just finish with the 
1874
   * cached referral as the response. */
1875
0
  if(!(qstate->query_flags & BIT_RD) && iq->deleg_msg) {
1876
0
    iq->response = iq->deleg_msg;
1877
0
    if(verbosity >= VERB_ALGO && iq->response)
1878
0
      log_dns_msg("no RD requested, using delegation msg", 
1879
0
        &iq->response->qinfo, iq->response->rep);
1880
0
    if(qstate->reply_origin)
1881
0
      sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1882
0
    return final_state(iq);
1883
0
  }
1884
  /* After this point, unset the RD flag -- this query is going to 
1885
   * be sent to an auth. server. */
1886
0
  iq->chase_flags &= ~BIT_RD;
1887
1888
  /* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1889
0
  if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1890
0
    !(qstate->query_flags&BIT_CD)) {
1891
0
    generate_dnskey_prefetch(qstate, iq, id);
1892
0
    fptr_ok(fptr_whitelist_modenv_detach_subs(
1893
0
      qstate->env->detach_subs));
1894
0
    (*qstate->env->detach_subs)(qstate);
1895
0
  }
1896
1897
  /* Jump to the next state. */
1898
0
  return next_state(iq, QUERYTARGETS_STATE);
1899
0
}
1900
1901
/**
1902
 * Given a basic query, generate a parent-side "target" query. 
1903
 * These are subordinate queries for missing delegation point target addresses,
1904
 * for which only the parent of the delegation provides correct IP addresses.
1905
 *
1906
 * @param qstate: query state.
1907
 * @param iq: iterator query state.
1908
 * @param id: module id.
1909
 * @param name: target qname.
1910
 * @param namelen: target qname length.
1911
 * @param qtype: target qtype (either A or AAAA).
1912
 * @param qclass: target qclass.
1913
 * @return true on success, false on failure.
1914
 */
1915
static int
1916
generate_parentside_target_query(struct module_qstate* qstate, 
1917
  struct iter_qstate* iq, int id, uint8_t* name, size_t namelen, 
1918
  uint16_t qtype, uint16_t qclass)
1919
0
{
1920
0
  struct module_qstate* subq;
1921
0
  if(!generate_sub_request(name, namelen, qtype, qclass, qstate, 
1922
0
    id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0))
1923
0
    return 0;
1924
0
  if(subq) {
1925
0
    struct iter_qstate* subiq = 
1926
0
      (struct iter_qstate*)subq->minfo[id];
1927
    /* blacklist the cache - we want to fetch parent stuff */
1928
0
    sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1929
0
    subiq->query_for_pside_glue = 1;
1930
0
    if(dname_subdomain_c(name, iq->dp->name)) {
1931
0
      subiq->dp = delegpt_copy(iq->dp, subq->region);
1932
0
      subiq->dnssec_expected = iter_indicates_dnssec(
1933
0
        qstate->env, subiq->dp, NULL, 
1934
0
        subq->qinfo.qclass);
1935
0
      subiq->refetch_glue = 1;
1936
0
    } else {
1937
0
      subiq->dp = dns_cache_find_delegation(qstate->env, 
1938
0
        name, namelen, qtype, qclass, subq->region,
1939
0
        &subiq->deleg_msg,
1940
0
        *qstate->env->now+subq->prefetch_leeway,
1941
0
        1, NULL, 0);
1942
      /* if no dp, then it's from root, refetch unneeded */
1943
0
      if(subiq->dp) { 
1944
0
        subiq->dnssec_expected = iter_indicates_dnssec(
1945
0
          qstate->env, subiq->dp, NULL, 
1946
0
          subq->qinfo.qclass);
1947
0
        subiq->refetch_glue = 1;
1948
0
      }
1949
0
    }
1950
0
  }
1951
0
  log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1952
0
  return 1;
1953
0
}
1954
1955
/**
1956
 * Given a basic query, generate a "target" query. These are subordinate
1957
 * queries for missing delegation point target addresses.
1958
 *
1959
 * @param qstate: query state.
1960
 * @param iq: iterator query state.
1961
 * @param id: module id.
1962
 * @param name: target qname.
1963
 * @param namelen: target qname length.
1964
 * @param qtype: target qtype (either A or AAAA).
1965
 * @param qclass: target qclass.
1966
 * @return true on success, false on failure.
1967
 */
1968
static int
1969
generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1970
        int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1971
0
{
1972
0
  struct module_qstate* subq;
1973
0
  if(!generate_sub_request(name, namelen, qtype, qclass, qstate, 
1974
0
    id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0))
1975
0
    return 0;
1976
0
  log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1977
0
  return 1;
1978
0
}
1979
1980
/**
1981
 * Given an event at a certain state, generate zero or more target queries
1982
 * for it's current delegation point.
1983
 *
1984
 * @param qstate: query state.
1985
 * @param iq: iterator query state.
1986
 * @param ie: iterator shared global environment.
1987
 * @param id: module id.
1988
 * @param maxtargets: The maximum number of targets to query for.
1989
 *  if it is negative, there is no maximum number of targets.
1990
 * @param num: returns the number of queries generated and processed, 
1991
 *  which may be zero if there were no missing targets.
1992
 * @return 0 on success, nonzero on error. 1 means temporary failure and
1993
 *  2 means the failure can be cached.
1994
 */
1995
static int
1996
query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1997
        struct iter_env* ie, int id, int maxtargets, int* num)
1998
0
{
1999
0
  int query_count = 0;
2000
0
  struct delegpt_ns* ns;
2001
0
  int missing;
2002
0
  int toget = 0;
2003
2004
0
  iter_mark_cycle_targets(qstate, iq->dp);
2005
0
  missing = (int)delegpt_count_missing_targets(iq->dp, NULL);
2006
0
  log_assert(maxtargets != 0); /* that would not be useful */
2007
2008
  /* Generate target requests. Basically, any missing targets
2009
   * are queried for here, regardless if it is necessary to do
2010
   * so to continue processing. */
2011
0
  if(maxtargets < 0 || maxtargets > missing)
2012
0
    toget = missing;
2013
0
  else  toget = maxtargets;
2014
0
  if(toget == 0) {
2015
0
    *num = 0;
2016
0
    return 0;
2017
0
  }
2018
2019
  /* now that we are sure that a target query is going to be made,
2020
   * check the limits. */
2021
0
  if(iq->depth == ie->max_dependency_depth)
2022
0
    return 1;
2023
0
  if(iq->depth > 0 && iq->target_count &&
2024
0
    iq->target_count[TARGET_COUNT_QUERIES] > MAX_TARGET_COUNT) {
2025
0
    char s[LDNS_MAX_DOMAINLEN];
2026
0
    dname_str(qstate->qinfo.qname, s);
2027
0
    verbose(VERB_QUERY, "request %s has exceeded the maximum "
2028
0
      "number of glue fetches %d", s,
2029
0
      iq->target_count[TARGET_COUNT_QUERIES]);
2030
0
    return 2;
2031
0
  }
2032
0
  if(iq->dp_target_count > MAX_DP_TARGET_COUNT) {
2033
0
    char s[LDNS_MAX_DOMAINLEN];
2034
0
    dname_str(qstate->qinfo.qname, s);
2035
0
    verbose(VERB_QUERY, "request %s has exceeded the maximum "
2036
0
      "number of glue fetches %d to a single delegation point",
2037
0
      s, iq->dp_target_count);
2038
0
    return 2;
2039
0
  }
2040
2041
  /* select 'toget' items from the total of 'missing' items */
2042
0
  log_assert(toget <= missing);
2043
2044
  /* loop over missing targets */
2045
0
  for(ns = iq->dp->nslist; ns; ns = ns->next) {
2046
0
    if(ns->resolved)
2047
0
      continue;
2048
2049
    /* randomly select this item with probability toget/missing */
2050
0
    if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
2051
      /* do not select this one, next; select toget number
2052
       * of items from a list one less in size */
2053
0
      missing --;
2054
0
      continue;
2055
0
    }
2056
2057
0
    if(ie->supports_ipv6 &&
2058
0
      ((ns->lame && !ns->done_pside6) ||
2059
0
      (!ns->lame && !ns->got6))) {
2060
      /* Send the AAAA request. */
2061
0
      if(!generate_target_query(qstate, iq, id, 
2062
0
        ns->name, ns->namelen,
2063
0
        LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
2064
0
        *num = query_count;
2065
0
        if(query_count > 0)
2066
0
          qstate->ext_state[id] = module_wait_subquery;
2067
0
        return 1;
2068
0
      }
2069
0
      query_count++;
2070
      /* If the mesh query list is full, exit the loop here.
2071
       * This makes the routine spawn one query at a time,
2072
       * and this means there is no query state load
2073
       * increase, because the spawned state uses cpu and a
2074
       * socket while this state waits for that spawned
2075
       * state. Next time we can look up further targets */
2076
0
      if(mesh_jostle_exceeded(qstate->env->mesh)) {
2077
        /* If no ip4 query is possible, that makes
2078
         * this ns resolved. */
2079
0
        if(!((ie->supports_ipv4 || ie->nat64.use_nat64) &&
2080
0
          ((ns->lame && !ns->done_pside4) ||
2081
0
          (!ns->lame && !ns->got4)))) {
2082
0
          ns->resolved = 1;
2083
0
        }
2084
0
        break;
2085
0
      }
2086
0
    }
2087
    /* Send the A request. */
2088
0
    if((ie->supports_ipv4 || ie->nat64.use_nat64) &&
2089
0
      ((ns->lame && !ns->done_pside4) ||
2090
0
      (!ns->lame && !ns->got4))) {
2091
0
      if(!generate_target_query(qstate, iq, id, 
2092
0
        ns->name, ns->namelen, 
2093
0
        LDNS_RR_TYPE_A, iq->qchase.qclass)) {
2094
0
        *num = query_count;
2095
0
        if(query_count > 0)
2096
0
          qstate->ext_state[id] = module_wait_subquery;
2097
0
        return 1;
2098
0
      }
2099
0
      query_count++;
2100
      /* If the mesh query list is full, exit the loop. */
2101
0
      if(mesh_jostle_exceeded(qstate->env->mesh)) {
2102
        /* With the ip6 query already checked for,
2103
         * this makes the ns resolved. It is no longer
2104
         * a missing target. */
2105
0
        ns->resolved = 1;
2106
0
        break;
2107
0
      }
2108
0
    }
2109
2110
    /* mark this target as in progress. */
2111
0
    ns->resolved = 1;
2112
0
    missing--;
2113
0
    toget--;
2114
0
    if(toget == 0)
2115
0
      break;
2116
0
  }
2117
0
  *num = query_count;
2118
0
  if(query_count > 0)
2119
0
    qstate->ext_state[id] = module_wait_subquery;
2120
2121
0
  return 0;
2122
0
}
2123
2124
/**
2125
 * Called by processQueryTargets when it would like extra targets to query
2126
 * but it seems to be out of options.  At last resort some less appealing
2127
 * options are explored.  If there are no more options, the result is SERVFAIL
2128
 *
2129
 * @param qstate: query state.
2130
 * @param iq: iterator query state.
2131
 * @param ie: iterator shared global environment.
2132
 * @param id: module id.
2133
 * @return true if the event requires more request processing immediately,
2134
 *         false if not. 
2135
 */
2136
static int
2137
processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
2138
  struct iter_env* ie, int id)
2139
0
{
2140
0
  struct delegpt_ns* ns;
2141
0
  int query_count = 0;
2142
0
  verbose(VERB_ALGO, "No more query targets, attempting last resort");
2143
0
  log_assert(iq->dp);
2144
2145
0
  if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen,
2146
0
    iq->qchase.qclass, NULL, NULL, NULL)) {
2147
    /* fail -- no more targets, no more hope of targets, no hope 
2148
     * of a response. */
2149
0
    errinf(qstate, "all the configured stub or forward servers failed,");
2150
0
    errinf_dname(qstate, "at zone", iq->dp->name);
2151
0
    errinf_reply(qstate, iq);
2152
0
    verbose(VERB_QUERY, "configured stub or forward servers failed -- returning SERVFAIL");
2153
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2154
0
  }
2155
0
  iq->dp->fallback_to_parent_side_NS = 1;
2156
0
  if(qstate->env->cfg->harden_unverified_glue) {
2157
0
    if(!cache_fill_missing(qstate->env, iq->qchase.qclass,
2158
0
      qstate->region, iq->dp, PACKED_RRSET_UNVERIFIED_GLUE))
2159
0
      log_err("out of memory in cache_fill_missing");
2160
0
    if(iq->dp->usable_list) {
2161
0
      verbose(VERB_ALGO, "try unverified glue from cache");
2162
0
      return next_state(iq, QUERYTARGETS_STATE);
2163
0
    }
2164
0
  }
2165
0
  if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
2166
0
    struct delegpt* dp;
2167
0
    int nolock = 0;
2168
0
    dp = hints_find_root(qstate->env->hints,
2169
0
      iq->qchase.qclass, nolock);
2170
0
    if(dp) {
2171
0
      struct delegpt_addr* a;
2172
0
      iq->chase_flags &= ~BIT_RD; /* go to authorities */
2173
0
      for(ns = dp->nslist; ns; ns=ns->next) {
2174
0
        (void)delegpt_add_ns(iq->dp, qstate->region,
2175
0
          ns->name, ns->lame, ns->tls_auth_name,
2176
0
          ns->port);
2177
0
      }
2178
0
      for(a = dp->target_list; a; a=a->next_target) {
2179
0
        (void)delegpt_add_addr(iq->dp, qstate->region,
2180
0
          &a->addr, a->addrlen, a->bogus,
2181
0
          a->lame, a->tls_auth_name, -1, NULL);
2182
0
      }
2183
0
      lock_rw_unlock(&qstate->env->hints->lock);
2184
      /* copy over some configuration since we update the
2185
       * delegation point in place */
2186
0
      iq->dp->tcp_upstream = dp->tcp_upstream;
2187
0
      iq->dp->ssl_upstream = dp->ssl_upstream;
2188
0
    }
2189
0
    iq->dp->has_parent_side_NS = 1;
2190
0
  } else if(!iq->dp->has_parent_side_NS) {
2191
0
    if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
2192
0
      qstate->region, &qstate->qinfo) 
2193
0
      || !iq->dp->has_parent_side_NS) {
2194
      /* if: malloc failure in lookup go up to try */
2195
      /* if: no parent NS in cache - go up one level */
2196
0
      verbose(VERB_ALGO, "try to grab parent NS");
2197
0
      iq->store_parent_NS = iq->dp;
2198
0
      iq->chase_flags &= ~BIT_RD; /* go to authorities */
2199
0
      iq->deleg_msg = NULL;
2200
0
      iq->refetch_glue = 1;
2201
0
      iq->query_restart_count++;
2202
0
      iq->sent_count = 0;
2203
0
      iq->dp_target_count = 0;
2204
0
      if(qstate->env->cfg->qname_minimisation)
2205
0
        iq->minimisation_state = INIT_MINIMISE_STATE;
2206
0
      return next_state(iq, INIT_REQUEST_STATE);
2207
0
    }
2208
0
  }
2209
  /* see if that makes new names available */
2210
0
  if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 
2211
0
    qstate->region, iq->dp, 0))
2212
0
    log_err("out of memory in cache_fill_missing");
2213
0
  if(iq->dp->usable_list) {
2214
0
    verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
2215
0
    return next_state(iq, QUERYTARGETS_STATE);
2216
0
  }
2217
  /* try to fill out parent glue from cache */
2218
0
  if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
2219
0
    qstate->region, &qstate->qinfo)) {
2220
    /* got parent stuff from cache, see if we can continue */
2221
0
    verbose(VERB_ALGO, "try parent-side glue from cache");
2222
0
    return next_state(iq, QUERYTARGETS_STATE);
2223
0
  }
2224
  /* query for an extra name added by the parent-NS record */
2225
0
  if(delegpt_count_missing_targets(iq->dp, NULL) > 0) {
2226
0
    int qs = 0, ret;
2227
0
    verbose(VERB_ALGO, "try parent-side target name");
2228
0
    if((ret=query_for_targets(qstate, iq, ie, id, 1, &qs))!=0) {
2229
0
      errinf(qstate, "could not fetch nameserver");
2230
0
      errinf_dname(qstate, "at zone", iq->dp->name);
2231
0
      if(ret == 1)
2232
0
        return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2233
0
      return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2234
0
    }
2235
0
    iq->num_target_queries += qs;
2236
0
    target_count_increase(iq, qs);
2237
0
    if(qs != 0) {
2238
0
      qstate->ext_state[id] = module_wait_subquery;
2239
0
      return 0; /* and wait for them */
2240
0
    }
2241
0
  }
2242
0
  if(iq->depth == ie->max_dependency_depth) {
2243
0
    verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
2244
0
    errinf(qstate, "cannot fetch more nameservers because at max dependency depth");
2245
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2246
0
  }
2247
0
  if(iq->depth > 0 && iq->target_count &&
2248
0
    iq->target_count[TARGET_COUNT_QUERIES] > MAX_TARGET_COUNT) {
2249
0
    char s[LDNS_MAX_DOMAINLEN];
2250
0
    dname_str(qstate->qinfo.qname, s);
2251
0
    verbose(VERB_QUERY, "request %s has exceeded the maximum "
2252
0
      "number of glue fetches %d", s,
2253
0
      iq->target_count[TARGET_COUNT_QUERIES]);
2254
0
    errinf(qstate, "exceeded the maximum number of glue fetches");
2255
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2256
0
  }
2257
  /* mark cycle targets for parent-side lookups */
2258
0
  iter_mark_pside_cycle_targets(qstate, iq->dp);
2259
  /* see if we can issue queries to get nameserver addresses */
2260
  /* this lookup is not randomized, but sequential. */
2261
0
  for(ns = iq->dp->nslist; ns; ns = ns->next) {
2262
    /* if this nameserver is at a delegation point, but that
2263
     * delegation point is a stub and we cannot go higher, skip*/
2264
0
    if( ((ie->supports_ipv6 && !ns->done_pside6) ||
2265
0
        ((ie->supports_ipv4 || ie->nat64.use_nat64) && !ns->done_pside4)) &&
2266
0
        !can_have_last_resort(qstate->env, ns->name, ns->namelen,
2267
0
      iq->qchase.qclass, NULL, NULL, NULL)) {
2268
0
      log_nametypeclass(VERB_ALGO, "cannot pside lookup ns "
2269
0
        "because it is also a stub/forward,",
2270
0
        ns->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
2271
0
      if(ie->supports_ipv6) ns->done_pside6 = 1;
2272
0
      if(ie->supports_ipv4 || ie->nat64.use_nat64) ns->done_pside4 = 1;
2273
0
      continue;
2274
0
    }
2275
    /* query for parent-side A and AAAA for nameservers */
2276
0
    if(ie->supports_ipv6 && !ns->done_pside6) {
2277
      /* Send the AAAA request. */
2278
0
      if(!generate_parentside_target_query(qstate, iq, id, 
2279
0
        ns->name, ns->namelen,
2280
0
        LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
2281
0
        errinf_dname(qstate, "could not generate nameserver AAAA lookup for", ns->name);
2282
0
        return error_response(qstate, id,
2283
0
          LDNS_RCODE_SERVFAIL);
2284
0
      }
2285
0
      ns->done_pside6 = 1;
2286
0
      query_count++;
2287
0
      if(mesh_jostle_exceeded(qstate->env->mesh)) {
2288
        /* Wait for the lookup; do not spawn multiple
2289
         * lookups at a time. */
2290
0
        verbose(VERB_ALGO, "try parent-side glue lookup");
2291
0
        iq->num_target_queries += query_count;
2292
0
        target_count_increase(iq, query_count);
2293
0
        qstate->ext_state[id] = module_wait_subquery;
2294
0
        return 0;
2295
0
      }
2296
0
    }
2297
0
    if((ie->supports_ipv4 || ie->nat64.use_nat64) && !ns->done_pside4) {
2298
      /* Send the A request. */
2299
0
      if(!generate_parentside_target_query(qstate, iq, id, 
2300
0
        ns->name, ns->namelen, 
2301
0
        LDNS_RR_TYPE_A, iq->qchase.qclass)) {
2302
0
        errinf_dname(qstate, "could not generate nameserver A lookup for", ns->name);
2303
0
        return error_response(qstate, id,
2304
0
          LDNS_RCODE_SERVFAIL);
2305
0
      }
2306
0
      ns->done_pside4 = 1;
2307
0
      query_count++;
2308
0
    }
2309
0
    if(query_count != 0) { /* suspend to await results */
2310
0
      verbose(VERB_ALGO, "try parent-side glue lookup");
2311
0
      iq->num_target_queries += query_count;
2312
0
      target_count_increase(iq, query_count);
2313
0
      qstate->ext_state[id] = module_wait_subquery;
2314
0
      return 0;
2315
0
    }
2316
0
  }
2317
2318
  /* if this was a parent-side glue query itself, then store that
2319
   * failure in cache. */
2320
0
  if(!qstate->no_cache_store && iq->query_for_pside_glue
2321
0
    && !iq->pside_glue)
2322
0
      iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2323
0
        iq->deleg_msg?iq->deleg_msg->rep:
2324
0
        (iq->response?iq->response->rep:NULL));
2325
2326
0
  errinf(qstate, "all servers for this domain failed,");
2327
0
  errinf_dname(qstate, "at zone", iq->dp->name);
2328
0
  errinf_reply(qstate, iq);
2329
0
  verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
2330
  /* fail -- no more targets, no more hope of targets, no hope 
2331
   * of a response. */
2332
0
  return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2333
0
}
2334
2335
/** 
2336
 * Try to find the NS record set that will resolve a qtype DS query. Due
2337
 * to grandparent/grandchild reasons we did not get a proper lookup right
2338
 * away.  We need to create type NS queries until we get the right parent
2339
 * for this lookup.  We remove labels from the query to find the right point.
2340
 * If we end up at the old dp name, then there is no solution.
2341
 * 
2342
 * @param qstate: query state.
2343
 * @param iq: iterator query state.
2344
 * @param id: module id.
2345
 * @return true if the event requires more immediate processing, false if
2346
 *         not. This is generally only true when forwarding the request to
2347
 *         the final state (i.e., on answer).
2348
 */
2349
static int
2350
processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
2351
0
{
2352
0
  struct module_qstate* subq = NULL;
2353
0
  verbose(VERB_ALGO, "processDSNSFind");
2354
2355
0
  if(!iq->dsns_point) {
2356
    /* initialize */
2357
0
    iq->dsns_point = iq->qchase.qname;
2358
0
    iq->dsns_point_len = iq->qchase.qname_len;
2359
0
  }
2360
  /* robustcheck for internal error: we are not underneath the dp */
2361
0
  if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
2362
0
    errinf_dname(qstate, "for DS query parent-child nameserver search the query is not under the zone", iq->dp->name);
2363
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2364
0
  }
2365
2366
  /* go up one (more) step, until we hit the dp, if so, end */
2367
0
  dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
2368
0
  if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
2369
    /* there was no inbetween nameserver, use the old delegation
2370
     * point again.  And this time, because dsns_point is nonNULL
2371
     * we are going to accept the (bad) result */
2372
0
    iq->state = QUERYTARGETS_STATE;
2373
0
    return 1;
2374
0
  }
2375
0
  iq->state = DSNS_FIND_STATE;
2376
2377
  /* spawn NS lookup (validation not needed, this is for DS lookup) */
2378
0
  log_nametypeclass(VERB_ALGO, "fetch nameservers", 
2379
0
    iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
2380
0
  if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len, 
2381
0
    LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
2382
0
    INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0, 0)) {
2383
0
    errinf_dname(qstate, "for DS query parent-child nameserver search, could not generate NS lookup for", iq->dsns_point);
2384
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2385
0
  }
2386
2387
0
  return 0;
2388
0
}
2389
2390
/**
2391
 * Check if we wait responses for sent queries and update the iterator's
2392
 * external state.
2393
 */
2394
static void
2395
check_waiting_queries(struct iter_qstate* iq, struct module_qstate* qstate,
2396
  int id)
2397
0
{
2398
0
  if(iq->num_target_queries>0 && iq->num_current_queries>0) {
2399
0
    verbose(VERB_ALGO, "waiting for %d targets to "
2400
0
      "resolve or %d outstanding queries to "
2401
0
      "respond", iq->num_target_queries,
2402
0
      iq->num_current_queries);
2403
0
    qstate->ext_state[id] = module_wait_reply;
2404
0
  } else if(iq->num_target_queries>0) {
2405
0
    verbose(VERB_ALGO, "waiting for %d targets to "
2406
0
      "resolve", iq->num_target_queries);
2407
0
    qstate->ext_state[id] = module_wait_subquery;
2408
0
  } else {
2409
0
    verbose(VERB_ALGO, "waiting for %d "
2410
0
      "outstanding queries to respond",
2411
0
      iq->num_current_queries);
2412
0
    qstate->ext_state[id] = module_wait_reply;
2413
0
  }
2414
0
}
2415
  
2416
/** 
2417
 * This is the request event state where the request will be sent to one of
2418
 * its current query targets. This state also handles issuing target lookup
2419
 * queries for missing target IP addresses. Queries typically iterate on
2420
 * this state, both when they are just trying different targets for a given
2421
 * delegation point, and when they change delegation points. This state
2422
 * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
2423
 *
2424
 * @param qstate: query state.
2425
 * @param iq: iterator query state.
2426
 * @param ie: iterator shared global environment.
2427
 * @param id: module id.
2428
 * @return true if the event requires more request processing immediately,
2429
 *         false if not. This state only returns true when it is generating
2430
 *         a SERVFAIL response because the query has hit a dead end.
2431
 */
2432
static int
2433
processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
2434
  struct iter_env* ie, int id)
2435
0
{
2436
0
  int tf_policy;
2437
0
  struct delegpt_addr* target;
2438
0
  struct outbound_entry* outq;
2439
0
  struct sockaddr_storage real_addr;
2440
0
  socklen_t real_addrlen;
2441
0
  int auth_fallback = 0;
2442
0
  uint8_t* qout_orig = NULL;
2443
0
  size_t qout_orig_len = 0;
2444
0
  int sq_check_ratelimit = 1;
2445
0
  int sq_was_ratelimited = 0;
2446
0
  int can_do_promisc = 0;
2447
2448
  /* NOTE: a request will encounter this state for each target it
2449
   * needs to send a query to. That is, at least one per referral,
2450
   * more if some targets timeout or return throwaway answers. */
2451
2452
0
  log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
2453
0
  verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
2454
0
    "currentqueries %d sentcount %d", iq->num_target_queries, 
2455
0
    iq->num_current_queries, iq->sent_count);
2456
2457
  /* Make sure that we haven't run away */
2458
0
  if(iq->referral_count > MAX_REFERRAL_COUNT) {
2459
0
    verbose(VERB_QUERY, "request has exceeded the maximum "
2460
0
      "number of referrrals with %d", iq->referral_count);
2461
0
    errinf(qstate, "exceeded the maximum of referrals");
2462
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2463
0
  }
2464
0
  if(iq->sent_count > ie->max_sent_count) {
2465
0
    verbose(VERB_QUERY, "request has exceeded the maximum "
2466
0
      "number of sends with %d", iq->sent_count);
2467
0
    errinf(qstate, "exceeded the maximum number of sends");
2468
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2469
0
  }
2470
2471
  /* Check if we reached MAX_TARGET_NX limit without a fallback activation. */
2472
0
  if(iq->target_count && !*iq->nxns_dp &&
2473
0
    iq->target_count[TARGET_COUNT_NX] > MAX_TARGET_NX) {
2474
0
    struct delegpt_ns* ns;
2475
    /* If we can wait for resolution, do so. */
2476
0
    if(iq->num_target_queries>0 || iq->num_current_queries>0) {
2477
0
      check_waiting_queries(iq, qstate, id);
2478
0
      return 0;
2479
0
    }
2480
0
    verbose(VERB_ALGO, "request has exceeded the maximum "
2481
0
      "number of nxdomain nameserver lookups (%d) with %d",
2482
0
      MAX_TARGET_NX, iq->target_count[TARGET_COUNT_NX]);
2483
    /* Check for dp because we require one below */
2484
0
    if(!iq->dp) {
2485
0
      verbose(VERB_QUERY, "Failed to get a delegation, "
2486
0
        "giving up");
2487
0
      errinf(qstate, "failed to get a delegation (eg. prime "
2488
0
        "failure)");
2489
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2490
0
    }
2491
    /* We reached the limit but we already have parent side
2492
     * information; stop resolution */
2493
0
    if(iq->dp->has_parent_side_NS) {
2494
0
      verbose(VERB_ALGO, "parent-side information is "
2495
0
        "already present for the delegation point, no "
2496
0
        "fallback possible");
2497
0
      errinf(qstate, "exceeded the maximum nameserver nxdomains");
2498
0
      return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2499
0
    }
2500
0
    verbose(VERB_ALGO, "initiating parent-side fallback for "
2501
0
      "nxdomain nameserver lookups");
2502
    /* Mark all the current NSes as resolved to allow for parent
2503
     * fallback */
2504
0
    for(ns=iq->dp->nslist; ns; ns=ns->next) {
2505
0
      ns->resolved = 1;
2506
0
    }
2507
    /* Note the delegation point that triggered the NXNS fallback;
2508
     * no reason for shared queries to keep trying there.
2509
     * This also marks the fallback activation. */
2510
0
    *iq->nxns_dp = malloc(iq->dp->namelen);
2511
0
    if(!*iq->nxns_dp) {
2512
0
      verbose(VERB_ALGO, "out of memory while initiating "
2513
0
        "fallback");
2514
0
      errinf(qstate, "exceeded the maximum nameserver "
2515
0
        "nxdomains (malloc)");
2516
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2517
0
    }
2518
0
    memcpy(*iq->nxns_dp, iq->dp->name, iq->dp->namelen);
2519
0
  } else if(iq->target_count && *iq->nxns_dp) {
2520
    /* Handle the NXNS fallback case. */
2521
    /* If we can wait for resolution, do so. */
2522
0
    if(iq->num_target_queries>0 || iq->num_current_queries>0) {
2523
0
      check_waiting_queries(iq, qstate, id);
2524
0
      return 0;
2525
0
    }
2526
    /* Check for dp because we require one below */
2527
0
    if(!iq->dp) {
2528
0
      verbose(VERB_QUERY, "Failed to get a delegation, "
2529
0
        "giving up");
2530
0
      errinf(qstate, "failed to get a delegation (eg. prime "
2531
0
        "failure)");
2532
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2533
0
    }
2534
2535
0
    if(iq->target_count[TARGET_COUNT_NX] > MAX_TARGET_NX_FALLBACK) {
2536
0
      verbose(VERB_ALGO, "request has exceeded the maximum "
2537
0
        "number of fallback nxdomain nameserver "
2538
0
        "lookups (%d) with %d", MAX_TARGET_NX_FALLBACK,
2539
0
        iq->target_count[TARGET_COUNT_NX]);
2540
0
      errinf(qstate, "exceeded the maximum nameserver nxdomains");
2541
0
      return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2542
0
    }
2543
2544
0
    if(!iq->dp->has_parent_side_NS) {
2545
0
      struct delegpt_ns* ns;
2546
0
      if(!dname_canonical_compare(*iq->nxns_dp, iq->dp->name)) {
2547
0
        verbose(VERB_ALGO, "this delegation point "
2548
0
          "initiated the fallback, marking the "
2549
0
          "nslist as resolved");
2550
0
        for(ns=iq->dp->nslist; ns; ns=ns->next) {
2551
0
          ns->resolved = 1;
2552
0
        }
2553
0
      }
2554
0
    }
2555
0
  }
2556
  
2557
  /* Make sure we have a delegation point, otherwise priming failed
2558
   * or another failure occurred */
2559
0
  if(!iq->dp) {
2560
0
    verbose(VERB_QUERY, "Failed to get a delegation, giving up");
2561
0
    errinf(qstate, "failed to get a delegation (eg. prime failure)");
2562
0
    return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2563
0
  }
2564
0
  if(!ie->supports_ipv6)
2565
0
    delegpt_no_ipv6(iq->dp);
2566
0
  if(!ie->supports_ipv4 && !ie->nat64.use_nat64)
2567
0
    delegpt_no_ipv4(iq->dp);
2568
0
  delegpt_log(VERB_ALGO, iq->dp);
2569
2570
0
  if(iq->num_current_queries>0) {
2571
    /* already busy answering a query, this restart is because
2572
     * more delegpt addrs became available, wait for existing
2573
     * query. */
2574
0
    verbose(VERB_ALGO, "woke up, but wait for outstanding query");
2575
0
    qstate->ext_state[id] = module_wait_reply;
2576
0
    return 0;
2577
0
  }
2578
2579
0
  if(iq->minimisation_state == INIT_MINIMISE_STATE
2580
0
    && !(iq->chase_flags & BIT_RD)) {
2581
    /* (Re)set qinfo_out to (new) delegation point, except when
2582
     * qinfo_out is already a subdomain of dp. This happens when
2583
     * increasing by more than one label at once (QNAMEs with more
2584
     * than MAX_MINIMISE_COUNT labels). */
2585
0
    if(!(iq->qinfo_out.qname_len 
2586
0
      && dname_subdomain_c(iq->qchase.qname, 
2587
0
        iq->qinfo_out.qname)
2588
0
      && dname_subdomain_c(iq->qinfo_out.qname, 
2589
0
        iq->dp->name))) {
2590
0
      iq->qinfo_out.qname = iq->dp->name;
2591
0
      iq->qinfo_out.qname_len = iq->dp->namelen;
2592
0
      iq->qinfo_out.qtype = LDNS_RR_TYPE_A;
2593
0
      iq->qinfo_out.qclass = iq->qchase.qclass;
2594
0
      iq->qinfo_out.local_alias = NULL;
2595
0
      iq->minimise_count = 0;
2596
0
    }
2597
2598
0
    iq->minimisation_state = MINIMISE_STATE;
2599
0
  }
2600
0
  if(iq->minimisation_state == MINIMISE_STATE) {
2601
0
    int qchaselabs = dname_count_labels(iq->qchase.qname);
2602
0
    int labdiff = qchaselabs -
2603
0
      dname_count_labels(iq->qinfo_out.qname);
2604
2605
0
    qout_orig = iq->qinfo_out.qname;
2606
0
    qout_orig_len = iq->qinfo_out.qname_len;
2607
0
    iq->qinfo_out.qname = iq->qchase.qname;
2608
0
    iq->qinfo_out.qname_len = iq->qchase.qname_len;
2609
0
    iq->minimise_count++;
2610
0
    iq->timeout_count = 0;
2611
2612
0
    iter_dec_attempts(iq->dp, 1, ie->outbound_msg_retry);
2613
2614
    /* Limit number of iterations for QNAMEs with more
2615
     * than MAX_MINIMISE_COUNT labels. Send first MINIMISE_ONE_LAB
2616
     * labels of QNAME always individually.
2617
     */
2618
0
    if(qchaselabs > MAX_MINIMISE_COUNT && labdiff > 1 && 
2619
0
      iq->minimise_count > MINIMISE_ONE_LAB) {
2620
0
      if(iq->minimise_count < MAX_MINIMISE_COUNT) {
2621
0
        int multilabs = qchaselabs - 1 - 
2622
0
          MINIMISE_ONE_LAB;
2623
0
        int extralabs = multilabs / 
2624
0
          MINIMISE_MULTIPLE_LABS;
2625
2626
0
        if (MAX_MINIMISE_COUNT - iq->minimise_count >= 
2627
0
          multilabs % MINIMISE_MULTIPLE_LABS)
2628
          /* Default behaviour is to add 1 label
2629
           * every iteration. Therefore, decrement
2630
           * the extralabs by 1 */
2631
0
          extralabs--;
2632
0
        if (extralabs < labdiff)
2633
0
          labdiff -= extralabs;
2634
0
        else
2635
0
          labdiff = 1;
2636
0
      }
2637
      /* Last minimised iteration, send all labels with
2638
       * QTYPE=NS */
2639
0
      else
2640
0
        labdiff = 1;
2641
0
    }
2642
2643
0
    if(labdiff > 1) {
2644
0
      verbose(VERB_QUERY, "removing %d labels", labdiff-1);
2645
0
      dname_remove_labels(&iq->qinfo_out.qname, 
2646
0
        &iq->qinfo_out.qname_len, 
2647
0
        labdiff-1);
2648
0
    }
2649
0
    if(labdiff < 1 || (labdiff < 2 
2650
0
      && (iq->qchase.qtype == LDNS_RR_TYPE_DS
2651
0
      || iq->qchase.qtype == LDNS_RR_TYPE_A)))
2652
      /* Stop minimising this query, resolve "as usual" */
2653
0
      iq->minimisation_state = DONOT_MINIMISE_STATE;
2654
0
    else if(!qstate->no_cache_lookup) {
2655
0
      struct dns_msg* msg = dns_cache_lookup(qstate->env, 
2656
0
        iq->qinfo_out.qname, iq->qinfo_out.qname_len, 
2657
0
        iq->qinfo_out.qtype, iq->qinfo_out.qclass, 
2658
0
        qstate->query_flags, qstate->region, 
2659
0
        qstate->env->scratch, 0, iq->dp->name,
2660
0
        iq->dp->namelen);
2661
0
      if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2662
0
        LDNS_RCODE_NOERROR)
2663
        /* no need to send query if it is already 
2664
         * cached as NOERROR */
2665
0
        return 1;
2666
0
      if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2667
0
        LDNS_RCODE_NXDOMAIN &&
2668
0
        qstate->env->need_to_validate &&
2669
0
        qstate->env->cfg->harden_below_nxdomain) {
2670
0
        if(msg->rep->security == sec_status_secure) {
2671
0
          iq->response = msg;
2672
0
          return final_state(iq);
2673
0
        }
2674
0
        if(msg->rep->security == sec_status_unchecked) {
2675
0
          struct module_qstate* subq = NULL;
2676
0
          if(!generate_sub_request(
2677
0
            iq->qinfo_out.qname,
2678
0
            iq->qinfo_out.qname_len,
2679
0
            iq->qinfo_out.qtype,
2680
0
            iq->qinfo_out.qclass,
2681
0
            qstate, id, iq,
2682
0
            INIT_REQUEST_STATE,
2683
0
            FINISHED_STATE, &subq, 1, 1))
2684
0
            verbose(VERB_ALGO,
2685
0
            "could not validate NXDOMAIN "
2686
0
            "response");
2687
0
        }
2688
0
      }
2689
0
      if(msg && FLAGS_GET_RCODE(msg->rep->flags) ==
2690
0
        LDNS_RCODE_NXDOMAIN) {
2691
        /* return and add a label in the next
2692
         * minimisation iteration.
2693
         */
2694
0
        return 1;
2695
0
      }
2696
0
    }
2697
0
  }
2698
0
  if(iq->minimisation_state == SKIP_MINIMISE_STATE) {
2699
0
    if(iq->timeout_count < MAX_MINIMISE_TIMEOUT_COUNT)
2700
      /* Do not increment qname, continue incrementing next 
2701
       * iteration */
2702
0
      iq->minimisation_state = MINIMISE_STATE;
2703
0
    else if(!qstate->env->cfg->qname_minimisation_strict)
2704
      /* Too many time-outs detected for this QNAME and QTYPE.
2705
       * We give up, disable QNAME minimisation. */
2706
0
      iq->minimisation_state = DONOT_MINIMISE_STATE;
2707
0
  }
2708
0
  if(iq->minimisation_state == DONOT_MINIMISE_STATE)
2709
0
    iq->qinfo_out = iq->qchase;
2710
2711
  /* now find an answer to this query */
2712
  /* see if authority zones have an answer */
2713
  /* now we know the dp, we can check the auth zone for locally hosted
2714
   * contents */
2715
0
  if(!iq->auth_zone_avoid && qstate->blacklist) {
2716
0
    if(auth_zones_can_fallback(qstate->env->auth_zones,
2717
0
      iq->dp->name, iq->dp->namelen, iq->qinfo_out.qclass)) {
2718
      /* if cache is blacklisted and this zone allows us
2719
       * to fallback to the internet, then do so, and
2720
       * fetch results from the internet servers */
2721
0
      iq->auth_zone_avoid = 1;
2722
0
    }
2723
0
  }
2724
0
  if(iq->auth_zone_avoid) {
2725
0
    iq->auth_zone_avoid = 0;
2726
0
    auth_fallback = 1;
2727
0
  } else if(auth_zones_lookup(qstate->env->auth_zones, &iq->qinfo_out,
2728
0
    qstate->region, &iq->response, &auth_fallback, iq->dp->name,
2729
0
    iq->dp->namelen)) {
2730
    /* use this as a response to be processed by the iterator */
2731
0
    if(verbosity >= VERB_ALGO) {
2732
0
      log_dns_msg("msg from auth zone",
2733
0
        &iq->response->qinfo, iq->response->rep);
2734
0
    }
2735
0
    if((iq->chase_flags&BIT_RD) && !(iq->response->rep->flags&BIT_AA)) {
2736
0
      verbose(VERB_ALGO, "forwarder, ignoring referral from auth zone");
2737
0
    } else {
2738
0
      qstate->env->mesh->num_query_authzone_up++;
2739
0
      iq->num_current_queries++;
2740
0
      iq->chase_to_rd = 0;
2741
0
      iq->dnssec_lame_query = 0;
2742
0
      iq->auth_zone_response = 1;
2743
0
      return next_state(iq, QUERY_RESP_STATE);
2744
0
    }
2745
0
  }
2746
0
  iq->auth_zone_response = 0;
2747
0
  if(auth_fallback == 0) {
2748
    /* like we got servfail from the auth zone lookup, and
2749
     * no internet fallback */
2750
0
    verbose(VERB_ALGO, "auth zone lookup failed, no fallback,"
2751
0
      " servfail");
2752
0
    errinf(qstate, "auth zone lookup failed, fallback is off");
2753
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2754
0
  }
2755
0
  if(iq->dp->auth_dp) {
2756
    /* we wanted to fallback, but had no delegpt, only the
2757
     * auth zone generated delegpt, create an actual one */
2758
0
    iq->auth_zone_avoid = 1;
2759
0
    return next_state(iq, INIT_REQUEST_STATE);
2760
0
  }
2761
  /* but mostly, fallback==1 (like, when no such auth zone exists)
2762
   * and we continue with lookups */
2763
2764
0
  tf_policy = 0;
2765
  /* < not <=, because although the array is large enough for <=, the
2766
   * generated query will immediately be discarded due to depth and
2767
   * that servfail is cached, which is not good as opportunism goes. */
2768
0
  if(iq->depth < ie->max_dependency_depth
2769
0
    && iq->num_target_queries == 0
2770
0
    && (!iq->target_count || iq->target_count[TARGET_COUNT_NX]==0)
2771
0
    && iq->sent_count < TARGET_FETCH_STOP) {
2772
0
    can_do_promisc = 1;
2773
0
  }
2774
  /* if the mesh query list is full, then do not waste cpu and sockets to
2775
   * fetch promiscuous targets. They can be looked up when needed. */
2776
0
  if(!iq->dp->fallback_to_parent_side_NS && can_do_promisc
2777
0
    && !mesh_jostle_exceeded(qstate->env->mesh)) {
2778
0
    tf_policy = ie->target_fetch_policy[iq->depth];
2779
0
  }
2780
2781
  /* if in 0x20 fallback get as many targets as possible */
2782
0
  if(iq->caps_fallback) {
2783
0
    int extra = 0, ret;
2784
0
    size_t naddr, nres, navail;
2785
0
    if((ret=query_for_targets(qstate, iq, ie, id, -1, &extra))!=0) {
2786
0
      errinf(qstate, "could not fetch nameservers for 0x20 fallback");
2787
0
      if(ret == 1)
2788
0
        return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2789
0
      return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
2790
0
    }
2791
0
    iq->num_target_queries += extra;
2792
0
    target_count_increase(iq, extra);
2793
0
    if(iq->num_target_queries > 0) {
2794
      /* wait to get all targets, we want to try em */
2795
0
      verbose(VERB_ALGO, "wait for all targets for fallback");
2796
0
      qstate->ext_state[id] = module_wait_reply;
2797
      /* undo qname minimise step because we'll get back here
2798
       * to do it again */
2799
0
      if(qout_orig && iq->minimise_count > 0) {
2800
0
        iq->minimise_count--;
2801
0
        iq->qinfo_out.qname = qout_orig;
2802
0
        iq->qinfo_out.qname_len = qout_orig_len;
2803
0
      }
2804
0
      return 0;
2805
0
    }
2806
    /* did we do enough fallback queries already? */
2807
0
    delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
2808
    /* the current caps_server is the number of fallbacks sent.
2809
     * the original query is one that matched too, so we have
2810
     * caps_server+1 number of matching queries now */
2811
0
    if(iq->caps_server+1 >= naddr*3 ||
2812
0
      iq->caps_server*2+2 >= (size_t)ie->max_sent_count) {
2813
      /* *2 on sentcount check because ipv6 may fail */
2814
      /* we're done, process the response */
2815
0
      verbose(VERB_ALGO, "0x20 fallback had %d responses "
2816
0
        "match for %d wanted, done.", 
2817
0
        (int)iq->caps_server+1, (int)naddr*3);
2818
0
      iq->response = iq->caps_response;
2819
0
      iq->caps_fallback = 0;
2820
0
      iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */
2821
0
      iq->num_current_queries++; /* RespState decrements it*/
2822
0
      iq->referral_count++; /* make sure we don't loop */
2823
0
      iq->sent_count = 0;
2824
0
      iq->dp_target_count = 0;
2825
0
      iq->state = QUERY_RESP_STATE;
2826
0
      return 1;
2827
0
    }
2828
0
    verbose(VERB_ALGO, "0x20 fallback number %d", 
2829
0
      (int)iq->caps_server);
2830
2831
  /* if there is a policy to fetch missing targets 
2832
   * opportunistically, do it. we rely on the fact that once a 
2833
   * query (or queries) for a missing name have been issued, 
2834
   * they will not show up again. */
2835
0
  } else if(tf_policy != 0) {
2836
0
    int extra = 0;
2837
0
    verbose(VERB_ALGO, "attempt to get extra %d targets", 
2838
0
      tf_policy);
2839
0
    (void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
2840
    /* errors ignored, these targets are not strictly necessary for
2841
     * this result, we do not have to reply with SERVFAIL */
2842
0
    iq->num_target_queries += extra;
2843
0
    target_count_increase(iq, extra);
2844
0
  }
2845
2846
  /* Add the current set of unused targets to our queue. */
2847
0
  delegpt_add_unused_targets(iq->dp);
2848
2849
0
  if(qstate->env->auth_zones) {
2850
0
    uint8_t* sname = NULL;
2851
0
    size_t snamelen = 0;
2852
    /* apply rpz triggers at query time; nameserver IP and dname */
2853
0
    struct dns_msg* forged_response_after_cname;
2854
0
    struct dns_msg* forged_response = rpz_callback_from_iterator_module(qstate, iq);
2855
0
    int count = 0;
2856
0
    while(forged_response && reply_find_rrset_section_an(
2857
0
      forged_response->rep, iq->qchase.qname,
2858
0
      iq->qchase.qname_len, LDNS_RR_TYPE_CNAME,
2859
0
      iq->qchase.qclass) &&
2860
0
      iq->qchase.qtype != LDNS_RR_TYPE_CNAME &&
2861
0
      count++ < ie->max_query_restarts) {
2862
      /* another cname to follow */
2863
0
      if(!handle_cname_response(qstate, iq, forged_response,
2864
0
        &sname, &snamelen)) {
2865
0
        errinf(qstate, "malloc failure, CNAME info");
2866
0
        return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2867
0
      }
2868
0
      iq->qchase.qname = sname;
2869
0
      iq->qchase.qname_len = snamelen;
2870
0
      forged_response_after_cname =
2871
0
        rpz_callback_from_iterator_cname(qstate, iq);
2872
0
      if(forged_response_after_cname) {
2873
0
        forged_response = forged_response_after_cname;
2874
0
      } else {
2875
        /* Follow the CNAME with a query restart */
2876
0
        iq->deleg_msg = NULL;
2877
0
        iq->dp = NULL;
2878
0
        iq->dsns_point = NULL;
2879
0
        iq->auth_zone_response = 0;
2880
0
        iq->refetch_glue = 0;
2881
0
        iq->query_restart_count++;
2882
0
        iq->sent_count = 0;
2883
0
        iq->dp_target_count = 0;
2884
0
        if(qstate->env->cfg->qname_minimisation)
2885
0
          iq->minimisation_state = INIT_MINIMISE_STATE;
2886
0
        outbound_list_clear(&iq->outlist);
2887
0
        iq->num_current_queries = 0;
2888
0
        fptr_ok(fptr_whitelist_modenv_detach_subs(
2889
0
          qstate->env->detach_subs));
2890
0
        (*qstate->env->detach_subs)(qstate);
2891
0
        iq->num_target_queries = 0;
2892
0
        return next_state(iq, INIT_REQUEST_STATE);
2893
0
      }
2894
0
    }
2895
0
    if(forged_response != NULL) {
2896
0
      qstate->ext_state[id] = module_finished;
2897
0
      qstate->return_rcode = LDNS_RCODE_NOERROR;
2898
0
      qstate->return_msg = forged_response;
2899
0
      iq->response = forged_response;
2900
0
      next_state(iq, FINISHED_STATE);
2901
0
      if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
2902
0
        log_err("rpz: prepend rrsets: out of memory");
2903
0
        return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2904
0
      }
2905
0
      return 0;
2906
0
    }
2907
0
  }
2908
2909
  /* Select the next usable target, filtering out unsuitable targets. */
2910
0
  target = iter_server_selection(ie, qstate->env, iq->dp,
2911
0
    iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
2912
0
    &iq->dnssec_lame_query, &iq->chase_to_rd,
2913
0
    iq->num_target_queries, qstate->blacklist,
2914
0
    qstate->prefetch_leeway);
2915
2916
  /* If no usable target was selected... */
2917
0
  if(!target) {
2918
    /* Here we distinguish between three states: generate a new 
2919
     * target query, just wait, or quit (with a SERVFAIL).
2920
     * We have the following information: number of active 
2921
     * target queries, number of active current queries, 
2922
     * the presence of missing targets at this delegation 
2923
     * point, and the given query target policy. */
2924
    
2925
    /* Check for the wait condition. If this is true, then 
2926
     * an action must be taken. */
2927
0
    if(iq->num_target_queries==0 && iq->num_current_queries==0) {
2928
      /* If there is nothing to wait for, then we need 
2929
       * to distinguish between generating (a) new target 
2930
       * query, or failing. */
2931
0
      if(delegpt_count_missing_targets(iq->dp, NULL) > 0) {
2932
0
        int qs = 0, ret;
2933
0
        verbose(VERB_ALGO, "querying for next "
2934
0
          "missing target");
2935
0
        if((ret=query_for_targets(qstate, iq, ie, id, 
2936
0
          1, &qs))!=0) {
2937
0
          errinf(qstate, "could not fetch nameserver");
2938
0
          errinf_dname(qstate, "at zone", iq->dp->name);
2939
0
          if(ret == 1)
2940
0
            return error_response(qstate, id,
2941
0
              LDNS_RCODE_SERVFAIL);
2942
0
          return error_response_cache(qstate, id,
2943
0
            LDNS_RCODE_SERVFAIL);
2944
0
        }
2945
0
        if(qs == 0 && 
2946
0
           delegpt_count_missing_targets(iq->dp, NULL) == 0){
2947
          /* it looked like there were missing
2948
           * targets, but they did not turn up.
2949
           * Try the bad choices again (if any),
2950
           * when we get back here missing==0,
2951
           * so this is not a loop. */
2952
0
          return 1;
2953
0
        }
2954
0
        if(qs == 0) {
2955
          /* There should be targets now, and
2956
           * if there are not, it should not
2957
           * wait for no targets. Stop it from
2958
           * waiting forever, or looping to
2959
           * here, as a safeguard. */
2960
0
          errinf(qstate, "could not generate nameserver lookups");
2961
0
          errinf_dname(qstate, "at zone", iq->dp->name);
2962
0
          return error_response(qstate, id,
2963
0
            LDNS_RCODE_SERVFAIL);
2964
0
        }
2965
0
        iq->num_target_queries += qs;
2966
0
        target_count_increase(iq, qs);
2967
0
      }
2968
      /* Since a target query might have been made, we 
2969
       * need to check again. */
2970
0
      if(iq->num_target_queries == 0) {
2971
        /* if in capsforid fallback, instead of last
2972
         * resort, we agree with the current reply
2973
         * we have (if any) (our count of addrs bad)*/
2974
0
        if(iq->caps_fallback && iq->caps_reply) {
2975
          /* we're done, process the response */
2976
0
          verbose(VERB_ALGO, "0x20 fallback had %d responses, "
2977
0
            "but no more servers except "
2978
0
            "last resort, done.", 
2979
0
            (int)iq->caps_server+1);
2980
0
          iq->response = iq->caps_response;
2981
0
          iq->caps_fallback = 0;
2982
0
          iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry); /* space for fallback */
2983
0
          iq->num_current_queries++; /* RespState decrements it*/
2984
0
          iq->referral_count++; /* make sure we don't loop */
2985
0
          iq->sent_count = 0;
2986
0
          iq->dp_target_count = 0;
2987
0
          iq->state = QUERY_RESP_STATE;
2988
0
          return 1;
2989
0
        }
2990
0
        return processLastResort(qstate, iq, ie, id);
2991
0
      }
2992
0
    }
2993
2994
    /* otherwise, we have no current targets, so submerge 
2995
     * until one of the target or direct queries return. */
2996
0
    verbose(VERB_ALGO, "no current targets");
2997
0
    check_waiting_queries(iq, qstate, id);
2998
    /* undo qname minimise step because we'll get back here
2999
     * to do it again */
3000
0
    if(qout_orig && iq->minimise_count > 0) {
3001
0
      iq->minimise_count--;
3002
0
      iq->qinfo_out.qname = qout_orig;
3003
0
      iq->qinfo_out.qname_len = qout_orig_len;
3004
0
    }
3005
0
    return 0;
3006
0
  }
3007
3008
  /* We have a target. We could have created promiscuous target
3009
   * queries but we are currently under pressure (mesh_jostle_exceeded).
3010
   * If we are configured to allow promiscuous target queries and haven't
3011
   * gone out to the network for a target query for this delegation, then
3012
   * it is possible to slip in a promiscuous one with a 1/10 chance. */
3013
0
  if(can_do_promisc && tf_policy == 0 && iq->depth == 0
3014
0
    && iq->depth < ie->max_dependency_depth
3015
0
    && ie->target_fetch_policy[iq->depth] != 0
3016
0
    && iq->dp_target_count == 0
3017
0
    && !ub_random_max(qstate->env->rnd, 10)) {
3018
0
    int extra = 0;
3019
0
    verbose(VERB_ALGO, "available target exists in cache but "
3020
0
      "attempt to get extra 1 target");
3021
0
    (void)query_for_targets(qstate, iq, ie, id, 1, &extra);
3022
    /* errors ignored, these targets are not strictly necessary for
3023
    * this result, we do not have to reply with SERVFAIL */
3024
0
    if(extra > 0) {
3025
0
      iq->num_target_queries += extra;
3026
0
      target_count_increase(iq, extra);
3027
0
      check_waiting_queries(iq, qstate, id);
3028
      /* undo qname minimise step because we'll get back here
3029
       * to do it again */
3030
0
      if(qout_orig && iq->minimise_count > 0) {
3031
0
        iq->minimise_count--;
3032
0
        iq->qinfo_out.qname = qout_orig;
3033
0
        iq->qinfo_out.qname_len = qout_orig_len;
3034
0
      }
3035
0
      return 0;
3036
0
    }
3037
0
  }
3038
3039
0
  target_count_increase_global_quota(iq, 1);
3040
0
  if(iq->target_count && iq->target_count[TARGET_COUNT_GLOBAL_QUOTA]
3041
0
    > MAX_GLOBAL_QUOTA) {
3042
0
    char s[LDNS_MAX_DOMAINLEN];
3043
0
    dname_str(qstate->qinfo.qname, s);
3044
0
    verbose(VERB_QUERY, "request %s has exceeded the maximum "
3045
0
      "global quota on number of upstream queries %d", s,
3046
0
      iq->target_count[TARGET_COUNT_GLOBAL_QUOTA]);
3047
0
    return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
3048
0
  }
3049
3050
  /* Do not check ratelimit for forwarding queries or if we already got a
3051
   * pass. */
3052
0
  sq_check_ratelimit = (!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok);
3053
  /* We have a valid target. */
3054
0
  if(verbosity >= VERB_QUERY) {
3055
0
    log_query_info(VERB_QUERY, "sending query:", &iq->qinfo_out);
3056
0
    log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
3057
0
      &target->addr, target->addrlen);
3058
0
    verbose(VERB_ALGO, "dnssec status: %s%s",
3059
0
      iq->dnssec_expected?"expected": "not expected",
3060
0
      iq->dnssec_lame_query?" but lame_query anyway": "");
3061
0
  }
3062
3063
0
  real_addr = target->addr;
3064
0
  real_addrlen = target->addrlen;
3065
3066
0
  if(ie->nat64.use_nat64 && target->addr.ss_family == AF_INET) {
3067
0
    addr_to_nat64(&target->addr, &ie->nat64.nat64_prefix_addr,
3068
0
      ie->nat64.nat64_prefix_addrlen, ie->nat64.nat64_prefix_net,
3069
0
      &real_addr, &real_addrlen);
3070
0
    log_name_addr(VERB_QUERY, "applied NAT64:",
3071
0
      iq->dp->name, &real_addr, real_addrlen);
3072
0
  }
3073
3074
0
  fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
3075
0
  outq = (*qstate->env->send_query)(&iq->qinfo_out,
3076
0
    iq->chase_flags | (iq->chase_to_rd?BIT_RD:0),
3077
    /* unset CD if to forwarder(RD set) and not dnssec retry
3078
     * (blacklist nonempty) and no trust-anchors are configured
3079
     * above the qname or on the first attempt when dnssec is on */
3080
0
    (qstate->env->cfg->disable_edns_do?0:EDNS_DO)|
3081
0
    ((iq->chase_to_rd||(iq->chase_flags&BIT_RD)!=0)&&
3082
0
    !qstate->blacklist&&(!iter_qname_indicates_dnssec(qstate->env,
3083
0
    &iq->qinfo_out)||target->attempts==1)?0:BIT_CD),
3084
0
    iq->dnssec_expected, iq->caps_fallback || is_caps_whitelisted(
3085
0
    ie, iq), sq_check_ratelimit, &real_addr, real_addrlen,
3086
0
    iq->dp->name, iq->dp->namelen,
3087
0
    (iq->dp->tcp_upstream || qstate->env->cfg->tcp_upstream),
3088
0
    (iq->dp->ssl_upstream || qstate->env->cfg->ssl_upstream),
3089
0
    target->tls_auth_name, qstate, &sq_was_ratelimited);
3090
0
  if(!outq) {
3091
0
    if(sq_was_ratelimited) {
3092
0
      lock_basic_lock(&ie->queries_ratelimit_lock);
3093
0
      ie->num_queries_ratelimited++;
3094
0
      lock_basic_unlock(&ie->queries_ratelimit_lock);
3095
0
      verbose(VERB_ALGO, "query exceeded ratelimits");
3096
0
      qstate->was_ratelimited = 1;
3097
0
      errinf_dname(qstate, "exceeded ratelimit for zone",
3098
0
        iq->dp->name);
3099
0
      return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
3100
0
    }
3101
0
    log_addr(VERB_QUERY, "error sending query to auth server",
3102
0
      &real_addr, real_addrlen);
3103
0
    if(qstate->env->cfg->qname_minimisation)
3104
0
      iq->minimisation_state = SKIP_MINIMISE_STATE;
3105
0
    return next_state(iq, QUERYTARGETS_STATE);
3106
0
  }
3107
0
  outbound_list_insert(&iq->outlist, outq);
3108
0
  iq->num_current_queries++;
3109
0
  iq->sent_count++;
3110
0
  qstate->ext_state[id] = module_wait_reply;
3111
3112
0
  return 0;
3113
0
}
3114
3115
/** find NS rrset in given list */
3116
static struct ub_packed_rrset_key*
3117
find_NS(struct reply_info* rep, size_t from, size_t to)
3118
0
{
3119
0
  size_t i;
3120
0
  for(i=from; i<to; i++) {
3121
0
    if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
3122
0
      return rep->rrsets[i];
3123
0
  }
3124
0
  return NULL;
3125
0
}
3126
3127
3128
/** 
3129
 * Process the query response. All queries end up at this state first. This
3130
 * process generally consists of analyzing the response and routing the
3131
 * event to the next state (either bouncing it back to a request state, or
3132
 * terminating the processing for this event).
3133
 * 
3134
 * @param qstate: query state.
3135
 * @param iq: iterator query state.
3136
 * @param ie: iterator shared global environment.
3137
 * @param id: module id.
3138
 * @return true if the event requires more immediate processing, false if
3139
 *         not. This is generally only true when forwarding the request to
3140
 *         the final state (i.e., on answer).
3141
 */
3142
static int
3143
processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
3144
  struct iter_env* ie, int id)
3145
0
{
3146
0
  int dnsseclame = 0, origtypecname = 0, orig_empty_nodata_found;
3147
0
  enum response_type type;
3148
3149
0
  iq->num_current_queries--;
3150
3151
0
  if(!inplace_cb_query_response_call(qstate->env, qstate, iq->response))
3152
0
    log_err("unable to call query_response callback");
3153
3154
0
  if(iq->response == NULL) {
3155
    /* Don't increment qname when QNAME minimisation is enabled */
3156
0
    if(qstate->env->cfg->qname_minimisation) {
3157
0
      iq->minimisation_state = SKIP_MINIMISE_STATE;
3158
0
    }
3159
0
    iq->timeout_count++;
3160
0
    iq->chase_to_rd = 0;
3161
0
    iq->dnssec_lame_query = 0;
3162
0
    verbose(VERB_ALGO, "query response was timeout");
3163
0
    return next_state(iq, QUERYTARGETS_STATE);
3164
0
  }
3165
0
  iq->timeout_count = 0;
3166
0
  orig_empty_nodata_found = iq->empty_nodata_found;
3167
0
  type = response_type_from_server(
3168
0
    (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
3169
0
    iq->response, &iq->qinfo_out, iq->dp, &iq->empty_nodata_found);
3170
0
  iq->chase_to_rd = 0;
3171
  /* remove TC flag, if this is erroneously set by TCP upstream */
3172
0
  iq->response->rep->flags &= ~BIT_TC;
3173
0
  if(orig_empty_nodata_found != iq->empty_nodata_found &&
3174
0
    iq->empty_nodata_found < EMPTY_NODATA_RETRY_COUNT) {
3175
    /* try to search at another server */
3176
0
    if(qstate->reply) {
3177
0
      struct delegpt_addr* a = delegpt_find_addr(
3178
0
        iq->dp, &qstate->reply->remote_addr,
3179
0
        qstate->reply->remote_addrlen);
3180
      /* make selection disprefer it */
3181
0
      if(a) a->lame = 1;
3182
0
    }
3183
0
    return next_state(iq, QUERYTARGETS_STATE);
3184
0
  }
3185
0
  if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD) &&
3186
0
    !iq->auth_zone_response) {
3187
    /* When forwarding (RD bit is set), we handle referrals 
3188
     * differently. No queries should be sent elsewhere */
3189
0
    type = RESPONSE_TYPE_ANSWER;
3190
0
  }
3191
0
  if(!qstate->env->cfg->disable_dnssec_lame_check && iq->dnssec_expected 
3192
0
                && !iq->dnssec_lame_query &&
3193
0
    !(iq->chase_flags&BIT_RD) 
3194
0
    && iq->sent_count < DNSSEC_LAME_DETECT_COUNT
3195
0
    && type != RESPONSE_TYPE_LAME 
3196
0
    && type != RESPONSE_TYPE_REC_LAME 
3197
0
    && type != RESPONSE_TYPE_THROWAWAY 
3198
0
    && type != RESPONSE_TYPE_UNTYPED) {
3199
    /* a possible answer, see if it is missing DNSSEC */
3200
    /* but not when forwarding, so we dont mark fwder lame */
3201
0
    if(!iter_msg_has_dnssec(iq->response)) {
3202
      /* Mark this address as dnsseclame in this dp,
3203
       * because that will make serverselection disprefer
3204
       * it, but also, once it is the only final option,
3205
       * use dnssec-lame-bypass if it needs to query there.*/
3206
0
      if(qstate->reply) {
3207
0
        struct delegpt_addr* a = delegpt_find_addr(
3208
0
          iq->dp, &qstate->reply->remote_addr,
3209
0
          qstate->reply->remote_addrlen);
3210
0
        if(a) a->dnsseclame = 1;
3211
0
      }
3212
      /* test the answer is from the zone we expected,
3213
       * otherwise, (due to parent,child on same server), we
3214
       * might mark the server,zone lame inappropriately */
3215
0
      if(!iter_msg_from_zone(iq->response, iq->dp, type,
3216
0
        iq->qchase.qclass))
3217
0
        qstate->reply = NULL;
3218
0
      type = RESPONSE_TYPE_LAME;
3219
0
      dnsseclame = 1;
3220
0
    }
3221
0
  } else iq->dnssec_lame_query = 0;
3222
  /* see if referral brings us close to the target */
3223
0
  if(type == RESPONSE_TYPE_REFERRAL) {
3224
0
    struct ub_packed_rrset_key* ns = find_NS(
3225
0
      iq->response->rep, iq->response->rep->an_numrrsets,
3226
0
      iq->response->rep->an_numrrsets 
3227
0
      + iq->response->rep->ns_numrrsets);
3228
0
    if(!ns) ns = find_NS(iq->response->rep, 0, 
3229
0
        iq->response->rep->an_numrrsets);
3230
0
    if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name) 
3231
0
      || !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
3232
0
      verbose(VERB_ALGO, "bad referral, throwaway");
3233
0
      type = RESPONSE_TYPE_THROWAWAY;
3234
0
    } else
3235
0
      iter_scrub_ds(iq->response, ns, iq->dp->name);
3236
0
  } else iter_scrub_ds(iq->response, NULL, NULL);
3237
0
  if(type == RESPONSE_TYPE_THROWAWAY &&
3238
0
    FLAGS_GET_RCODE(iq->response->rep->flags) == LDNS_RCODE_YXDOMAIN) {
3239
    /* YXDOMAIN is a permanent error, no need to retry */
3240
0
    type = RESPONSE_TYPE_ANSWER;
3241
0
  }
3242
0
  if(type == RESPONSE_TYPE_CNAME)
3243
0
    origtypecname = 1;
3244
0
  if(type == RESPONSE_TYPE_CNAME && iq->response->rep->an_numrrsets >= 1
3245
0
    && ntohs(iq->response->rep->rrsets[0]->rk.type) == LDNS_RR_TYPE_DNAME) {
3246
0
    uint8_t* sname = NULL;
3247
0
    size_t snamelen = 0;
3248
0
    get_cname_target(iq->response->rep->rrsets[0], &sname,
3249
0
      &snamelen);
3250
0
    if(snamelen && dname_subdomain_c(sname, iq->response->rep->rrsets[0]->rk.dname)) {
3251
      /* DNAME to a subdomain loop; do not recurse */
3252
0
      type = RESPONSE_TYPE_ANSWER;
3253
0
    }
3254
0
  }
3255
0
  if(type == RESPONSE_TYPE_CNAME &&
3256
0
    (iq->qchase.qtype == LDNS_RR_TYPE_CNAME ||
3257
0
      iq->qchase.qtype == LDNS_RR_TYPE_ANY) &&
3258
0
    iq->minimisation_state == MINIMISE_STATE &&
3259
0
    query_dname_compare(iq->qchase.qname, iq->qinfo_out.qname) == 0) {
3260
    /* The minimised query for full QTYPE and hidden QTYPE can be
3261
     * classified as CNAME response type, even when the original
3262
     * QTYPE=CNAME. This should be treated as answer response type.
3263
     */
3264
    /* For QTYPE=ANY, it is also considered the response, that
3265
     * is what the classifier would say, if it saw qtype ANY,
3266
     * and this same response was returned for that. The response
3267
     * can already be treated as such an answer, without having
3268
     * to send another query with a new qtype. */
3269
0
    type = RESPONSE_TYPE_ANSWER;
3270
0
  }
3271
3272
  /* handle each of the type cases */
3273
0
  if(type == RESPONSE_TYPE_ANSWER) {
3274
    /* ANSWER type responses terminate the query algorithm, 
3275
     * so they sent on their */
3276
0
    if(verbosity >= VERB_DETAIL) {
3277
0
      verbose(VERB_DETAIL, "query response was %s",
3278
0
        FLAGS_GET_RCODE(iq->response->rep->flags)
3279
0
        ==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
3280
0
        (iq->response->rep->an_numrrsets?"ANSWER":
3281
0
        "nodata ANSWER"));
3282
0
    }
3283
    /* if qtype is DS, check we have the right level of answer,
3284
     * like grandchild answer but we need the middle, reject it */
3285
0
    if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
3286
0
      && !(iq->chase_flags&BIT_RD)
3287
0
      && iter_ds_toolow(iq->response, iq->dp)
3288
0
      && iter_dp_cangodown(&iq->qchase, iq->dp)) {
3289
      /* close down outstanding requests to be discarded */
3290
0
      outbound_list_clear(&iq->outlist);
3291
0
      iq->num_current_queries = 0;
3292
0
      fptr_ok(fptr_whitelist_modenv_detach_subs(
3293
0
        qstate->env->detach_subs));
3294
0
      (*qstate->env->detach_subs)(qstate);
3295
0
      iq->num_target_queries = 0;
3296
0
      return processDSNSFind(qstate, iq, id);
3297
0
    }
3298
0
    if(iq->qchase.qtype == LDNS_RR_TYPE_DNSKEY && SERVE_EXPIRED
3299
0
      && qstate->is_valrec &&
3300
0
      reply_find_answer_rrset(&iq->qchase, iq->response->rep) != NULL) {
3301
      /* clean out the authority section, if any, so it
3302
       * does not overwrite dnssec valid data in the
3303
       * validation recursion lookup. */
3304
0
      verbose(VERB_ALGO, "make DNSKEY minimal for serve "
3305
0
        "expired");
3306
0
      iter_make_minimal(iq->response->rep);
3307
0
    }
3308
0
    if(!qstate->no_cache_store)
3309
0
      iter_dns_store(qstate->env, &iq->response->qinfo,
3310
0
        iq->response->rep,
3311
0
        iq->qchase.qtype != iq->response->qinfo.qtype,
3312
0
        qstate->prefetch_leeway,
3313
0
        iq->dp&&iq->dp->has_parent_side_NS,
3314
0
        qstate->region, qstate->query_flags,
3315
0
        qstate->qstarttime, qstate->is_valrec);
3316
    /* close down outstanding requests to be discarded */
3317
0
    outbound_list_clear(&iq->outlist);
3318
0
    iq->num_current_queries = 0;
3319
0
    fptr_ok(fptr_whitelist_modenv_detach_subs(
3320
0
      qstate->env->detach_subs));
3321
0
    (*qstate->env->detach_subs)(qstate);
3322
0
    iq->num_target_queries = 0;
3323
0
    if(qstate->reply)
3324
0
      sock_list_insert(&qstate->reply_origin,
3325
0
        &qstate->reply->remote_addr,
3326
0
        qstate->reply->remote_addrlen, qstate->region);
3327
0
    if(iq->minimisation_state != DONOT_MINIMISE_STATE
3328
0
      && !(iq->chase_flags & BIT_RD)) {
3329
0
      if(FLAGS_GET_RCODE(iq->response->rep->flags) != 
3330
0
        LDNS_RCODE_NOERROR) {
3331
0
        if(qstate->env->cfg->qname_minimisation_strict) {
3332
0
          if(FLAGS_GET_RCODE(iq->response->rep->flags) ==
3333
0
            LDNS_RCODE_NXDOMAIN) {
3334
0
            iter_scrub_nxdomain(iq->response);
3335
0
            return final_state(iq);
3336
0
          }
3337
0
          return error_response_cache(qstate, id,
3338
0
            LDNS_RCODE_SERVFAIL);
3339
0
        }
3340
        /* Best effort qname-minimisation. 
3341
         * Stop minimising and send full query when
3342
         * RCODE is not NOERROR. */
3343
0
        iq->minimisation_state = DONOT_MINIMISE_STATE;
3344
0
      }
3345
0
      if(FLAGS_GET_RCODE(iq->response->rep->flags) ==
3346
0
        LDNS_RCODE_NXDOMAIN && !origtypecname) {
3347
        /* Stop resolving when NXDOMAIN is DNSSEC
3348
         * signed. Based on assumption that nameservers
3349
         * serving signed zones do not return NXDOMAIN
3350
         * for empty-non-terminals. */
3351
        /* If this response is actually a CNAME type,
3352
         * the nxdomain rcode may not be for the qname,
3353
         * and so it is not the final response. */
3354
0
        if(iq->dnssec_expected)
3355
0
          return final_state(iq);
3356
        /* Make subrequest to validate intermediate
3357
         * NXDOMAIN if harden-below-nxdomain is
3358
         * enabled. */
3359
0
        if(qstate->env->cfg->harden_below_nxdomain &&
3360
0
          qstate->env->need_to_validate) {
3361
0
          struct module_qstate* subq = NULL;
3362
0
          log_query_info(VERB_QUERY,
3363
0
            "schedule NXDOMAIN validation:",
3364
0
            &iq->response->qinfo);
3365
0
          if(!generate_sub_request(
3366
0
            iq->response->qinfo.qname,
3367
0
            iq->response->qinfo.qname_len,
3368
0
            iq->response->qinfo.qtype,
3369
0
            iq->response->qinfo.qclass,
3370
0
            qstate, id, iq,
3371
0
            INIT_REQUEST_STATE,
3372
0
            FINISHED_STATE, &subq, 1, 1))
3373
0
            verbose(VERB_ALGO,
3374
0
            "could not validate NXDOMAIN "
3375
0
            "response");
3376
0
        }
3377
0
      }
3378
0
      return next_state(iq, QUERYTARGETS_STATE);
3379
0
    }
3380
0
    return final_state(iq);
3381
0
  } else if(type == RESPONSE_TYPE_REFERRAL) {
3382
0
    struct delegpt* old_dp = NULL;
3383
    /* REFERRAL type responses get a reset of the 
3384
     * delegation point, and back to the QUERYTARGETS_STATE. */
3385
0
    verbose(VERB_DETAIL, "query response was REFERRAL");
3386
3387
    /* if hardened, only store referral if we asked for it */
3388
0
    if(!qstate->no_cache_store &&
3389
0
    (!qstate->env->cfg->harden_referral_path ||
3390
0
        (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS 
3391
0
      && (qstate->query_flags&BIT_RD) 
3392
0
      && !(qstate->query_flags&BIT_CD)
3393
         /* we know that all other NS rrsets are scrubbed
3394
          * away, thus on referral only one is left.
3395
          * see if that equals the query name... */
3396
0
      && ( /* auth section, but sometimes in answer section*/
3397
0
        reply_find_rrset_section_ns(iq->response->rep,
3398
0
        iq->qchase.qname, iq->qchase.qname_len,
3399
0
        LDNS_RR_TYPE_NS, iq->qchase.qclass)
3400
0
        || reply_find_rrset_section_an(iq->response->rep,
3401
0
        iq->qchase.qname, iq->qchase.qname_len,
3402
0
        LDNS_RR_TYPE_NS, iq->qchase.qclass)
3403
0
        )
3404
0
        ))) {
3405
      /* Store the referral under the current query */
3406
      /* no prefetch-leeway, since its not the answer */
3407
0
      iter_dns_store(qstate->env, &iq->response->qinfo,
3408
0
        iq->response->rep, 1, 0, 0, NULL, 0,
3409
0
        qstate->qstarttime, qstate->is_valrec);
3410
0
      if(iq->store_parent_NS)
3411
0
        iter_store_parentside_NS(qstate->env, 
3412
0
          iq->response->rep);
3413
0
      if(qstate->env->neg_cache)
3414
0
        val_neg_addreferral(qstate->env->neg_cache, 
3415
0
          iq->response->rep, iq->dp->name);
3416
0
    }
3417
    /* store parent-side-in-zone-glue, if directly queried for */
3418
0
    if(!qstate->no_cache_store && iq->query_for_pside_glue
3419
0
      && !iq->pside_glue) {
3420
0
        iq->pside_glue = reply_find_rrset(iq->response->rep, 
3421
0
          iq->qchase.qname, iq->qchase.qname_len, 
3422
0
          iq->qchase.qtype, iq->qchase.qclass);
3423
0
        if(iq->pside_glue) {
3424
0
          log_rrset_key(VERB_ALGO, "found parent-side "
3425
0
            "glue", iq->pside_glue);
3426
0
          iter_store_parentside_rrset(qstate->env,
3427
0
            iq->pside_glue);
3428
0
        }
3429
0
    }
3430
3431
    /* Reset the event state, setting the current delegation 
3432
     * point to the referral. */
3433
0
    iq->deleg_msg = iq->response;
3434
    /* Keep current delegation point for label comparison */
3435
0
    old_dp = iq->dp;
3436
0
    iq->dp = delegpt_from_message(iq->response, qstate->region);
3437
0
    if (qstate->env->cfg->qname_minimisation)
3438
0
      iq->minimisation_state = INIT_MINIMISE_STATE;
3439
0
    if(!iq->dp) {
3440
0
      errinf(qstate, "malloc failure, for delegation point");
3441
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3442
0
    }
3443
0
    if(old_dp->namelabs + 1 < iq->dp->namelabs) {
3444
      /* We got a grandchild delegation (more than one label
3445
       * difference) than expected. Check for in-between
3446
       * delegations in the cache and remove them.
3447
       * They could prove problematic when they expire
3448
       * and rrset_expired_above() encounters them during
3449
       * delegation cache lookups. */
3450
0
      uint8_t* qname = iq->dp->name;
3451
0
      size_t qnamelen = iq->dp->namelen;
3452
0
      rrset_cache_remove_above(qstate->env->rrset_cache,
3453
0
        &qname, &qnamelen, LDNS_RR_TYPE_NS,
3454
0
        iq->qchase.qclass, *qstate->env->now,
3455
0
        old_dp->name, old_dp->namelen);
3456
0
    }
3457
0
    if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 
3458
0
      qstate->region, iq->dp, 0)) {
3459
0
      errinf(qstate, "malloc failure, copy extra info into delegation point");
3460
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3461
0
    }
3462
0
    if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
3463
0
      iq->store_parent_NS->name) == 0)
3464
0
      iter_merge_retry_counts(iq->dp, iq->store_parent_NS,
3465
0
        ie->outbound_msg_retry);
3466
0
    delegpt_log(VERB_ALGO, iq->dp);
3467
    /* Count this as a referral. */
3468
0
    iq->referral_count++;
3469
0
    iq->sent_count = 0;
3470
0
    iq->dp_target_count = 0;
3471
    /* see if the next dp is a trust anchor, or a DS was sent
3472
     * along, indicating dnssec is expected for next zone */
3473
0
    iq->dnssec_expected = iter_indicates_dnssec(qstate->env, 
3474
0
      iq->dp, iq->response, iq->qchase.qclass);
3475
    /* if dnssec, validating then also fetch the key for the DS */
3476
0
    if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
3477
0
      !(qstate->query_flags&BIT_CD))
3478
0
      generate_dnskey_prefetch(qstate, iq, id);
3479
3480
    /* spawn off NS and addr to auth servers for the NS we just
3481
     * got in the referral. This gets authoritative answer
3482
     * (answer section trust level) rrset. 
3483
     * right after, we detach the subs, answer goes to cache. */
3484
0
    if(qstate->env->cfg->harden_referral_path)
3485
0
      generate_ns_check(qstate, iq, id);
3486
3487
    /* stop current outstanding queries. 
3488
     * FIXME: should the outstanding queries be waited for and
3489
     * handled? Say by a subquery that inherits the outbound_entry.
3490
     */
3491
0
    outbound_list_clear(&iq->outlist);
3492
0
    iq->num_current_queries = 0;
3493
0
    fptr_ok(fptr_whitelist_modenv_detach_subs(
3494
0
      qstate->env->detach_subs));
3495
0
    (*qstate->env->detach_subs)(qstate);
3496
0
    iq->num_target_queries = 0;
3497
0
    iq->response = NULL;
3498
0
    iq->fail_addr_type = 0;
3499
0
    verbose(VERB_ALGO, "cleared outbound list for next round");
3500
0
    return next_state(iq, QUERYTARGETS_STATE);
3501
0
  } else if(type == RESPONSE_TYPE_CNAME) {
3502
0
    uint8_t* sname = NULL;
3503
0
    size_t snamelen = 0;
3504
    /* CNAME type responses get a query restart (i.e., get a 
3505
     * reset of the query state and go back to INIT_REQUEST_STATE).
3506
     */
3507
0
    verbose(VERB_DETAIL, "query response was CNAME");
3508
0
    if(verbosity >= VERB_ALGO)
3509
0
      log_dns_msg("cname msg", &iq->response->qinfo, 
3510
0
        iq->response->rep);
3511
    /* if qtype is DS, check we have the right level of answer,
3512
     * like grandchild answer but we need the middle, reject it */
3513
0
    if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
3514
0
      && !(iq->chase_flags&BIT_RD)
3515
0
      && iter_ds_toolow(iq->response, iq->dp)
3516
0
      && iter_dp_cangodown(&iq->qchase, iq->dp)) {
3517
0
      outbound_list_clear(&iq->outlist);
3518
0
      iq->num_current_queries = 0;
3519
0
      fptr_ok(fptr_whitelist_modenv_detach_subs(
3520
0
        qstate->env->detach_subs));
3521
0
      (*qstate->env->detach_subs)(qstate);
3522
0
      iq->num_target_queries = 0;
3523
0
      return processDSNSFind(qstate, iq, id);
3524
0
    }
3525
0
    if(iq->minimisation_state == MINIMISE_STATE &&
3526
0
      query_dname_compare(iq->qchase.qname,
3527
0
      iq->qinfo_out.qname) != 0) {
3528
0
      verbose(VERB_ALGO, "continue query minimisation, "
3529
0
        "downwards, after CNAME response for "
3530
0
        "intermediate label");
3531
      /* continue query minimisation, downwards */
3532
0
      return next_state(iq, QUERYTARGETS_STATE);
3533
0
    }
3534
    /* Process the CNAME response. */
3535
0
    if(!handle_cname_response(qstate, iq, iq->response, 
3536
0
      &sname, &snamelen)) {
3537
0
      errinf(qstate, "malloc failure, CNAME info");
3538
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3539
0
    }
3540
    /* cache the CNAME response under the current query */
3541
    /* NOTE : set referral=1, so that rrsets get stored but not 
3542
     * the partial query answer (CNAME only). */
3543
    /* prefetchleeway applied because this updates answer parts */
3544
0
    if(!qstate->no_cache_store)
3545
0
      iter_dns_store(qstate->env, &iq->response->qinfo,
3546
0
        iq->response->rep, 1, qstate->prefetch_leeway,
3547
0
        iq->dp&&iq->dp->has_parent_side_NS, NULL,
3548
0
        qstate->query_flags, qstate->qstarttime,
3549
0
        qstate->is_valrec);
3550
    /* set the current request's qname to the new value. */
3551
0
    iq->qchase.qname = sname;
3552
0
    iq->qchase.qname_len = snamelen;
3553
0
    if(qstate->env->auth_zones) {
3554
      /* apply rpz qname triggers after cname */
3555
0
      struct dns_msg* forged_response =
3556
0
        rpz_callback_from_iterator_cname(qstate, iq);
3557
0
      int count = 0;
3558
0
      while(forged_response && reply_find_rrset_section_an(
3559
0
        forged_response->rep, iq->qchase.qname,
3560
0
        iq->qchase.qname_len, LDNS_RR_TYPE_CNAME,
3561
0
        iq->qchase.qclass) &&
3562
0
        iq->qchase.qtype != LDNS_RR_TYPE_CNAME &&
3563
0
        count++ < ie->max_query_restarts) {
3564
        /* another cname to follow */
3565
0
        if(!handle_cname_response(qstate, iq, forged_response,
3566
0
          &sname, &snamelen)) {
3567
0
          errinf(qstate, "malloc failure, CNAME info");
3568
0
          return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3569
0
        }
3570
0
        iq->qchase.qname = sname;
3571
0
        iq->qchase.qname_len = snamelen;
3572
0
        forged_response =
3573
0
          rpz_callback_from_iterator_cname(qstate, iq);
3574
0
      }
3575
0
      if(forged_response != NULL) {
3576
0
        qstate->ext_state[id] = module_finished;
3577
0
        qstate->return_rcode = LDNS_RCODE_NOERROR;
3578
0
        qstate->return_msg = forged_response;
3579
0
        iq->response = forged_response;
3580
0
        next_state(iq, FINISHED_STATE);
3581
0
        if(!iter_prepend(iq, qstate->return_msg, qstate->region)) {
3582
0
          log_err("rpz: after cname, prepend rrsets: out of memory");
3583
0
          return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
3584
0
        }
3585
0
        qstate->return_msg->qinfo = qstate->qinfo;
3586
0
        return 0;
3587
0
      }
3588
0
    }
3589
    /* Clear the query state, since this is a query restart. */
3590
0
    iq->deleg_msg = NULL;
3591
0
    iq->dp = NULL;
3592
0
    iq->dsns_point = NULL;
3593
0
    iq->auth_zone_response = 0;
3594
0
    iq->sent_count = 0;
3595
0
    iq->dp_target_count = 0;
3596
0
    iq->query_restart_count++;
3597
0
    if(qstate->env->cfg->qname_minimisation)
3598
0
      iq->minimisation_state = INIT_MINIMISE_STATE;
3599
3600
    /* stop current outstanding queries. 
3601
     * FIXME: should the outstanding queries be waited for and
3602
     * handled? Say by a subquery that inherits the outbound_entry.
3603
     */
3604
0
    outbound_list_clear(&iq->outlist);
3605
0
    iq->num_current_queries = 0;
3606
0
    fptr_ok(fptr_whitelist_modenv_detach_subs(
3607
0
      qstate->env->detach_subs));
3608
0
    (*qstate->env->detach_subs)(qstate);
3609
0
    iq->num_target_queries = 0;
3610
0
    if(qstate->reply)
3611
0
      sock_list_insert(&qstate->reply_origin,
3612
0
        &qstate->reply->remote_addr,
3613
0
        qstate->reply->remote_addrlen, qstate->region);
3614
0
    verbose(VERB_ALGO, "cleared outbound list for query restart");
3615
    /* go to INIT_REQUEST_STATE for new qname. */
3616
0
    return next_state(iq, INIT_REQUEST_STATE);
3617
0
  } else if(type == RESPONSE_TYPE_LAME) {
3618
    /* Cache the LAMEness. */
3619
0
    verbose(VERB_DETAIL, "query response was %sLAME",
3620
0
      dnsseclame?"DNSSEC ":"");
3621
0
    if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
3622
0
      log_err("mark lame: mismatch in qname and dpname");
3623
      /* throwaway this reply below */
3624
0
    } else if(qstate->reply) {
3625
      /* need addr for lameness cache, but we may have
3626
       * gotten this from cache, so test to be sure */
3627
0
      if(!infra_set_lame(qstate->env->infra_cache,
3628
0
        &qstate->reply->remote_addr,
3629
0
        qstate->reply->remote_addrlen,
3630
0
        iq->dp->name, iq->dp->namelen,
3631
0
        *qstate->env->now, dnsseclame, 0,
3632
0
        iq->qchase.qtype))
3633
0
        log_err("mark host lame: out of memory");
3634
0
    }
3635
0
  } else if(type == RESPONSE_TYPE_REC_LAME) {
3636
    /* Cache the LAMEness. */
3637
0
    verbose(VERB_DETAIL, "query response REC_LAME: "
3638
0
      "recursive but not authoritative server");
3639
0
    if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
3640
0
      log_err("mark rec_lame: mismatch in qname and dpname");
3641
      /* throwaway this reply below */
3642
0
    } else if(qstate->reply) {
3643
      /* need addr for lameness cache, but we may have
3644
       * gotten this from cache, so test to be sure */
3645
0
      verbose(VERB_DETAIL, "mark as REC_LAME");
3646
0
      if(!infra_set_lame(qstate->env->infra_cache, 
3647
0
        &qstate->reply->remote_addr,
3648
0
        qstate->reply->remote_addrlen,
3649
0
        iq->dp->name, iq->dp->namelen,
3650
0
        *qstate->env->now, 0, 1, iq->qchase.qtype))
3651
0
        log_err("mark host lame: out of memory");
3652
0
    } 
3653
0
  } else if(type == RESPONSE_TYPE_THROWAWAY) {
3654
    /* LAME and THROWAWAY responses are handled the same way. 
3655
     * In this case, the event is just sent directly back to 
3656
     * the QUERYTARGETS_STATE without resetting anything, 
3657
     * because, clearly, the next target must be tried. */
3658
0
    verbose(VERB_DETAIL, "query response was THROWAWAY");
3659
0
  } else {
3660
0
    log_warn("A query response came back with an unknown type: %d",
3661
0
      (int)type);
3662
0
  }
3663
3664
  /* LAME, THROWAWAY and "unknown" all end up here.
3665
   * Recycle to the QUERYTARGETS state to hopefully try a 
3666
   * different target. */
3667
0
  if (qstate->env->cfg->qname_minimisation &&
3668
0
    !qstate->env->cfg->qname_minimisation_strict)
3669
0
    iq->minimisation_state = DONOT_MINIMISE_STATE;
3670
0
  if(iq->auth_zone_response) {
3671
    /* can we fallback? */
3672
0
    iq->auth_zone_response = 0;
3673
0
    if(!auth_zones_can_fallback(qstate->env->auth_zones,
3674
0
      iq->dp->name, iq->dp->namelen, qstate->qinfo.qclass)) {
3675
0
      verbose(VERB_ALGO, "auth zone response bad, and no"
3676
0
        " fallback possible, servfail");
3677
0
      errinf_dname(qstate, "response is bad, no fallback, "
3678
0
        "for auth zone", iq->dp->name);
3679
0
      return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
3680
0
    }
3681
0
    verbose(VERB_ALGO, "auth zone response was bad, "
3682
0
      "fallback enabled");
3683
0
    iq->auth_zone_avoid = 1;
3684
0
    if(iq->dp->auth_dp) {
3685
      /* we are using a dp for the auth zone, with no
3686
       * nameservers, get one first */
3687
0
      iq->dp = NULL;
3688
0
      return next_state(iq, INIT_REQUEST_STATE);
3689
0
    }
3690
0
  }
3691
0
  return next_state(iq, QUERYTARGETS_STATE);
3692
0
}
3693
3694
/**
3695
 * Return priming query results to interested super querystates.
3696
 * 
3697
 * Sets the delegation point and delegation message (not nonRD queries).
3698
 * This is a callback from walk_supers.
3699
 *
3700
 * @param qstate: priming query state that finished.
3701
 * @param id: module id.
3702
 * @param forq: the qstate for which priming has been done.
3703
 */
3704
static void
3705
prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
3706
0
{
3707
0
  struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3708
0
  struct delegpt* dp = NULL;
3709
3710
0
  log_assert(qstate->is_priming || foriq->wait_priming_stub);
3711
0
  log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
3712
  /* Convert our response to a delegation point */
3713
0
  dp = delegpt_from_message(qstate->return_msg, forq->region);
3714
0
  if(!dp) {
3715
    /* if there is no convertible delegation point, then 
3716
     * the ANSWER type was (presumably) a negative answer. */
3717
0
    verbose(VERB_ALGO, "prime response was not a positive "
3718
0
      "ANSWER; failing");
3719
0
    foriq->dp = NULL;
3720
0
    foriq->state = QUERYTARGETS_STATE;
3721
0
    return;
3722
0
  }
3723
3724
0
  log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
3725
0
  delegpt_log(VERB_ALGO, dp);
3726
0
  foriq->dp = dp;
3727
0
  foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
3728
0
  if(!foriq->deleg_msg) {
3729
0
    log_err("copy prime response: out of memory");
3730
0
    foriq->dp = NULL;
3731
0
    foriq->state = QUERYTARGETS_STATE;
3732
0
    return;
3733
0
  }
3734
3735
  /* root priming responses go to init stage 2, priming stub 
3736
   * responses to to stage 3. */
3737
0
  if(foriq->wait_priming_stub) {
3738
0
    foriq->state = INIT_REQUEST_3_STATE;
3739
0
    foriq->wait_priming_stub = 0;
3740
0
  } else foriq->state = INIT_REQUEST_2_STATE;
3741
  /* because we are finished, the parent will be reactivated */
3742
0
}
3743
3744
/** 
3745
 * This handles the response to a priming query. This is used to handle both
3746
 * root and stub priming responses. This is basically the equivalent of the
3747
 * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
3748
 * REFERRALs as ANSWERS. It will also update and reactivate the originating
3749
 * event.
3750
 *
3751
 * @param qstate: query state.
3752
 * @param id: module id.
3753
 * @return true if the event needs more immediate processing, false if not.
3754
 *         This state always returns false.
3755
 */
3756
static int
3757
processPrimeResponse(struct module_qstate* qstate, int id)
3758
0
{
3759
0
  struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3760
0
  enum response_type type;
3761
0
  iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
3762
0
  type = response_type_from_server(
3763
0
    (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd), 
3764
0
    iq->response, &iq->qchase, iq->dp, NULL);
3765
0
  if(type == RESPONSE_TYPE_ANSWER) {
3766
0
    qstate->return_rcode = LDNS_RCODE_NOERROR;
3767
0
    qstate->return_msg = iq->response;
3768
0
  } else {
3769
0
    errinf(qstate, "prime response did not get an answer");
3770
0
    errinf_dname(qstate, "for", qstate->qinfo.qname);
3771
0
    qstate->return_rcode = LDNS_RCODE_SERVFAIL;
3772
0
    qstate->return_msg = NULL;
3773
0
  }
3774
3775
  /* validate the root or stub after priming (if enabled).
3776
   * This is the same query as the prime query, but with validation.
3777
   * Now that we are primed, the additional queries that validation
3778
   * may need can be resolved. */
3779
0
  if(qstate->env->cfg->harden_referral_path) {
3780
0
    struct module_qstate* subq = NULL;
3781
0
    log_nametypeclass(VERB_ALGO, "schedule prime validation", 
3782
0
      qstate->qinfo.qname, qstate->qinfo.qtype,
3783
0
      qstate->qinfo.qclass);
3784
0
    if(!generate_sub_request(qstate->qinfo.qname, 
3785
0
      qstate->qinfo.qname_len, qstate->qinfo.qtype,
3786
0
      qstate->qinfo.qclass, qstate, id, iq,
3787
0
      INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1, 0)) {
3788
0
      verbose(VERB_ALGO, "could not generate prime check");
3789
0
    }
3790
0
    generate_a_aaaa_check(qstate, iq, id);
3791
0
  }
3792
3793
  /* This event is finished. */
3794
0
  qstate->ext_state[id] = module_finished;
3795
0
  return 0;
3796
0
}
3797
3798
/** 
3799
 * Do final processing on responses to target queries. Events reach this
3800
 * state after the iterative resolution algorithm terminates. This state is
3801
 * responsible for reactivating the original event, and housekeeping related
3802
 * to received target responses (caching, updating the current delegation
3803
 * point, etc).
3804
 * Callback from walk_supers for every super state that is interested in 
3805
 * the results from this query.
3806
 *
3807
 * @param qstate: query state.
3808
 * @param id: module id.
3809
 * @param forq: super query state.
3810
 */
3811
static void
3812
processTargetResponse(struct module_qstate* qstate, int id,
3813
  struct module_qstate* forq)
3814
0
{
3815
0
  struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
3816
0
  struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
3817
0
  struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3818
0
  struct ub_packed_rrset_key* rrset;
3819
0
  struct delegpt_ns* dpns;
3820
0
  log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
3821
3822
0
  foriq->state = QUERYTARGETS_STATE;
3823
0
  log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
3824
0
  log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
3825
3826
  /* Tell the originating event that this target query has finished
3827
   * (regardless if it succeeded or not). */
3828
0
  foriq->num_target_queries--;
3829
3830
  /* check to see if parent event is still interested (in orig name).  */
3831
0
  if(!foriq->dp) {
3832
0
    verbose(VERB_ALGO, "subq: parent not interested, was reset");
3833
0
    return; /* not interested anymore */
3834
0
  }
3835
0
  dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
3836
0
      qstate->qinfo.qname_len);
3837
0
  if(!dpns) {
3838
    /* If not interested, just stop processing this event */
3839
0
    verbose(VERB_ALGO, "subq: parent not interested anymore");
3840
    /* could be because parent was jostled out of the cache,
3841
       and a new identical query arrived, that does not want it*/
3842
0
    return;
3843
0
  }
3844
3845
  /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
3846
0
  if(iq->pside_glue) {
3847
    /* if the pside_glue is NULL, then it could not be found,
3848
     * the done_pside is already set when created and a cache
3849
     * entry created in processFinished so nothing to do here */
3850
0
    log_rrset_key(VERB_ALGO, "add parentside glue to dp", 
3851
0
      iq->pside_glue);
3852
0
    if(!delegpt_add_rrset(foriq->dp, forq->region, 
3853
0
      iq->pside_glue, 1, NULL))
3854
0
      log_err("out of memory adding pside glue");
3855
0
  }
3856
3857
  /* This response is relevant to the current query, so we
3858
   * add (attempt to add, anyway) this target(s) and reactivate
3859
   * the original event.
3860
   * NOTE: we could only look for the AnswerRRset if the
3861
   * response type was ANSWER. */
3862
0
  rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
3863
0
  if(rrset) {
3864
0
    int additions = 0;
3865
    /* if CNAMEs have been followed - add new NS to delegpt. */
3866
    /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
3867
0
    if(!delegpt_find_ns(foriq->dp, rrset->rk.dname,
3868
0
      rrset->rk.dname_len)) {
3869
      /* if dpns->lame then set newcname ns lame too */
3870
0
      if(!delegpt_add_ns(foriq->dp, forq->region,
3871
0
        rrset->rk.dname, dpns->lame, dpns->tls_auth_name,
3872
0
        dpns->port))
3873
0
        log_err("out of memory adding cnamed-ns");
3874
0
    }
3875
    /* if dpns->lame then set the address(es) lame too */
3876
0
    if(!delegpt_add_rrset(foriq->dp, forq->region, rrset, 
3877
0
      dpns->lame, &additions))
3878
0
      log_err("out of memory adding targets");
3879
0
    if(!additions) {
3880
      /* no new addresses, increase the nxns counter, like
3881
       * this could be a list of wildcards with no new
3882
       * addresses */
3883
0
      target_count_increase_nx(foriq, 1);
3884
0
    }
3885
0
    verbose(VERB_ALGO, "added target response");
3886
0
    delegpt_log(VERB_ALGO, foriq->dp);
3887
0
  } else {
3888
0
    verbose(VERB_ALGO, "iterator TargetResponse failed");
3889
0
    delegpt_mark_neg(dpns, qstate->qinfo.qtype);
3890
0
    if((dpns->got4 == 2 || (!ie->supports_ipv4 && !ie->nat64.use_nat64)) &&
3891
0
      (dpns->got6 == 2 || !ie->supports_ipv6)) {
3892
0
      dpns->resolved = 1; /* fail the target */
3893
      /* do not count cached answers */
3894
0
      if(qstate->reply_origin && qstate->reply_origin->len != 0) {
3895
0
        target_count_increase_nx(foriq, 1);
3896
0
      }
3897
0
    }
3898
0
  }
3899
0
}
3900
3901
/**
3902
 * Process response for DS NS Find queries, that attempt to find the delegation
3903
 * point where we ask the DS query from.
3904
 *
3905
 * @param qstate: query state.
3906
 * @param id: module id.
3907
 * @param forq: super query state.
3908
 */
3909
static void
3910
processDSNSResponse(struct module_qstate* qstate, int id,
3911
  struct module_qstate* forq)
3912
0
{
3913
0
  struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3914
3915
  /* if the finished (iq->response) query has no NS set: continue
3916
   * up to look for the right dp; nothing to change, do DPNSstate */
3917
0
  if(qstate->return_rcode != LDNS_RCODE_NOERROR)
3918
0
    return; /* seek further */
3919
  /* find the NS RRset (without allowing CNAMEs) */
3920
0
  if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
3921
0
    qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
3922
0
    qstate->qinfo.qclass)){
3923
0
    return; /* seek further */
3924
0
  }
3925
3926
  /* else, store as DP and continue at querytargets */
3927
0
  foriq->state = QUERYTARGETS_STATE;
3928
0
  foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
3929
0
  if(!foriq->dp) {
3930
0
    log_err("out of memory in dsns dp alloc");
3931
0
    errinf(qstate, "malloc failure, in DS search");
3932
0
    return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
3933
0
  }
3934
  /* success, go query the querytargets in the new dp (and go down) */
3935
0
}
3936
3937
/**
3938
 * Process response for qclass=ANY queries for a particular class.
3939
 * Append to result or error-exit.
3940
 *
3941
 * @param qstate: query state.
3942
 * @param id: module id.
3943
 * @param forq: super query state.
3944
 */
3945
static void
3946
processClassResponse(struct module_qstate* qstate, int id,
3947
  struct module_qstate* forq)
3948
0
{
3949
0
  struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
3950
0
  struct dns_msg* from = qstate->return_msg;
3951
0
  log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
3952
0
  log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
3953
0
  if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
3954
    /* cause servfail for qclass ANY query */
3955
0
    foriq->response = NULL;
3956
0
    foriq->state = FINISHED_STATE;
3957
0
    return;
3958
0
  }
3959
  /* append result */
3960
0
  if(!foriq->response) {
3961
    /* allocate the response: copy RCODE, sec_state */
3962
0
    foriq->response = dns_copy_msg(from, forq->region);
3963
0
    if(!foriq->response) {
3964
0
      log_err("malloc failed for qclass ANY response"); 
3965
0
      foriq->state = FINISHED_STATE;
3966
0
      return;
3967
0
    }
3968
0
    foriq->response->qinfo.qclass = forq->qinfo.qclass;
3969
    /* qclass ANY does not receive the AA flag on replies */
3970
0
    foriq->response->rep->authoritative = 0; 
3971
0
  } else {
3972
0
    struct dns_msg* to = foriq->response;
3973
    /* add _from_ this response _to_ existing collection */
3974
    /* if there are records, copy RCODE */
3975
    /* lower sec_state if this message is lower */
3976
0
    if(from->rep->rrset_count != 0) {
3977
0
      size_t n = from->rep->rrset_count+to->rep->rrset_count;
3978
0
      struct ub_packed_rrset_key** dest, **d;
3979
      /* copy appropriate rcode */
3980
0
      to->rep->flags = from->rep->flags;
3981
      /* copy rrsets */
3982
0
      if(from->rep->rrset_count > RR_COUNT_MAX ||
3983
0
        to->rep->rrset_count > RR_COUNT_MAX) {
3984
0
        log_err("malloc failed (too many rrsets) in collect ANY"); 
3985
0
        foriq->state = FINISHED_STATE;
3986
0
        return; /* integer overflow protection */
3987
0
      }
3988
0
      dest = regional_alloc(forq->region, sizeof(dest[0])*n);
3989
0
      if(!dest) {
3990
0
        log_err("malloc failed in collect ANY"); 
3991
0
        foriq->state = FINISHED_STATE;
3992
0
        return;
3993
0
      }
3994
0
      d = dest;
3995
      /* copy AN */
3996
0
      memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
3997
0
        * sizeof(dest[0]));
3998
0
      dest += to->rep->an_numrrsets;
3999
0
      memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
4000
0
        * sizeof(dest[0]));
4001
0
      dest += from->rep->an_numrrsets;
4002
      /* copy NS */
4003
0
      memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
4004
0
        to->rep->ns_numrrsets * sizeof(dest[0]));
4005
0
      dest += to->rep->ns_numrrsets;
4006
0
      memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
4007
0
        from->rep->ns_numrrsets * sizeof(dest[0]));
4008
0
      dest += from->rep->ns_numrrsets;
4009
      /* copy AR */
4010
0
      memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
4011
0
        to->rep->ns_numrrsets,
4012
0
        to->rep->ar_numrrsets * sizeof(dest[0]));
4013
0
      dest += to->rep->ar_numrrsets;
4014
0
      memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
4015
0
        from->rep->ns_numrrsets,
4016
0
        from->rep->ar_numrrsets * sizeof(dest[0]));
4017
      /* update counts */
4018
0
      to->rep->rrsets = d;
4019
0
      to->rep->an_numrrsets += from->rep->an_numrrsets;
4020
0
      to->rep->ns_numrrsets += from->rep->ns_numrrsets;
4021
0
      to->rep->ar_numrrsets += from->rep->ar_numrrsets;
4022
0
      to->rep->rrset_count = n;
4023
0
    }
4024
0
    if(from->rep->security < to->rep->security) /* lowest sec */
4025
0
      to->rep->security = from->rep->security;
4026
0
    if(from->rep->qdcount != 0) /* insert qd if appropriate */
4027
0
      to->rep->qdcount = from->rep->qdcount;
4028
0
    if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
4029
0
      to->rep->ttl = from->rep->ttl;
4030
0
    if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
4031
0
      to->rep->prefetch_ttl = from->rep->prefetch_ttl;
4032
0
    if(from->rep->serve_expired_ttl < to->rep->serve_expired_ttl)
4033
0
      to->rep->serve_expired_ttl = from->rep->serve_expired_ttl;
4034
0
    if(from->rep->serve_expired_norec_ttl < to->rep->serve_expired_norec_ttl)
4035
0
      to->rep->serve_expired_norec_ttl = from->rep->serve_expired_norec_ttl;
4036
0
  }
4037
  /* are we done? */
4038
0
  foriq->num_current_queries --;
4039
0
  if(foriq->num_current_queries == 0)
4040
0
    foriq->state = FINISHED_STATE;
4041
0
}
4042
  
4043
/** 
4044
 * Collect class ANY responses and make them into one response.  This
4045
 * state is started and it creates queries for all classes (that have
4046
 * root hints).  The answers are then collected.
4047
 *
4048
 * @param qstate: query state.
4049
 * @param id: module id.
4050
 * @return true if the event needs more immediate processing, false if not.
4051
 */
4052
static int
4053
processCollectClass(struct module_qstate* qstate, int id)
4054
0
{
4055
0
  struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
4056
0
  struct module_qstate* subq;
4057
  /* If qchase.qclass == 0 then send out queries for all classes.
4058
   * Otherwise, do nothing (wait for all answers to arrive and the
4059
   * processClassResponse to put them together, and that moves us
4060
   * towards the Finished state when done. */
4061
0
  if(iq->qchase.qclass == 0) {
4062
0
    uint16_t c = 0;
4063
0
    iq->qchase.qclass = LDNS_RR_CLASS_ANY;
4064
0
    while(iter_get_next_root(qstate->env->hints,
4065
0
      qstate->env->fwds, &c)) {
4066
      /* generate query for this class */
4067
0
      log_nametypeclass(VERB_ALGO, "spawn collect query",
4068
0
        qstate->qinfo.qname, qstate->qinfo.qtype, c);
4069
0
      if(!generate_sub_request(qstate->qinfo.qname,
4070
0
        qstate->qinfo.qname_len, qstate->qinfo.qtype,
4071
0
        c, qstate, id, iq, INIT_REQUEST_STATE,
4072
0
        FINISHED_STATE, &subq, 
4073
0
        (int)!(qstate->query_flags&BIT_CD), 0)) {
4074
0
        errinf(qstate, "could not generate class ANY"
4075
0
          " lookup query");
4076
0
        return error_response(qstate, id, 
4077
0
          LDNS_RCODE_SERVFAIL);
4078
0
      }
4079
      /* ignore subq, no special init required */
4080
0
      iq->num_current_queries ++;
4081
0
      if(c == 0xffff)
4082
0
        break;
4083
0
      else c++;
4084
0
    }
4085
    /* if no roots are configured at all, return */
4086
0
    if(iq->num_current_queries == 0) {
4087
0
      verbose(VERB_ALGO, "No root hints or fwds, giving up "
4088
0
        "on qclass ANY");
4089
0
      return error_response_cache(qstate, id, LDNS_RCODE_REFUSED);
4090
0
    }
4091
    /* return false, wait for queries to return */
4092
0
  }
4093
  /* if woke up here because of an answer, wait for more answers */
4094
0
  return 0;
4095
0
}
4096
4097
/** 
4098
 * This handles the final state for first-tier responses (i.e., responses to
4099
 * externally generated queries).
4100
 *
4101
 * @param qstate: query state.
4102
 * @param iq: iterator query state.
4103
 * @param id: module id.
4104
 * @return true if the event needs more processing, false if not. Since this
4105
 *         is the final state for an event, it always returns false.
4106
 */
4107
static int
4108
processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
4109
  int id)
4110
0
{
4111
0
  log_query_info(VERB_QUERY, "finishing processing for", 
4112
0
    &qstate->qinfo);
4113
4114
  /* store negative cache element for parent side glue. */
4115
0
  if(!qstate->no_cache_store && iq->query_for_pside_glue
4116
0
    && !iq->pside_glue)
4117
0
      iter_store_parentside_neg(qstate->env, &qstate->qinfo,
4118
0
        iq->deleg_msg?iq->deleg_msg->rep:
4119
0
        (iq->response?iq->response->rep:NULL));
4120
0
  if(!iq->response) {
4121
0
    verbose(VERB_ALGO, "No response is set, servfail");
4122
0
    errinf(qstate, "(no response found at query finish)");
4123
0
    return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4124
0
  }
4125
4126
  /* Make sure that the RA flag is set (since the presence of 
4127
   * this module means that recursion is available) */
4128
0
  iq->response->rep->flags |= BIT_RA;
4129
4130
  /* Clear the AA flag */
4131
  /* FIXME: does this action go here or in some other module? */
4132
0
  iq->response->rep->flags &= ~BIT_AA;
4133
4134
  /* make sure QR flag is on */
4135
0
  iq->response->rep->flags |= BIT_QR;
4136
4137
  /* explicitly set the EDE string to NULL */
4138
0
  iq->response->rep->reason_bogus_str = NULL;
4139
0
  if((qstate->env->cfg->val_log_level >= 2 ||
4140
0
    qstate->env->cfg->log_servfail) && qstate->errinf &&
4141
0
    !qstate->env->cfg->val_log_squelch) {
4142
0
    char* err_str = errinf_to_str_misc(qstate);
4143
0
    if(err_str) {
4144
0
      verbose(VERB_ALGO, "iterator EDE: %s", err_str);
4145
0
      iq->response->rep->reason_bogus_str = err_str;
4146
0
    }
4147
0
  }
4148
4149
  /* we have finished processing this query */
4150
0
  qstate->ext_state[id] = module_finished;
4151
4152
  /* TODO:  we are using a private TTL, trim the response. */
4153
  /* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
4154
4155
  /* prepend any items we have accumulated */
4156
0
  if(iq->an_prepend_list || iq->ns_prepend_list) {
4157
0
    if(!iter_prepend(iq, iq->response, qstate->region)) {
4158
0
      log_err("prepend rrsets: out of memory");
4159
0
      return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4160
0
    }
4161
    /* reset the query name back */
4162
0
    iq->response->qinfo = qstate->qinfo;
4163
    /* the security state depends on the combination */
4164
0
    iq->response->rep->security = sec_status_unchecked;
4165
    /* store message with the finished prepended items,
4166
     * but only if we did recursion. The nonrecursion referral
4167
     * from cache does not need to be stored in the msg cache. */
4168
0
    if(!qstate->no_cache_store && (qstate->query_flags&BIT_RD)) {
4169
0
      iter_dns_store(qstate->env, &qstate->qinfo, 
4170
0
        iq->response->rep, 0, qstate->prefetch_leeway,
4171
0
        iq->dp&&iq->dp->has_parent_side_NS,
4172
0
        qstate->region, qstate->query_flags,
4173
0
        qstate->qstarttime, qstate->is_valrec);
4174
0
    }
4175
0
  }
4176
0
  qstate->return_rcode = LDNS_RCODE_NOERROR;
4177
0
  qstate->return_msg = iq->response;
4178
0
  return 0;
4179
0
}
4180
4181
/*
4182
 * Return priming query results to interested super querystates.
4183
 * 
4184
 * Sets the delegation point and delegation message (not nonRD queries).
4185
 * This is a callback from walk_supers.
4186
 *
4187
 * @param qstate: query state that finished.
4188
 * @param id: module id.
4189
 * @param super: the qstate to inform.
4190
 */
4191
void
4192
iter_inform_super(struct module_qstate* qstate, int id, 
4193
  struct module_qstate* super)
4194
0
{
4195
0
  if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
4196
0
    processClassResponse(qstate, id, super);
4197
0
  else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
4198
0
    super->minfo[id])->state == DSNS_FIND_STATE)
4199
0
    processDSNSResponse(qstate, id, super);
4200
0
  else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
4201
0
    error_supers(qstate, id, super);
4202
0
  else if(qstate->is_priming)
4203
0
    prime_supers(qstate, id, super);
4204
0
  else  processTargetResponse(qstate, id, super);
4205
0
}
4206
4207
/**
4208
 * Handle iterator state.
4209
 * Handle events. This is the real processing loop for events, responsible
4210
 * for moving events through the various states. If a processing method
4211
 * returns true, then it will be advanced to the next state. If false, then
4212
 * processing will stop.
4213
 *
4214
 * @param qstate: query state.
4215
 * @param ie: iterator shared global environment.
4216
 * @param iq: iterator query state.
4217
 * @param id: module id.
4218
 */
4219
static void
4220
iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
4221
  struct iter_env* ie, int id)
4222
0
{
4223
0
  int cont = 1;
4224
0
  while(cont) {
4225
0
    verbose(VERB_ALGO, "iter_handle processing q with state %s",
4226
0
      iter_state_to_string(iq->state));
4227
0
    switch(iq->state) {
4228
0
      case INIT_REQUEST_STATE:
4229
0
        cont = processInitRequest(qstate, iq, ie, id);
4230
0
        break;
4231
0
      case INIT_REQUEST_2_STATE:
4232
0
        cont = processInitRequest2(qstate, iq, id);
4233
0
        break;
4234
0
      case INIT_REQUEST_3_STATE:
4235
0
        cont = processInitRequest3(qstate, iq, id);
4236
0
        break;
4237
0
      case QUERYTARGETS_STATE:
4238
0
        cont = processQueryTargets(qstate, iq, ie, id);
4239
0
        break;
4240
0
      case QUERY_RESP_STATE:
4241
0
        cont = processQueryResponse(qstate, iq, ie, id);
4242
0
        break;
4243
0
      case PRIME_RESP_STATE:
4244
0
        cont = processPrimeResponse(qstate, id);
4245
0
        break;
4246
0
      case COLLECT_CLASS_STATE:
4247
0
        cont = processCollectClass(qstate, id);
4248
0
        break;
4249
0
      case DSNS_FIND_STATE:
4250
0
        cont = processDSNSFind(qstate, iq, id);
4251
0
        break;
4252
0
      case FINISHED_STATE:
4253
0
        cont = processFinished(qstate, iq, id);
4254
0
        break;
4255
0
      default:
4256
0
        log_warn("iterator: invalid state: %d",
4257
0
          iq->state);
4258
0
        cont = 0;
4259
0
        break;
4260
0
    }
4261
0
  }
4262
0
}
4263
4264
/** 
4265
 * This is the primary entry point for processing request events. Note that
4266
 * this method should only be used by external modules.
4267
 * @param qstate: query state.
4268
 * @param ie: iterator shared global environment.
4269
 * @param iq: iterator query state.
4270
 * @param id: module id.
4271
 */
4272
static void
4273
process_request(struct module_qstate* qstate, struct iter_qstate* iq,
4274
  struct iter_env* ie, int id)
4275
0
{
4276
  /* external requests start in the INIT state, and finish using the
4277
   * FINISHED state. */
4278
0
  iq->state = INIT_REQUEST_STATE;
4279
0
  iq->final_state = FINISHED_STATE;
4280
0
  verbose(VERB_ALGO, "process_request: new external request event");
4281
0
  iter_handle(qstate, iq, ie, id);
4282
0
}
4283
4284
/** process authoritative server reply */
4285
static void
4286
process_response(struct module_qstate* qstate, struct iter_qstate* iq, 
4287
  struct iter_env* ie, int id, struct outbound_entry* outbound,
4288
  enum module_ev event)
4289
0
{
4290
0
  struct msg_parse* prs;
4291
0
  struct edns_data edns;
4292
0
  sldns_buffer* pkt;
4293
4294
0
  verbose(VERB_ALGO, "process_response: new external response event");
4295
0
  iq->response = NULL;
4296
0
  iq->state = QUERY_RESP_STATE;
4297
0
  if(event == module_event_noreply || event == module_event_error) {
4298
0
    if(event == module_event_noreply && iq->timeout_count >= 3 &&
4299
0
      qstate->env->cfg->use_caps_bits_for_id &&
4300
0
      !iq->caps_fallback && !is_caps_whitelisted(ie, iq)) {
4301
      /* start fallback */
4302
0
      iq->caps_fallback = 1;
4303
0
      iq->caps_server = 0;
4304
0
      iq->caps_reply = NULL;
4305
0
      iq->caps_response = NULL;
4306
0
      iq->caps_minimisation_state = DONOT_MINIMISE_STATE;
4307
0
      iq->state = QUERYTARGETS_STATE;
4308
0
      iq->num_current_queries--;
4309
      /* need fresh attempts for the 0x20 fallback, if
4310
       * that was the cause for the failure */
4311
0
      iter_dec_attempts(iq->dp, 3, ie->outbound_msg_retry);
4312
0
      verbose(VERB_DETAIL, "Capsforid: timeouts, starting fallback");
4313
0
      goto handle_it;
4314
0
    }
4315
0
    goto handle_it;
4316
0
  }
4317
0
  if( (event != module_event_reply && event != module_event_capsfail)
4318
0
    || !qstate->reply) {
4319
0
    log_err("Bad event combined with response");
4320
0
    outbound_list_remove(&iq->outlist, outbound);
4321
0
    errinf(qstate, "module iterator received wrong internal event with a response message");
4322
0
    (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4323
0
    return;
4324
0
  }
4325
4326
  /* parse message */
4327
0
  fill_fail_addr(iq, &qstate->reply->remote_addr,
4328
0
    qstate->reply->remote_addrlen);
4329
0
  prs = (struct msg_parse*)regional_alloc(qstate->env->scratch, 
4330
0
    sizeof(struct msg_parse));
4331
0
  if(!prs) {
4332
0
    log_err("out of memory on incoming message");
4333
    /* like packet got dropped */
4334
0
    goto handle_it;
4335
0
  }
4336
0
  memset(prs, 0, sizeof(*prs));
4337
0
  memset(&edns, 0, sizeof(edns));
4338
0
  pkt = qstate->reply->c->buffer;
4339
0
  sldns_buffer_set_position(pkt, 0);
4340
0
  if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
4341
0
    verbose(VERB_ALGO, "parse error on reply packet");
4342
0
    iq->parse_failures++;
4343
0
    goto handle_it;
4344
0
  }
4345
  /* edns is not examined, but removed from message to help cache */
4346
0
  if(parse_extract_edns_from_response_msg(prs, &edns, qstate->env->scratch) !=
4347
0
    LDNS_RCODE_NOERROR) {
4348
0
    iq->parse_failures++;
4349
0
    goto handle_it;
4350
0
  }
4351
4352
  /* Copy the edns options we may got from the back end */
4353
0
  qstate->edns_opts_back_in = NULL;
4354
0
  if(edns.opt_list_in) {
4355
0
    qstate->edns_opts_back_in = edns_opt_copy_region(edns.opt_list_in,
4356
0
      qstate->region);
4357
0
    if(!qstate->edns_opts_back_in) {
4358
0
      log_err("out of memory on incoming message");
4359
      /* like packet got dropped */
4360
0
      goto handle_it;
4361
0
    }
4362
0
  }
4363
0
  if(!inplace_cb_edns_back_parsed_call(qstate->env, qstate)) {
4364
0
    log_err("unable to call edns_back_parsed callback");
4365
0
    goto handle_it;
4366
0
  }
4367
4368
  /* remove CD-bit, we asked for in case we handle validation ourself */
4369
0
  prs->flags &= ~BIT_CD;
4370
4371
  /* normalize and sanitize: easy to delete items from linked lists */
4372
0
  if(!scrub_message(pkt, prs, &iq->qinfo_out, iq->dp->name, 
4373
0
    qstate->env->scratch, qstate->env, qstate, ie)) {
4374
    /* if 0x20 enabled, start fallback, but we have no message */
4375
0
    if(event == module_event_capsfail && !iq->caps_fallback) {
4376
0
      iq->caps_fallback = 1;
4377
0
      iq->caps_server = 0;
4378
0
      iq->caps_reply = NULL;
4379
0
      iq->caps_response = NULL;
4380
0
      iq->caps_minimisation_state = DONOT_MINIMISE_STATE;
4381
0
      iq->state = QUERYTARGETS_STATE;
4382
0
      iq->num_current_queries--;
4383
0
      verbose(VERB_DETAIL, "Capsforid: scrub failed, starting fallback with no response");
4384
0
    }
4385
0
    iq->scrub_failures++;
4386
0
    goto handle_it;
4387
0
  }
4388
4389
  /* allocate response dns_msg in region */
4390
0
  iq->response = dns_alloc_msg(pkt, prs, qstate->region);
4391
0
  if(!iq->response)
4392
0
    goto handle_it;
4393
0
  log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
4394
0
  log_name_addr(VERB_DETAIL, "reply from", iq->dp->name,
4395
0
    &qstate->reply->remote_addr, qstate->reply->remote_addrlen);
4396
0
  if(verbosity >= VERB_ALGO)
4397
0
    log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo, 
4398
0
      iq->response->rep);
4399
4400
0
  if(qstate->env->cfg->aggressive_nsec) {
4401
0
    limit_nsec_ttl(iq->response);
4402
0
  }
4403
0
  if(event == module_event_capsfail || iq->caps_fallback) {
4404
0
    if(qstate->env->cfg->qname_minimisation &&
4405
0
      iq->minimisation_state != DONOT_MINIMISE_STATE) {
4406
      /* Skip QNAME minimisation for next query, since that
4407
       * one has to match the current query. */
4408
0
      iq->minimisation_state = SKIP_MINIMISE_STATE;
4409
0
    }
4410
    /* for fallback we care about main answer, not additionals */
4411
    /* removing that makes comparison more likely to succeed */
4412
0
    caps_strip_reply(iq->response->rep);
4413
4414
0
    if(iq->caps_fallback &&
4415
0
      iq->caps_minimisation_state != iq->minimisation_state) {
4416
      /* QNAME minimisation state has changed, restart caps
4417
       * fallback. */
4418
0
      iq->caps_fallback = 0;
4419
0
    }
4420
4421
0
    if(!iq->caps_fallback) {
4422
      /* start fallback */
4423
0
      iq->caps_fallback = 1;
4424
0
      iq->caps_server = 0;
4425
0
      iq->caps_reply = iq->response->rep;
4426
0
      iq->caps_response = iq->response;
4427
0
      iq->caps_minimisation_state = iq->minimisation_state;
4428
0
      iq->state = QUERYTARGETS_STATE;
4429
0
      iq->num_current_queries--;
4430
0
      verbose(VERB_DETAIL, "Capsforid: starting fallback");
4431
0
      goto handle_it;
4432
0
    } else {
4433
      /* check if reply is the same, otherwise, fail */
4434
0
      if(!iq->caps_reply) {
4435
0
        iq->caps_reply = iq->response->rep;
4436
0
        iq->caps_response = iq->response;
4437
0
        iq->caps_server = -1; /*become zero at ++,
4438
        so that we start the full set of trials */
4439
0
      } else if(caps_failed_rcode(iq->caps_reply) &&
4440
0
        !caps_failed_rcode(iq->response->rep)) {
4441
        /* prefer to upgrade to non-SERVFAIL */
4442
0
        iq->caps_reply = iq->response->rep;
4443
0
        iq->caps_response = iq->response;
4444
0
      } else if(!caps_failed_rcode(iq->caps_reply) &&
4445
0
        caps_failed_rcode(iq->response->rep)) {
4446
        /* if we have non-SERVFAIL as answer then 
4447
         * we can ignore SERVFAILs for the equality
4448
         * comparison */
4449
        /* no instructions here, skip other else */
4450
0
      } else if(caps_failed_rcode(iq->caps_reply) &&
4451
0
        caps_failed_rcode(iq->response->rep)) {
4452
        /* failure is same as other failure in fallbk*/
4453
        /* no instructions here, skip other else */
4454
0
      } else if(!reply_equal(iq->response->rep, iq->caps_reply,
4455
0
        qstate->env->scratch)) {
4456
0
        verbose(VERB_DETAIL, "Capsforid fallback: "
4457
0
          "getting different replies, failed");
4458
0
        outbound_list_remove(&iq->outlist, outbound);
4459
0
        errinf(qstate, "0x20 failed, then got different replies in fallback");
4460
0
        (void)error_response_cache(qstate, id,
4461
0
          LDNS_RCODE_SERVFAIL);
4462
0
        return;
4463
0
      }
4464
      /* continue the fallback procedure at next server */
4465
0
      iq->caps_server++;
4466
0
      iq->state = QUERYTARGETS_STATE;
4467
0
      iq->num_current_queries--;
4468
0
      verbose(VERB_DETAIL, "Capsforid: reply is equal. "
4469
0
        "go to next fallback");
4470
0
      goto handle_it;
4471
0
    }
4472
0
  }
4473
0
  iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
4474
4475
0
handle_it:
4476
0
  outbound_list_remove(&iq->outlist, outbound);
4477
0
  iter_handle(qstate, iq, ie, id);
4478
0
}
4479
4480
void 
4481
iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
4482
  struct outbound_entry* outbound)
4483
0
{
4484
0
  struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
4485
0
  struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
4486
0
  verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s", 
4487
0
    id, strextstate(qstate->ext_state[id]), strmodulevent(event));
4488
0
  if(iq) log_query_info(VERB_QUERY, "iterator operate: query", 
4489
0
    &qstate->qinfo);
4490
0
  if(iq && qstate->qinfo.qname != iq->qchase.qname)
4491
0
    log_query_info(VERB_QUERY, "iterator operate: chased to", 
4492
0
      &iq->qchase);
4493
4494
  /* perform iterator state machine */
4495
0
  if((event == module_event_new || event == module_event_pass) && 
4496
0
    iq == NULL) {
4497
0
    if(!iter_new(qstate, id)) {
4498
0
      errinf(qstate, "malloc failure, new iterator module allocation");
4499
0
      (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4500
0
      return;
4501
0
    }
4502
0
    iq = (struct iter_qstate*)qstate->minfo[id];
4503
0
    process_request(qstate, iq, ie, id);
4504
0
    return;
4505
0
  }
4506
0
  if(iq && event == module_event_pass) {
4507
0
    iter_handle(qstate, iq, ie, id);
4508
0
    return;
4509
0
  }
4510
0
  if(iq && outbound) {
4511
0
    process_response(qstate, iq, ie, id, outbound, event);
4512
0
    return;
4513
0
  }
4514
0
  if(event == module_event_error) {
4515
0
    verbose(VERB_ALGO, "got called with event error, giving up");
4516
0
    errinf(qstate, "iterator module got the error event");
4517
0
    (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4518
0
    return;
4519
0
  }
4520
4521
0
  log_err("bad event for iterator");
4522
0
  errinf(qstate, "iterator module received wrong event");
4523
0
  (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
4524
0
}
4525
4526
void 
4527
iter_clear(struct module_qstate* qstate, int id)
4528
0
{
4529
0
  struct iter_qstate* iq;
4530
0
  if(!qstate)
4531
0
    return;
4532
0
  iq = (struct iter_qstate*)qstate->minfo[id];
4533
0
  if(iq) {
4534
0
    outbound_list_clear(&iq->outlist);
4535
0
    if(iq->target_count && --iq->target_count[TARGET_COUNT_REF] == 0) {
4536
0
      free(iq->target_count);
4537
0
      if(*iq->nxns_dp) free(*iq->nxns_dp);
4538
0
      free(iq->nxns_dp);
4539
0
    }
4540
0
    iq->num_current_queries = 0;
4541
0
  }
4542
0
  qstate->minfo[id] = NULL;
4543
0
}
4544
4545
size_t 
4546
iter_get_mem(struct module_env* env, int id)
4547
0
{
4548
0
  struct iter_env* ie = (struct iter_env*)env->modinfo[id];
4549
0
  if(!ie)
4550
0
    return 0;
4551
0
  return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
4552
0
    + donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
4553
0
}
4554
4555
/**
4556
 * The iterator function block 
4557
 */
4558
static struct module_func_block iter_block = {
4559
  "iterator",
4560
  NULL, NULL, &iter_init, &iter_deinit, &iter_operate,
4561
  &iter_inform_super, &iter_clear, &iter_get_mem
4562
};
4563
4564
struct module_func_block* 
4565
iter_get_funcblock(void)
4566
0
{
4567
0
  return &iter_block;
4568
0
}
4569
4570
const char* 
4571
iter_state_to_string(enum iter_state state)
4572
0
{
4573
0
  switch (state)
4574
0
  {
4575
0
  case INIT_REQUEST_STATE :
4576
0
    return "INIT REQUEST STATE";
4577
0
  case INIT_REQUEST_2_STATE :
4578
0
    return "INIT REQUEST STATE (stage 2)";
4579
0
  case INIT_REQUEST_3_STATE:
4580
0
    return "INIT REQUEST STATE (stage 3)";
4581
0
  case QUERYTARGETS_STATE :
4582
0
    return "QUERY TARGETS STATE";
4583
0
  case PRIME_RESP_STATE :
4584
0
    return "PRIME RESPONSE STATE";
4585
0
  case COLLECT_CLASS_STATE :
4586
0
    return "COLLECT CLASS STATE";
4587
0
  case DSNS_FIND_STATE :
4588
0
    return "DSNS FIND STATE";
4589
0
  case QUERY_RESP_STATE :
4590
0
    return "QUERY RESPONSE STATE";
4591
0
  case FINISHED_STATE :
4592
0
    return "FINISHED RESPONSE STATE";
4593
0
  default :
4594
0
    return "UNKNOWN ITER STATE";
4595
0
  }
4596
0
}
4597
4598
int 
4599
iter_state_is_responsestate(enum iter_state s)
4600
0
{
4601
0
  switch(s) {
4602
0
    case INIT_REQUEST_STATE :
4603
0
    case INIT_REQUEST_2_STATE :
4604
0
    case INIT_REQUEST_3_STATE :
4605
0
    case QUERYTARGETS_STATE :
4606
0
    case COLLECT_CLASS_STATE :
4607
0
      return 0;
4608
0
    default:
4609
0
      break;
4610
0
  }
4611
0
  return 1;
4612
0
}