Coverage Report

Created: 2025-11-16 06:46

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