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