Coverage Report

Created: 2026-04-15 06:24

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