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