]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - iterator/iterator.c
import unbound 1.4.21
[FreeBSD/FreeBSD.git] / 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 LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * This file contains a module that performs recusive iterative DNS query
40  * processing.
41  */
42
43 #include "config.h"
44 #include <ldns/ldns.h>
45 #include "iterator/iterator.h"
46 #include "iterator/iter_utils.h"
47 #include "iterator/iter_hints.h"
48 #include "iterator/iter_fwd.h"
49 #include "iterator/iter_donotq.h"
50 #include "iterator/iter_delegpt.h"
51 #include "iterator/iter_resptype.h"
52 #include "iterator/iter_scrub.h"
53 #include "iterator/iter_priv.h"
54 #include "validator/val_neg.h"
55 #include "services/cache/dns.h"
56 #include "services/cache/infra.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
66 int 
67 iter_init(struct module_env* env, int id)
68 {
69         struct iter_env* iter_env = (struct iter_env*)calloc(1,
70                 sizeof(struct iter_env));
71         if(!iter_env) {
72                 log_err("malloc failure");
73                 return 0;
74         }
75         env->modinfo[id] = (void*)iter_env;
76         if(!iter_apply_cfg(iter_env, env->cfg)) {
77                 log_err("iterator: could not apply configuration settings.");
78                 return 0;
79         }
80         return 1;
81 }
82
83 void 
84 iter_deinit(struct module_env* env, int id)
85 {
86         struct iter_env* iter_env;
87         if(!env || !env->modinfo[id])
88                 return;
89         iter_env = (struct iter_env*)env->modinfo[id];
90         free(iter_env->target_fetch_policy);
91         priv_delete(iter_env->priv);
92         donotq_delete(iter_env->donotq);
93         free(iter_env);
94         env->modinfo[id] = NULL;
95 }
96
97 /** new query for iterator */
98 static int
99 iter_new(struct module_qstate* qstate, int id)
100 {
101         struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
102                 qstate->region, sizeof(struct iter_qstate));
103         qstate->minfo[id] = iq;
104         if(!iq) 
105                 return 0;
106         memset(iq, 0, sizeof(*iq));
107         iq->state = INIT_REQUEST_STATE;
108         iq->final_state = FINISHED_STATE;
109         iq->an_prepend_list = NULL;
110         iq->an_prepend_last = NULL;
111         iq->ns_prepend_list = NULL;
112         iq->ns_prepend_last = NULL;
113         iq->dp = NULL;
114         iq->depth = 0;
115         iq->num_target_queries = 0;
116         iq->num_current_queries = 0;
117         iq->query_restart_count = 0;
118         iq->referral_count = 0;
119         iq->sent_count = 0;
120         iq->wait_priming_stub = 0;
121         iq->refetch_glue = 0;
122         iq->dnssec_expected = 0;
123         iq->dnssec_lame_query = 0;
124         iq->chase_flags = qstate->query_flags;
125         /* Start with the (current) qname. */
126         iq->qchase = qstate->qinfo;
127         outbound_list_init(&iq->outlist);
128         return 1;
129 }
130
131 /**
132  * Transition to the next state. This can be used to advance a currently
133  * processing event. It cannot be used to reactivate a forEvent.
134  *
135  * @param iq: iterator query state
136  * @param nextstate The state to transition to.
137  * @return true. This is so this can be called as the return value for the
138  *         actual process*State() methods. (Transitioning to the next state
139  *         implies further processing).
140  */
141 static int
142 next_state(struct iter_qstate* iq, enum iter_state nextstate)
143 {
144         /* If transitioning to a "response" state, make sure that there is a
145          * response */
146         if(iter_state_is_responsestate(nextstate)) {
147                 if(iq->response == NULL) {
148                         log_err("transitioning to response state sans "
149                                 "response.");
150                 }
151         }
152         iq->state = nextstate;
153         return 1;
154 }
155
156 /**
157  * Transition an event to its final state. Final states always either return
158  * a result up the module chain, or reactivate a dependent event. Which
159  * final state to transtion to is set in the module state for the event when
160  * it was created, and depends on the original purpose of the event.
161  *
162  * The response is stored in the qstate->buf buffer.
163  *
164  * @param iq: iterator query state
165  * @return false. This is so this method can be used as the return value for
166  *         the processState methods. (Transitioning to the final state
167  */
168 static int
169 final_state(struct iter_qstate* iq)
170 {
171         return next_state(iq, iq->final_state);
172 }
173
174 /**
175  * Callback routine to handle errors in parent query states
176  * @param qstate: query state that failed.
177  * @param id: module id.
178  * @param super: super state.
179  */
180 static void
181 error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
182 {
183         struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
184
185         if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
186                 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
187                 /* mark address as failed. */
188                 struct delegpt_ns* dpns = NULL;
189                 if(super_iq->dp)
190                         dpns = delegpt_find_ns(super_iq->dp, 
191                                 qstate->qinfo.qname, qstate->qinfo.qname_len);
192                 if(!dpns) {
193                         /* not interested */
194                         verbose(VERB_ALGO, "subq error, but not interested");
195                         log_query_info(VERB_ALGO, "superq", &super->qinfo);
196                         if(super_iq->dp)
197                                 delegpt_log(VERB_ALGO, super_iq->dp);
198                         log_assert(0);
199                         return;
200                 } else {
201                         /* see if the failure did get (parent-lame) info */
202                         if(!cache_fill_missing(super->env, 
203                                 super_iq->qchase.qclass, super->region, 
204                                 super_iq->dp))
205                                 log_err("out of memory adding missing");
206                 }
207                 dpns->resolved = 1; /* mark as failed */
208                 super_iq->num_target_queries--; 
209         }
210         if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
211                 /* prime failed to get delegation */
212                 super_iq->dp = NULL;
213         }
214         /* evaluate targets again */
215         super_iq->state = QUERYTARGETS_STATE; 
216         /* super becomes runnable, and will process this change */
217 }
218
219 /**
220  * Return an error to the client
221  * @param qstate: our query state
222  * @param id: module id
223  * @param rcode: error code (DNS errcode).
224  * @return: 0 for use by caller, to make notation easy, like:
225  *      return error_response(..). 
226  */
227 static int
228 error_response(struct module_qstate* qstate, int id, int rcode)
229 {
230         verbose(VERB_QUERY, "return error response %s", 
231                 ldns_lookup_by_id(ldns_rcodes, rcode)?
232                 ldns_lookup_by_id(ldns_rcodes, rcode)->name:"??");
233         qstate->return_rcode = rcode;
234         qstate->return_msg = NULL;
235         qstate->ext_state[id] = module_finished;
236         return 0;
237 }
238
239 /**
240  * Return an error to the client and cache the error code in the
241  * message cache (so per qname, qtype, qclass).
242  * @param qstate: our query state
243  * @param id: module id
244  * @param rcode: error code (DNS errcode).
245  * @return: 0 for use by caller, to make notation easy, like:
246  *      return error_response(..). 
247  */
248 static int
249 error_response_cache(struct module_qstate* qstate, int id, int rcode)
250 {
251         /* store in cache */
252         struct reply_info err;
253         memset(&err, 0, sizeof(err));
254         err.flags = (uint16_t)(BIT_QR | BIT_RA);
255         FLAGS_SET_RCODE(err.flags, rcode);
256         err.qdcount = 1;
257         err.ttl = NORR_TTL;
258         err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
259         /* do not waste time trying to validate this servfail */
260         err.security = sec_status_indeterminate;
261         verbose(VERB_ALGO, "store error response in message cache");
262         iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL);
263         return error_response(qstate, id, rcode);
264 }
265
266 /** check if prepend item is duplicate item */
267 static int
268 prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
269         struct ub_packed_rrset_key* dup)
270 {
271         size_t i;
272         for(i=0; i<to; i++) {
273                 if(sets[i]->rk.type == dup->rk.type &&
274                         sets[i]->rk.rrset_class == dup->rk.rrset_class &&
275                         sets[i]->rk.dname_len == dup->rk.dname_len &&
276                         query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
277                         == 0)
278                         return 1;
279         }
280         return 0;
281 }
282
283 /** prepend the prepend list in the answer and authority section of dns_msg */
284 static int
285 iter_prepend(struct iter_qstate* iq, struct dns_msg* msg, 
286         struct regional* region)
287 {
288         struct iter_prep_list* p;
289         struct ub_packed_rrset_key** sets;
290         size_t num_an = 0, num_ns = 0;;
291         for(p = iq->an_prepend_list; p; p = p->next)
292                 num_an++;
293         for(p = iq->ns_prepend_list; p; p = p->next)
294                 num_ns++;
295         if(num_an + num_ns == 0)
296                 return 1;
297         verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
298         sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
299                 sizeof(struct ub_packed_rrset_key*));
300         if(!sets) 
301                 return 0;
302         /* ANSWER section */
303         num_an = 0;
304         for(p = iq->an_prepend_list; p; p = p->next) {
305                 sets[num_an++] = p->rrset;
306         }
307         memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
308                 sizeof(struct ub_packed_rrset_key*));
309         /* AUTH section */
310         num_ns = 0;
311         for(p = iq->ns_prepend_list; p; p = p->next) {
312                 if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
313                         num_ns, p->rrset) || prepend_is_duplicate(
314                         msg->rep->rrsets+msg->rep->an_numrrsets, 
315                         msg->rep->ns_numrrsets, p->rrset))
316                         continue;
317                 sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
318         }
319         memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns, 
320                 msg->rep->rrsets + msg->rep->an_numrrsets, 
321                 (msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
322                 sizeof(struct ub_packed_rrset_key*));
323
324         /* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
325          * this is what recursors should give. */
326         msg->rep->rrset_count += num_an + num_ns;
327         msg->rep->an_numrrsets += num_an;
328         msg->rep->ns_numrrsets += num_ns;
329         msg->rep->rrsets = sets;
330         return 1;
331 }
332
333 /**
334  * Add rrset to ANSWER prepend list
335  * @param qstate: query state.
336  * @param iq: iterator query state.
337  * @param rrset: rrset to add.
338  * @return false on failure (malloc).
339  */
340 static int
341 iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
342         struct ub_packed_rrset_key* rrset)
343 {
344         struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
345                 qstate->region, sizeof(struct iter_prep_list));
346         if(!p)
347                 return 0;
348         p->rrset = rrset;
349         p->next = NULL;
350         /* add at end */
351         if(iq->an_prepend_last)
352                 iq->an_prepend_last->next = p;
353         else    iq->an_prepend_list = p;
354         iq->an_prepend_last = p;
355         return 1;
356 }
357
358 /**
359  * Add rrset to AUTHORITY prepend list
360  * @param qstate: query state.
361  * @param iq: iterator query state.
362  * @param rrset: rrset to add.
363  * @return false on failure (malloc).
364  */
365 static int
366 iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
367         struct ub_packed_rrset_key* rrset)
368 {
369         struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
370                 qstate->region, sizeof(struct iter_prep_list));
371         if(!p)
372                 return 0;
373         p->rrset = rrset;
374         p->next = NULL;
375         /* add at end */
376         if(iq->ns_prepend_last)
377                 iq->ns_prepend_last->next = p;
378         else    iq->ns_prepend_list = p;
379         iq->ns_prepend_last = p;
380         return 1;
381 }
382
383 /**
384  * Given a CNAME response (defined as a response containing a CNAME or DNAME
385  * that does not answer the request), process the response, modifying the
386  * state as necessary. This follows the CNAME/DNAME chain and returns the
387  * final query name.
388  *
389  * sets the new query name, after following the CNAME/DNAME chain.
390  * @param qstate: query state.
391  * @param iq: iterator query state.
392  * @param msg: the response.
393  * @param mname: returned target new query name.
394  * @param mname_len: length of mname.
395  * @return false on (malloc) error.
396  */
397 static int
398 handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
399         struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
400 {
401         size_t i;
402         /* Start with the (current) qname. */
403         *mname = iq->qchase.qname;
404         *mname_len = iq->qchase.qname_len;
405
406         /* Iterate over the ANSWER rrsets in order, looking for CNAMEs and 
407          * DNAMES. */
408         for(i=0; i<msg->rep->an_numrrsets; i++) {
409                 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
410                 /* If there is a (relevant) DNAME, add it to the list.
411                  * We always expect there to be CNAME that was generated 
412                  * by this DNAME following, so we don't process the DNAME 
413                  * directly.  */
414                 if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
415                         dname_strict_subdomain_c(*mname, r->rk.dname)) {
416                         if(!iter_add_prepend_answer(qstate, iq, r))
417                                 return 0;
418                         continue;
419                 }
420
421                 if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
422                         query_dname_compare(*mname, r->rk.dname) == 0) {
423                         /* Add this relevant CNAME rrset to the prepend list.*/
424                         if(!iter_add_prepend_answer(qstate, iq, r))
425                                 return 0;
426                         get_cname_target(r, mname, mname_len);
427                 }
428
429                 /* Other rrsets in the section are ignored. */
430         }
431         /* add authority rrsets to authority prepend, for wildcarded CNAMEs */
432         for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
433                 msg->rep->ns_numrrsets; i++) {
434                 struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
435                 /* only add NSEC/NSEC3, as they may be needed for validation */
436                 if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
437                         ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
438                         if(!iter_add_prepend_auth(qstate, iq, r))
439                                 return 0;
440                 }
441         }
442         return 1;
443 }
444
445 /**
446  * Generate a subrequest.
447  * Generate a local request event. Local events are tied to this module, and
448  * have a correponding (first tier) event that is waiting for this event to
449  * resolve to continue.
450  *
451  * @param qname The query name for this request.
452  * @param qnamelen length of qname
453  * @param qtype The query type for this request.
454  * @param qclass The query class for this request.
455  * @param qstate The event that is generating this event.
456  * @param id: module id.
457  * @param iq: The iterator state that is generating this event.
458  * @param initial_state The initial response state (normally this
459  *          is QUERY_RESP_STATE, unless it is known that the request won't
460  *          need iterative processing
461  * @param finalstate The final state for the response to this request.
462  * @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
463  *      not need initialisation.
464  * @param v: if true, validation is done on the subquery.
465  * @return false on error (malloc).
466  */
467 static int
468 generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype, 
469         uint16_t qclass, struct module_qstate* qstate, int id,
470         struct iter_qstate* iq, enum iter_state initial_state, 
471         enum iter_state finalstate, struct module_qstate** subq_ret, int v)
472 {
473         struct module_qstate* subq = NULL;
474         struct iter_qstate* subiq = NULL;
475         uint16_t qflags = 0; /* OPCODE QUERY, no flags */
476         struct query_info qinf;
477         int prime = (finalstate == PRIME_RESP_STATE)?1:0;
478         qinf.qname = qname;
479         qinf.qname_len = qnamelen;
480         qinf.qtype = qtype;
481         qinf.qclass = qclass;
482
483         /* RD should be set only when sending the query back through the INIT
484          * state. */
485         if(initial_state == INIT_REQUEST_STATE)
486                 qflags |= BIT_RD;
487         /* We set the CD flag so we can send this through the "head" of 
488          * the resolution chain, which might have a validator. We are 
489          * uninterested in validating things not on the direct resolution 
490          * path.  */
491         if(!v)
492                 qflags |= BIT_CD;
493         
494         /* attach subquery, lookup existing or make a new one */
495         fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
496         if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime, &subq)) {
497                 return 0;
498         }
499         *subq_ret = subq;
500         if(subq) {
501                 /* initialise the new subquery */
502                 subq->curmod = id;
503                 subq->ext_state[id] = module_state_initial;
504                 subq->minfo[id] = regional_alloc(subq->region, 
505                         sizeof(struct iter_qstate));
506                 if(!subq->minfo[id]) {
507                         log_err("init subq: out of memory");
508                         fptr_ok(fptr_whitelist_modenv_kill_sub(
509                                 qstate->env->kill_sub));
510                         (*qstate->env->kill_sub)(subq);
511                         return 0;
512                 }
513                 subiq = (struct iter_qstate*)subq->minfo[id];
514                 memset(subiq, 0, sizeof(*subiq));
515                 subiq->num_target_queries = 0;
516                 subiq->num_current_queries = 0;
517                 subiq->depth = iq->depth+1;
518                 outbound_list_init(&subiq->outlist);
519                 subiq->state = initial_state;
520                 subiq->final_state = finalstate;
521                 subiq->qchase = subq->qinfo;
522                 subiq->chase_flags = subq->query_flags;
523                 subiq->refetch_glue = 0;
524         }
525         return 1;
526 }
527
528 /**
529  * Generate and send a root priming request.
530  * @param qstate: the qtstate that triggered the need to prime.
531  * @param iq: iterator query state.
532  * @param id: module id.
533  * @param qclass: the class to prime.
534  * @return 0 on failure
535  */
536 static int
537 prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
538         uint16_t qclass)
539 {
540         struct delegpt* dp;
541         struct module_qstate* subq;
542         verbose(VERB_DETAIL, "priming . %s NS", 
543                 ldns_lookup_by_id(ldns_rr_classes, (int)qclass)?
544                 ldns_lookup_by_id(ldns_rr_classes, (int)qclass)->name:"??");
545         dp = hints_lookup_root(qstate->env->hints, qclass);
546         if(!dp) {
547                 verbose(VERB_ALGO, "Cannot prime due to lack of hints");
548                 return 0;
549         }
550         /* Priming requests start at the QUERYTARGETS state, skipping 
551          * the normal INIT state logic (which would cause an infloop). */
552         if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS, 
553                 qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
554                 &subq, 0)) {
555                 verbose(VERB_ALGO, "could not prime root");
556                 return 0;
557         }
558         if(subq) {
559                 struct iter_qstate* subiq = 
560                         (struct iter_qstate*)subq->minfo[id];
561                 /* Set the initial delegation point to the hint.
562                  * copy dp, it is now part of the root prime query. 
563                  * dp was part of in the fixed hints structure. */
564                 subiq->dp = delegpt_copy(dp, subq->region);
565                 if(!subiq->dp) {
566                         log_err("out of memory priming root, copydp");
567                         fptr_ok(fptr_whitelist_modenv_kill_sub(
568                                 qstate->env->kill_sub));
569                         (*qstate->env->kill_sub)(subq);
570                         return 0;
571                 }
572                 /* there should not be any target queries. */
573                 subiq->num_target_queries = 0; 
574                 subiq->dnssec_expected = iter_indicates_dnssec(
575                         qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
576         }
577         
578         /* this module stops, our submodule starts, and does the query. */
579         qstate->ext_state[id] = module_wait_subquery;
580         return 1;
581 }
582
583 /**
584  * Generate and process a stub priming request. This method tests for the
585  * need to prime a stub zone, so it is safe to call for every request.
586  *
587  * @param qstate: the qtstate that triggered the need to prime.
588  * @param iq: iterator query state.
589  * @param id: module id.
590  * @param qname: request name.
591  * @param qclass: request class.
592  * @return true if a priming subrequest was made, false if not. The will only
593  *         issue a priming request if it detects an unprimed stub.
594  *         Uses value of 2 to signal during stub-prime in root-prime situation
595  *         that a noprime-stub is available and resolution can continue.
596  */
597 static int
598 prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
599         uint8_t* qname, uint16_t qclass)
600 {
601         /* Lookup the stub hint. This will return null if the stub doesn't 
602          * need to be re-primed. */
603         struct iter_hints_stub* stub;
604         struct delegpt* stub_dp;
605         struct module_qstate* subq;
606
607         if(!qname) return 0;
608         stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp);
609         /* The stub (if there is one) does not need priming. */
610         if(!stub)
611                 return 0;
612         stub_dp = stub->dp;
613
614         /* is it a noprime stub (always use) */
615         if(stub->noprime) {
616                 int r = 0;
617                 if(iq->dp == NULL) r = 2;
618                 /* copy the dp out of the fixed hints structure, so that
619                  * it can be changed when servicing this query */
620                 iq->dp = delegpt_copy(stub_dp, qstate->region);
621                 if(!iq->dp) {
622                         log_err("out of memory priming stub");
623                         (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
624                         return 1; /* return 1 to make module stop, with error */
625                 }
626                 log_nametypeclass(VERB_DETAIL, "use stub", stub_dp->name, 
627                         LDNS_RR_TYPE_NS, qclass);
628                 return r;
629         }
630
631         /* Otherwise, we need to (re)prime the stub. */
632         log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name, 
633                 LDNS_RR_TYPE_NS, qclass);
634
635         /* Stub priming events start at the QUERYTARGETS state to avoid the
636          * redundant INIT state processing. */
637         if(!generate_sub_request(stub_dp->name, stub_dp->namelen, 
638                 LDNS_RR_TYPE_NS, qclass, qstate, id, iq,
639                 QUERYTARGETS_STATE, PRIME_RESP_STATE, &subq, 0)) {
640                 verbose(VERB_ALGO, "could not prime stub");
641                 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
642                 return 1; /* return 1 to make module stop, with error */
643         }
644         if(subq) {
645                 struct iter_qstate* subiq = 
646                         (struct iter_qstate*)subq->minfo[id];
647
648                 /* Set the initial delegation point to the hint. */
649                 /* make copy to avoid use of stub dp by different qs/threads */
650                 subiq->dp = delegpt_copy(stub_dp, subq->region);
651                 if(!subiq->dp) {
652                         log_err("out of memory priming stub, copydp");
653                         fptr_ok(fptr_whitelist_modenv_kill_sub(
654                                 qstate->env->kill_sub));
655                         (*qstate->env->kill_sub)(subq);
656                         (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
657                         return 1; /* return 1 to make module stop, with error */
658                 }
659                 /* there should not be any target queries -- although there 
660                  * wouldn't be anyway, since stub hints never have 
661                  * missing targets. */
662                 subiq->num_target_queries = 0; 
663                 subiq->wait_priming_stub = 1;
664                 subiq->dnssec_expected = iter_indicates_dnssec(
665                         qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
666         }
667         
668         /* this module stops, our submodule starts, and does the query. */
669         qstate->ext_state[id] = module_wait_subquery;
670         return 1;
671 }
672
673 /**
674  * Generate A and AAAA checks for glue that is in-zone for the referral
675  * we just got to obtain authoritative information on the adresses.
676  *
677  * @param qstate: the qtstate that triggered the need to prime.
678  * @param iq: iterator query state.
679  * @param id: module id.
680  */
681 static void
682 generate_a_aaaa_check(struct module_qstate* qstate, struct iter_qstate* iq, 
683         int id)
684 {
685         struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
686         struct module_qstate* subq;
687         size_t i;
688         struct reply_info* rep = iq->response->rep;
689         struct ub_packed_rrset_key* s;
690         log_assert(iq->dp);
691
692         if(iq->depth == ie->max_dependency_depth)
693                 return;
694         /* walk through additional, and check if in-zone,
695          * only relevant A, AAAA are left after scrub anyway */
696         for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
697                 s = rep->rrsets[i];
698                 /* check *ALL* addresses that are transmitted in additional*/
699                 /* is it an address ? */
700                 if( !(ntohs(s->rk.type)==LDNS_RR_TYPE_A ||
701                         ntohs(s->rk.type)==LDNS_RR_TYPE_AAAA)) {
702                         continue;
703                 }
704                 /* is this query the same as the A/AAAA check for it */
705                 if(qstate->qinfo.qtype == ntohs(s->rk.type) &&
706                         qstate->qinfo.qclass == ntohs(s->rk.rrset_class) &&
707                         query_dname_compare(qstate->qinfo.qname, 
708                                 s->rk.dname)==0 &&
709                         (qstate->query_flags&BIT_RD) && 
710                         !(qstate->query_flags&BIT_CD))
711                         continue;
712
713                 /* generate subrequest for it */
714                 log_nametypeclass(VERB_ALGO, "schedule addr fetch", 
715                         s->rk.dname, ntohs(s->rk.type), 
716                         ntohs(s->rk.rrset_class));
717                 if(!generate_sub_request(s->rk.dname, s->rk.dname_len, 
718                         ntohs(s->rk.type), ntohs(s->rk.rrset_class),
719                         qstate, id, iq,
720                         INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
721                         verbose(VERB_ALGO, "could not generate addr check");
722                         return;
723                 }
724                 /* ignore subq - not need for more init */
725         }
726 }
727
728 /**
729  * Generate a NS check request to obtain authoritative information
730  * on an NS rrset.
731  *
732  * @param qstate: the qtstate that triggered the need to prime.
733  * @param iq: iterator query state.
734  * @param id: module id.
735  */
736 static void
737 generate_ns_check(struct module_qstate* qstate, struct iter_qstate* iq, int id)
738 {
739         struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
740         struct module_qstate* subq;
741         log_assert(iq->dp);
742
743         if(iq->depth == ie->max_dependency_depth)
744                 return;
745         /* is this query the same as the nscheck? */
746         if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS &&
747                 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
748                 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
749                 /* spawn off A, AAAA queries for in-zone glue to check */
750                 generate_a_aaaa_check(qstate, iq, id);
751                 return;
752         }
753
754         log_nametypeclass(VERB_ALGO, "schedule ns fetch", 
755                 iq->dp->name, LDNS_RR_TYPE_NS, iq->qchase.qclass);
756         if(!generate_sub_request(iq->dp->name, iq->dp->namelen, 
757                 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
758                 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
759                 verbose(VERB_ALGO, "could not generate ns check");
760                 return;
761         }
762         if(subq) {
763                 struct iter_qstate* subiq = 
764                         (struct iter_qstate*)subq->minfo[id];
765
766                 /* make copy to avoid use of stub dp by different qs/threads */
767                 /* refetch glue to start higher up the tree */
768                 subiq->refetch_glue = 1;
769                 subiq->dp = delegpt_copy(iq->dp, subq->region);
770                 if(!subiq->dp) {
771                         log_err("out of memory generating ns check, copydp");
772                         fptr_ok(fptr_whitelist_modenv_kill_sub(
773                                 qstate->env->kill_sub));
774                         (*qstate->env->kill_sub)(subq);
775                         return;
776                 }
777         }
778 }
779
780 /**
781  * Generate a DNSKEY prefetch query to get the DNSKEY for the DS record we
782  * just got in a referral (where we have dnssec_expected, thus have trust
783  * anchors above it).  Note that right after calling this routine the
784  * iterator detached subqueries (because of following the referral), and thus
785  * the DNSKEY query becomes detached, its return stored in the cache for
786  * later lookup by the validator.  This cache lookup by the validator avoids
787  * the roundtrip incurred by the DNSKEY query.  The DNSKEY query is now
788  * performed at about the same time the original query is sent to the domain,
789  * thus the two answers are likely to be returned at about the same time,
790  * saving a roundtrip from the validated lookup.
791  *
792  * @param qstate: the qtstate that triggered the need to prime.
793  * @param iq: iterator query state.
794  * @param id: module id.
795  */
796 static void
797 generate_dnskey_prefetch(struct module_qstate* qstate, 
798         struct iter_qstate* iq, int id)
799 {
800         struct module_qstate* subq;
801         log_assert(iq->dp);
802
803         /* is this query the same as the prefetch? */
804         if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
805                 query_dname_compare(iq->dp->name, qstate->qinfo.qname)==0 &&
806                 (qstate->query_flags&BIT_RD) && !(qstate->query_flags&BIT_CD)){
807                 return;
808         }
809
810         /* if the DNSKEY is in the cache this lookup will stop quickly */
811         log_nametypeclass(VERB_ALGO, "schedule dnskey prefetch", 
812                 iq->dp->name, LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass);
813         if(!generate_sub_request(iq->dp->name, iq->dp->namelen, 
814                 LDNS_RR_TYPE_DNSKEY, iq->qchase.qclass, qstate, id, iq,
815                 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
816                 /* we'll be slower, but it'll work */
817                 verbose(VERB_ALGO, "could not generate dnskey prefetch");
818                 return;
819         }
820         if(subq) {
821                 struct iter_qstate* subiq = 
822                         (struct iter_qstate*)subq->minfo[id];
823                 /* this qstate has the right delegation for the dnskey lookup*/
824                 /* make copy to avoid use of stub dp by different qs/threads */
825                 subiq->dp = delegpt_copy(iq->dp, subq->region);
826                 /* if !subiq->dp, it'll start from the cache, no problem */
827         }
828 }
829
830 /**
831  * See if the query needs forwarding.
832  * 
833  * @param qstate: query state.
834  * @param iq: iterator query state.
835  * @return true if the request is forwarded, false if not.
836  *      If returns true but, iq->dp is NULL then a malloc failure occurred.
837  */
838 static int
839 forward_request(struct module_qstate* qstate, struct iter_qstate* iq)
840 {
841         struct delegpt* dp;
842         uint8_t* delname = iq->qchase.qname;
843         size_t delnamelen = iq->qchase.qname_len;
844         if(iq->refetch_glue) {
845                 delname = iq->dp->name;
846                 delnamelen = iq->dp->namelen;
847         }
848         /* strip one label off of DS query to lookup higher for it */
849         if( (iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue)
850                 && !dname_is_root(iq->qchase.qname))
851                 dname_remove_label(&delname, &delnamelen);
852         dp = forwards_lookup(qstate->env->fwds, delname, iq->qchase.qclass);
853         if(!dp) 
854                 return 0;
855         /* send recursion desired to forward addr */
856         iq->chase_flags |= BIT_RD; 
857         iq->dp = delegpt_copy(dp, qstate->region);
858         /* iq->dp checked by caller */
859         verbose(VERB_ALGO, "forwarding request");
860         return 1;
861 }
862
863 /** 
864  * Process the initial part of the request handling. This state roughly
865  * corresponds to resolver algorithms steps 1 (find answer in cache) and 2
866  * (find the best servers to ask).
867  *
868  * Note that all requests start here, and query restarts revisit this state.
869  *
870  * This state either generates: 1) a response, from cache or error, 2) a
871  * priming event, or 3) forwards the request to the next state (init2,
872  * generally).
873  *
874  * @param qstate: query state.
875  * @param iq: iterator query state.
876  * @param ie: iterator shared global environment.
877  * @param id: module id.
878  * @return true if the event needs more request processing immediately,
879  *         false if not.
880  */
881 static int
882 processInitRequest(struct module_qstate* qstate, struct iter_qstate* iq,
883         struct iter_env* ie, int id)
884 {
885         uint8_t* delname;
886         size_t delnamelen;
887         struct dns_msg* msg;
888
889         log_query_info(VERB_DETAIL, "resolving", &qstate->qinfo);
890         /* check effort */
891
892         /* We enforce a maximum number of query restarts. This is primarily a
893          * cheap way to prevent CNAME loops. */
894         if(iq->query_restart_count > MAX_RESTART_COUNT) {
895                 verbose(VERB_QUERY, "request has exceeded the maximum number"
896                         " of query restarts with %d", iq->query_restart_count);
897                 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
898         }
899
900         /* We enforce a maximum recursion/dependency depth -- in general, 
901          * this is unnecessary for dependency loops (although it will 
902          * catch those), but it provides a sensible limit to the amount 
903          * of work required to answer a given query. */
904         verbose(VERB_ALGO, "request has dependency depth of %d", iq->depth);
905         if(iq->depth > ie->max_dependency_depth) {
906                 verbose(VERB_QUERY, "request has exceeded the maximum "
907                         "dependency depth with depth of %d", iq->depth);
908                 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
909         }
910
911         /* If the request is qclass=ANY, setup to generate each class */
912         if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
913                 iq->qchase.qclass = 0;
914                 return next_state(iq, COLLECT_CLASS_STATE);
915         }
916
917         /* Resolver Algorithm Step 1 -- Look for the answer in local data. */
918
919         /* This either results in a query restart (CNAME cache response), a
920          * terminating response (ANSWER), or a cache miss (null). */
921         
922         if(qstate->blacklist) {
923                 /* if cache, or anything else, was blacklisted then
924                  * getting older results from cache is a bad idea, no cache */
925                 verbose(VERB_ALGO, "cache blacklisted, going to the network");
926                 msg = NULL;
927         } else {
928                 msg = dns_cache_lookup(qstate->env, iq->qchase.qname, 
929                         iq->qchase.qname_len, iq->qchase.qtype, 
930                         iq->qchase.qclass, qstate->region, qstate->env->scratch);
931                 if(!msg && qstate->env->neg_cache) {
932                         /* lookup in negative cache; may result in 
933                          * NOERROR/NODATA or NXDOMAIN answers that need validation */
934                         msg = val_neg_getmsg(qstate->env->neg_cache, &iq->qchase,
935                                 qstate->region, qstate->env->rrset_cache,
936                                 qstate->env->scratch_buffer, 
937                                 *qstate->env->now, 1/*add SOA*/, NULL);
938                 }
939                 /* item taken from cache does not match our query name, thus
940                  * security needs to be re-examined later */
941                 if(msg && query_dname_compare(qstate->qinfo.qname,
942                         iq->qchase.qname) != 0)
943                         msg->rep->security = sec_status_unchecked;
944         }
945         if(msg) {
946                 /* handle positive cache response */
947                 enum response_type type = response_type_from_cache(msg, 
948                         &iq->qchase);
949                 if(verbosity >= VERB_ALGO) {
950                         log_dns_msg("msg from cache lookup", &msg->qinfo, 
951                                 msg->rep);
952                         verbose(VERB_ALGO, "msg ttl is %d, prefetch ttl %d", 
953                                 (int)msg->rep->ttl, 
954                                 (int)msg->rep->prefetch_ttl);
955                 }
956
957                 if(type == RESPONSE_TYPE_CNAME) {
958                         uint8_t* sname = 0;
959                         size_t slen = 0;
960                         verbose(VERB_ALGO, "returning CNAME response from "
961                                 "cache");
962                         if(!handle_cname_response(qstate, iq, msg, 
963                                 &sname, &slen))
964                                 return error_response(qstate, id, 
965                                         LDNS_RCODE_SERVFAIL);
966                         iq->qchase.qname = sname;
967                         iq->qchase.qname_len = slen;
968                         /* This *is* a query restart, even if it is a cheap 
969                          * one. */
970                         iq->dp = NULL;
971                         iq->refetch_glue = 0;
972                         iq->query_restart_count++;
973                         iq->sent_count = 0;
974                         sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
975                         return next_state(iq, INIT_REQUEST_STATE);
976                 }
977
978                 /* if from cache, NULL, else insert 'cache IP' len=0 */
979                 if(qstate->reply_origin)
980                         sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
981                 /* it is an answer, response, to final state */
982                 verbose(VERB_ALGO, "returning answer from cache.");
983                 iq->response = msg;
984                 return final_state(iq);
985         }
986         
987         /* attempt to forward the request */
988         if(forward_request(qstate, iq))
989         {
990                 if(!iq->dp) {
991                         log_err("alloc failure for forward dp");
992                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
993                 }
994                 iq->refetch_glue = 0;
995                 /* the request has been forwarded.
996                  * forwarded requests need to be immediately sent to the 
997                  * next state, QUERYTARGETS. */
998                 return next_state(iq, QUERYTARGETS_STATE);
999         }
1000
1001         /* Resolver Algorithm Step 2 -- find the "best" servers. */
1002
1003         /* first, adjust for DS queries. To avoid the grandparent problem, 
1004          * we just look for the closest set of server to the parent of qname.
1005          * When re-fetching glue we also need to ask the parent.
1006          */
1007         if(iq->refetch_glue) {
1008                 if(!iq->dp) {
1009                         log_err("internal or malloc fail: no dp for refetch");
1010                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1011                 }
1012                 delname = iq->dp->name;
1013                 delnamelen = iq->dp->namelen;
1014         } else {
1015                 delname = iq->qchase.qname;
1016                 delnamelen = iq->qchase.qname_len;
1017         }
1018         if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue ||
1019            (iq->qchase.qtype == LDNS_RR_TYPE_NS && qstate->prefetch_leeway)) {
1020                 /* remove first label from delname, root goes to hints,
1021                  * but only to fetch glue, not for qtype=DS. */
1022                 /* also when prefetching an NS record, fetch it again from
1023                  * its parent, just as if it expired, so that you do not
1024                  * get stuck on an older nameserver that gives old NSrecords */
1025                 if(dname_is_root(delname) && (iq->refetch_glue ||
1026                         (iq->qchase.qtype == LDNS_RR_TYPE_NS &&
1027                         qstate->prefetch_leeway)))
1028                         delname = NULL; /* go to root priming */
1029                 else    dname_remove_label(&delname, &delnamelen);
1030         }
1031         /* delname is the name to lookup a delegation for. If NULL rootprime */
1032         while(1) {
1033                 
1034                 /* Lookup the delegation in the cache. If null, then the 
1035                  * cache needs to be primed for the qclass. */
1036                 if(delname)
1037                      iq->dp = dns_cache_find_delegation(qstate->env, delname, 
1038                         delnamelen, iq->qchase.qtype, iq->qchase.qclass, 
1039                         qstate->region, &iq->deleg_msg,
1040                         *qstate->env->now+qstate->prefetch_leeway);
1041                 else iq->dp = NULL;
1042
1043                 /* If the cache has returned nothing, then we have a 
1044                  * root priming situation. */
1045                 if(iq->dp == NULL) {
1046                         /* if there is a stub, then no root prime needed */
1047                         int r = prime_stub(qstate, iq, id, delname,
1048                                 iq->qchase.qclass);
1049                         if(r == 2)
1050                                 break; /* got noprime-stub-zone, continue */
1051                         else if(r)
1052                                 return 0; /* stub prime request made */
1053                         if(forwards_lookup_root(qstate->env->fwds, 
1054                                 iq->qchase.qclass)) {
1055                                 /* forward zone root, no root prime needed */
1056                                 /* fill in some dp - safety belt */
1057                                 iq->dp = hints_lookup_root(qstate->env->hints, 
1058                                         iq->qchase.qclass);
1059                                 if(!iq->dp) {
1060                                         log_err("internal error: no hints dp");
1061                                         return error_response(qstate, id, 
1062                                                 LDNS_RCODE_SERVFAIL);
1063                                 }
1064                                 iq->dp = delegpt_copy(iq->dp, qstate->region);
1065                                 if(!iq->dp) {
1066                                         log_err("out of memory in safety belt");
1067                                         return error_response(qstate, id, 
1068                                                 LDNS_RCODE_SERVFAIL);
1069                                 }
1070                                 return next_state(iq, INIT_REQUEST_2_STATE);
1071                         }
1072                         /* Note that the result of this will set a new
1073                          * DelegationPoint based on the result of priming. */
1074                         if(!prime_root(qstate, iq, id, iq->qchase.qclass))
1075                                 return error_response(qstate, id, 
1076                                         LDNS_RCODE_REFUSED);
1077
1078                         /* priming creates and sends a subordinate query, with 
1079                          * this query as the parent. So further processing for 
1080                          * this event will stop until reactivated by the 
1081                          * results of priming. */
1082                         return 0;
1083                 }
1084
1085                 /* see if this dp not useless.
1086                  * It is useless if:
1087                  *      o all NS items are required glue. 
1088                  *        or the query is for NS item that is required glue.
1089                  *      o no addresses are provided.
1090                  *      o RD qflag is on.
1091                  * Instead, go up one level, and try to get even further
1092                  * If the root was useless, use safety belt information. 
1093                  * Only check cache returns, because replies for servers
1094                  * could be useless but lead to loops (bumping into the
1095                  * same server reply) if useless-checked.
1096                  */
1097                 if(iter_dp_is_useless(&qstate->qinfo, qstate->query_flags, 
1098                         iq->dp)) {
1099                         if(dname_is_root(iq->dp->name)) {
1100                                 /* use safety belt */
1101                                 verbose(VERB_QUERY, "Cache has root NS but "
1102                                 "no addresses. Fallback to the safety belt.");
1103                                 iq->dp = hints_lookup_root(qstate->env->hints, 
1104                                         iq->qchase.qclass);
1105                                 /* note deleg_msg is from previous lookup,
1106                                  * but RD is on, so it is not used */
1107                                 if(!iq->dp) {
1108                                         log_err("internal error: no hints dp");
1109                                         return error_response(qstate, id, 
1110                                                 LDNS_RCODE_REFUSED);
1111                                 }
1112                                 iq->dp = delegpt_copy(iq->dp, qstate->region);
1113                                 if(!iq->dp) {
1114                                         log_err("out of memory in safety belt");
1115                                         return error_response(qstate, id, 
1116                                                 LDNS_RCODE_SERVFAIL);
1117                                 }
1118                                 break;
1119                         } else {
1120                                 verbose(VERB_ALGO, 
1121                                         "cache delegation was useless:");
1122                                 delegpt_log(VERB_ALGO, iq->dp);
1123                                 /* go up */
1124                                 delname = iq->dp->name;
1125                                 delnamelen = iq->dp->namelen;
1126                                 dname_remove_label(&delname, &delnamelen);
1127                         }
1128                 } else break;
1129         }
1130
1131         verbose(VERB_ALGO, "cache delegation returns delegpt");
1132         delegpt_log(VERB_ALGO, iq->dp);
1133
1134         /* Otherwise, set the current delegation point and move on to the 
1135          * next state. */
1136         return next_state(iq, INIT_REQUEST_2_STATE);
1137 }
1138
1139 /** 
1140  * Process the second part of the initial request handling. This state
1141  * basically exists so that queries that generate root priming events have
1142  * the same init processing as ones that do not. Request events that reach
1143  * this state must have a valid currentDelegationPoint set.
1144  *
1145  * This part is primarly handling stub zone priming. Events that reach this
1146  * state must have a current delegation point.
1147  *
1148  * @param qstate: query state.
1149  * @param iq: iterator query state.
1150  * @param id: module id.
1151  * @return true if the event needs more request processing immediately,
1152  *         false if not.
1153  */
1154 static int
1155 processInitRequest2(struct module_qstate* qstate, struct iter_qstate* iq,
1156         int id)
1157 {
1158         uint8_t* delname;
1159         size_t delnamelen;
1160         log_query_info(VERB_QUERY, "resolving (init part 2): ", 
1161                 &qstate->qinfo);
1162
1163         if(iq->refetch_glue) {
1164                 if(!iq->dp) {
1165                         log_err("internal or malloc fail: no dp for refetch");
1166                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1167                 }
1168                 delname = iq->dp->name;
1169                 delnamelen = iq->dp->namelen;
1170         } else {
1171                 delname = iq->qchase.qname;
1172                 delnamelen = iq->qchase.qname_len;
1173         }
1174         if(iq->qchase.qtype == LDNS_RR_TYPE_DS || iq->refetch_glue) {
1175                 if(!dname_is_root(delname))
1176                         dname_remove_label(&delname, &delnamelen);
1177                 iq->refetch_glue = 0; /* if CNAME causes restart, no refetch */
1178         }
1179         /* Check to see if we need to prime a stub zone. */
1180         if(prime_stub(qstate, iq, id, delname, iq->qchase.qclass)) {
1181                 /* A priming sub request was made */
1182                 return 0;
1183         }
1184
1185         /* most events just get forwarded to the next state. */
1186         return next_state(iq, INIT_REQUEST_3_STATE);
1187 }
1188
1189 /** 
1190  * Process the third part of the initial request handling. This state exists
1191  * as a separate state so that queries that generate stub priming events
1192  * will get the tail end of the init process but not repeat the stub priming
1193  * check.
1194  *
1195  * @param qstate: query state.
1196  * @param iq: iterator query state.
1197  * @param id: module id.
1198  * @return true, advancing the event to the QUERYTARGETS_STATE.
1199  */
1200 static int
1201 processInitRequest3(struct module_qstate* qstate, struct iter_qstate* iq, 
1202         int id)
1203 {
1204         log_query_info(VERB_QUERY, "resolving (init part 3): ", 
1205                 &qstate->qinfo);
1206         /* if the cache reply dp equals a validation anchor or msg has DS,
1207          * then DNSSEC RRSIGs are expected in the reply */
1208         iq->dnssec_expected = iter_indicates_dnssec(qstate->env, iq->dp, 
1209                 iq->deleg_msg, iq->qchase.qclass);
1210
1211         /* If the RD flag wasn't set, then we just finish with the 
1212          * cached referral as the response. */
1213         if(!(qstate->query_flags & BIT_RD)) {
1214                 iq->response = iq->deleg_msg;
1215                 if(verbosity >= VERB_ALGO)
1216                         log_dns_msg("no RD requested, using delegation msg", 
1217                                 &iq->response->qinfo, iq->response->rep);
1218                 if(qstate->reply_origin)
1219                         sock_list_insert(&qstate->reply_origin, NULL, 0, qstate->region);
1220                 return final_state(iq);
1221         }
1222         /* After this point, unset the RD flag -- this query is going to 
1223          * be sent to an auth. server. */
1224         iq->chase_flags &= ~BIT_RD;
1225
1226         /* if dnssec expected, fetch key for the trust-anchor or cached-DS */
1227         if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
1228                 !(qstate->query_flags&BIT_CD)) {
1229                 generate_dnskey_prefetch(qstate, iq, id);
1230                 fptr_ok(fptr_whitelist_modenv_detach_subs(
1231                         qstate->env->detach_subs));
1232                 (*qstate->env->detach_subs)(qstate);
1233         }
1234
1235         /* Jump to the next state. */
1236         return next_state(iq, QUERYTARGETS_STATE);
1237 }
1238
1239 /**
1240  * Given a basic query, generate a parent-side "target" query. 
1241  * These are subordinate queries for missing delegation point target addresses,
1242  * for which only the parent of the delegation provides correct IP addresses.
1243  *
1244  * @param qstate: query state.
1245  * @param iq: iterator query state.
1246  * @param id: module id.
1247  * @param name: target qname.
1248  * @param namelen: target qname length.
1249  * @param qtype: target qtype (either A or AAAA).
1250  * @param qclass: target qclass.
1251  * @return true on success, false on failure.
1252  */
1253 static int
1254 generate_parentside_target_query(struct module_qstate* qstate, 
1255         struct iter_qstate* iq, int id, uint8_t* name, size_t namelen, 
1256         uint16_t qtype, uint16_t qclass)
1257 {
1258         struct module_qstate* subq;
1259         if(!generate_sub_request(name, namelen, qtype, qclass, qstate, 
1260                 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1261                 return 0;
1262         if(subq) {
1263                 struct iter_qstate* subiq = 
1264                         (struct iter_qstate*)subq->minfo[id];
1265                 /* blacklist the cache - we want to fetch parent stuff */
1266                 sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
1267                 subiq->query_for_pside_glue = 1;
1268                 if(dname_subdomain_c(name, iq->dp->name)) {
1269                         subiq->dp = delegpt_copy(iq->dp, subq->region);
1270                         subiq->dnssec_expected = iter_indicates_dnssec(
1271                                 qstate->env, subiq->dp, NULL, 
1272                                 subq->qinfo.qclass);
1273                         subiq->refetch_glue = 1;
1274                 } else {
1275                         subiq->dp = dns_cache_find_delegation(qstate->env, 
1276                                 name, namelen, qtype, qclass, subq->region,
1277                                 &subiq->deleg_msg,
1278                                 *qstate->env->now+subq->prefetch_leeway); 
1279                         /* if no dp, then it's from root, refetch unneeded */
1280                         if(subiq->dp) { 
1281                                 subiq->dnssec_expected = iter_indicates_dnssec(
1282                                         qstate->env, subiq->dp, NULL, 
1283                                         subq->qinfo.qclass);
1284                                 subiq->refetch_glue = 1;
1285                         }
1286                 }
1287         }
1288         log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
1289         return 1;
1290 }
1291
1292 /**
1293  * Given a basic query, generate a "target" query. These are subordinate
1294  * queries for missing delegation point target addresses.
1295  *
1296  * @param qstate: query state.
1297  * @param iq: iterator query state.
1298  * @param id: module id.
1299  * @param name: target qname.
1300  * @param namelen: target qname length.
1301  * @param qtype: target qtype (either A or AAAA).
1302  * @param qclass: target qclass.
1303  * @return true on success, false on failure.
1304  */
1305 static int
1306 generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq,
1307         int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass)
1308 {
1309         struct module_qstate* subq;
1310         if(!generate_sub_request(name, namelen, qtype, qclass, qstate, 
1311                 id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
1312                 return 0;
1313         log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass);
1314         return 1;
1315 }
1316
1317 /**
1318  * Given an event at a certain state, generate zero or more target queries
1319  * for it's current delegation point.
1320  *
1321  * @param qstate: query state.
1322  * @param iq: iterator query state.
1323  * @param ie: iterator shared global environment.
1324  * @param id: module id.
1325  * @param maxtargets: The maximum number of targets to query for.
1326  *      if it is negative, there is no maximum number of targets.
1327  * @param num: returns the number of queries generated and processed, 
1328  *      which may be zero if there were no missing targets.
1329  * @return false on error.
1330  */
1331 static int
1332 query_for_targets(struct module_qstate* qstate, struct iter_qstate* iq,
1333         struct iter_env* ie, int id, int maxtargets, int* num)
1334 {
1335         int query_count = 0;
1336         struct delegpt_ns* ns;
1337         int missing;
1338         int toget = 0;
1339
1340         if(iq->depth == ie->max_dependency_depth)
1341                 return 0;
1342
1343         iter_mark_cycle_targets(qstate, iq->dp);
1344         missing = (int)delegpt_count_missing_targets(iq->dp);
1345         log_assert(maxtargets != 0); /* that would not be useful */
1346
1347         /* Generate target requests. Basically, any missing targets 
1348          * are queried for here, regardless if it is necessary to do 
1349          * so to continue processing. */
1350         if(maxtargets < 0 || maxtargets > missing)
1351                 toget = missing;
1352         else    toget = maxtargets;
1353         if(toget == 0) {
1354                 *num = 0;
1355                 return 1;
1356         }
1357         /* select 'toget' items from the total of 'missing' items */
1358         log_assert(toget <= missing);
1359
1360         /* loop over missing targets */
1361         for(ns = iq->dp->nslist; ns; ns = ns->next) {
1362                 if(ns->resolved)
1363                         continue;
1364
1365                 /* randomly select this item with probability toget/missing */
1366                 if(!iter_ns_probability(qstate->env->rnd, toget, missing)) {
1367                         /* do not select this one, next; select toget number
1368                          * of items from a list one less in size */
1369                         missing --;
1370                         continue;
1371                 }
1372
1373                 if(ie->supports_ipv6 && !ns->got6) {
1374                         /* Send the AAAA request. */
1375                         if(!generate_target_query(qstate, iq, id, 
1376                                 ns->name, ns->namelen,
1377                                 LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) {
1378                                 *num = query_count;
1379                                 if(query_count > 0)
1380                                         qstate->ext_state[id] = module_wait_subquery;
1381                                 return 0;
1382                         }
1383                         query_count++;
1384                 }
1385                 /* Send the A request. */
1386                 if(ie->supports_ipv4 && !ns->got4) {
1387                         if(!generate_target_query(qstate, iq, id, 
1388                                 ns->name, ns->namelen, 
1389                                 LDNS_RR_TYPE_A, iq->qchase.qclass)) {
1390                                 *num = query_count;
1391                                 if(query_count > 0)
1392                                         qstate->ext_state[id] = module_wait_subquery;
1393                                 return 0;
1394                         }
1395                         query_count++;
1396                 }
1397
1398                 /* mark this target as in progress. */
1399                 ns->resolved = 1;
1400                 missing--;
1401                 toget--;
1402                 if(toget == 0)
1403                         break;
1404         }
1405         *num = query_count;
1406         if(query_count > 0)
1407                 qstate->ext_state[id] = module_wait_subquery;
1408
1409         return 1;
1410 }
1411
1412 /** see if last resort is possible - does config allow queries to parent */
1413 static int
1414 can_have_last_resort(struct module_env* env, struct delegpt* dp,
1415         struct iter_qstate* iq)
1416 {
1417         struct delegpt* fwddp;
1418         struct iter_hints_stub* stub;
1419         /* do not process a last resort (the parent side) if a stub
1420          * or forward is configured, because we do not want to go 'above'
1421          * the configured servers */
1422         if(!dname_is_root(dp->name) && (stub = (struct iter_hints_stub*)
1423                 name_tree_find(&env->hints->tree, dp->name, dp->namelen,
1424                 dp->namelabs, iq->qchase.qclass)) &&
1425                 /* has_parent side is turned off for stub_first, where we
1426                  * are allowed to go to the parent */
1427                 stub->dp->has_parent_side_NS) {
1428                 verbose(VERB_QUERY, "configured stub servers failed -- returning SERVFAIL");
1429                 return 0;
1430         }
1431         if((fwddp = forwards_find(env->fwds, dp->name, iq->qchase.qclass)) &&
1432                 /* has_parent_side is turned off for forward_first, where
1433                  * we are allowed to go to the parent */
1434                 fwddp->has_parent_side_NS) {
1435                 verbose(VERB_QUERY, "configured forward servers failed -- returning SERVFAIL");
1436                 return 0;
1437         }
1438         return 1;
1439 }
1440
1441 /**
1442  * Called by processQueryTargets when it would like extra targets to query
1443  * but it seems to be out of options.  At last resort some less appealing
1444  * options are explored.  If there are no more options, the result is SERVFAIL
1445  *
1446  * @param qstate: query state.
1447  * @param iq: iterator query state.
1448  * @param ie: iterator shared global environment.
1449  * @param id: module id.
1450  * @return true if the event requires more request processing immediately,
1451  *         false if not. 
1452  */
1453 static int
1454 processLastResort(struct module_qstate* qstate, struct iter_qstate* iq,
1455         struct iter_env* ie, int id)
1456 {
1457         struct delegpt_ns* ns;
1458         int query_count = 0;
1459         verbose(VERB_ALGO, "No more query targets, attempting last resort");
1460         log_assert(iq->dp);
1461
1462         if(!can_have_last_resort(qstate->env, iq->dp, iq)) {
1463                 /* fail -- no more targets, no more hope of targets, no hope 
1464                  * of a response. */
1465                 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1466         }
1467         if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) {
1468                 struct delegpt* p = hints_lookup_root(qstate->env->hints,
1469                         iq->qchase.qclass);
1470                 if(p) {
1471                         struct delegpt_ns* ns;
1472                         struct delegpt_addr* a;
1473                         iq->chase_flags &= ~BIT_RD; /* go to authorities */
1474                         for(ns = p->nslist; ns; ns=ns->next) {
1475                                 (void)delegpt_add_ns(iq->dp, qstate->region,
1476                                         ns->name, ns->lame);
1477                         }
1478                         for(a = p->target_list; a; a=a->next_target) {
1479                                 (void)delegpt_add_addr(iq->dp, qstate->region,
1480                                         &a->addr, a->addrlen, a->bogus,
1481                                         a->lame);
1482                         }
1483                 }
1484                 iq->dp->has_parent_side_NS = 1;
1485         } else if(!iq->dp->has_parent_side_NS) {
1486                 if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp,
1487                         qstate->region, &qstate->qinfo) 
1488                         || !iq->dp->has_parent_side_NS) {
1489                         /* if: malloc failure in lookup go up to try */
1490                         /* if: no parent NS in cache - go up one level */
1491                         verbose(VERB_ALGO, "try to grab parent NS");
1492                         iq->store_parent_NS = iq->dp;
1493                         iq->chase_flags &= ~BIT_RD; /* go to authorities */
1494                         iq->deleg_msg = NULL;
1495                         iq->refetch_glue = 1;
1496                         iq->query_restart_count++;
1497                         iq->sent_count = 0;
1498                         return next_state(iq, INIT_REQUEST_STATE);
1499                 }
1500         }
1501         /* see if that makes new names available */
1502         if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 
1503                 qstate->region, iq->dp))
1504                 log_err("out of memory in cache_fill_missing");
1505         if(iq->dp->usable_list) {
1506                 verbose(VERB_ALGO, "try parent-side-name, w. glue from cache");
1507                 return next_state(iq, QUERYTARGETS_STATE);
1508         }
1509         /* try to fill out parent glue from cache */
1510         if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp,
1511                 qstate->region, &qstate->qinfo)) {
1512                 /* got parent stuff from cache, see if we can continue */
1513                 verbose(VERB_ALGO, "try parent-side glue from cache");
1514                 return next_state(iq, QUERYTARGETS_STATE);
1515         }
1516         /* query for an extra name added by the parent-NS record */
1517         if(delegpt_count_missing_targets(iq->dp) > 0) {
1518                 int qs = 0;
1519                 verbose(VERB_ALGO, "try parent-side target name");
1520                 if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) {
1521                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1522                 }
1523                 iq->num_target_queries += qs;
1524                 if(qs != 0) {
1525                         qstate->ext_state[id] = module_wait_subquery;
1526                         return 0; /* and wait for them */
1527                 }
1528         }
1529         if(iq->depth == ie->max_dependency_depth) {
1530                 verbose(VERB_QUERY, "maxdepth and need more nameservers, fail");
1531                 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1532         }
1533         /* mark cycle targets for parent-side lookups */
1534         iter_mark_pside_cycle_targets(qstate, iq->dp);
1535         /* see if we can issue queries to get nameserver addresses */
1536         /* this lookup is not randomized, but sequential. */
1537         for(ns = iq->dp->nslist; ns; ns = ns->next) {
1538                 /* query for parent-side A and AAAA for nameservers */
1539                 if(ie->supports_ipv6 && !ns->done_pside6) {
1540                         /* Send the AAAA request. */
1541                         if(!generate_parentside_target_query(qstate, iq, id, 
1542                                 ns->name, ns->namelen,
1543                                 LDNS_RR_TYPE_AAAA, iq->qchase.qclass))
1544                                 return error_response(qstate, id,
1545                                         LDNS_RCODE_SERVFAIL);
1546                         ns->done_pside6 = 1;
1547                         query_count++;
1548                 }
1549                 if(ie->supports_ipv4 && !ns->done_pside4) {
1550                         /* Send the A request. */
1551                         if(!generate_parentside_target_query(qstate, iq, id, 
1552                                 ns->name, ns->namelen, 
1553                                 LDNS_RR_TYPE_A, iq->qchase.qclass))
1554                                 return error_response(qstate, id,
1555                                         LDNS_RCODE_SERVFAIL);
1556                         ns->done_pside4 = 1;
1557                         query_count++;
1558                 }
1559                 if(query_count != 0) { /* suspend to await results */
1560                         verbose(VERB_ALGO, "try parent-side glue lookup");
1561                         iq->num_target_queries += query_count;
1562                         qstate->ext_state[id] = module_wait_subquery;
1563                         return 0;
1564                 }
1565         }
1566
1567         /* if this was a parent-side glue query itself, then store that
1568          * failure in cache. */
1569         if(iq->query_for_pside_glue && !iq->pside_glue)
1570                 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
1571                         iq->deleg_msg?iq->deleg_msg->rep:
1572                         (iq->response?iq->response->rep:NULL));
1573
1574         verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL");
1575         /* fail -- no more targets, no more hope of targets, no hope 
1576          * of a response. */
1577         return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1578 }
1579
1580 /** 
1581  * Try to find the NS record set that will resolve a qtype DS query. Due
1582  * to grandparent/grandchild reasons we did not get a proper lookup right
1583  * away.  We need to create type NS queries until we get the right parent
1584  * for this lookup.  We remove labels from the query to find the right point.
1585  * If we end up at the old dp name, then there is no solution.
1586  * 
1587  * @param qstate: query state.
1588  * @param iq: iterator query state.
1589  * @param id: module id.
1590  * @return true if the event requires more immediate processing, false if
1591  *         not. This is generally only true when forwarding the request to
1592  *         the final state (i.e., on answer).
1593  */
1594 static int
1595 processDSNSFind(struct module_qstate* qstate, struct iter_qstate* iq, int id)
1596 {
1597         struct module_qstate* subq = NULL;
1598         verbose(VERB_ALGO, "processDSNSFind");
1599
1600         if(!iq->dsns_point) {
1601                 /* initialize */
1602                 iq->dsns_point = iq->qchase.qname;
1603                 iq->dsns_point_len = iq->qchase.qname_len;
1604         }
1605         /* robustcheck for internal error: we are not underneath the dp */
1606         if(!dname_subdomain_c(iq->dsns_point, iq->dp->name)) {
1607                 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1608         }
1609
1610         /* go up one (more) step, until we hit the dp, if so, end */
1611         dname_remove_label(&iq->dsns_point, &iq->dsns_point_len);
1612         if(query_dname_compare(iq->dsns_point, iq->dp->name) == 0) {
1613                 /* there was no inbetween nameserver, use the old delegation
1614                  * point again.  And this time, because dsns_point is nonNULL
1615                  * we are going to accept the (bad) result */
1616                 iq->state = QUERYTARGETS_STATE;
1617                 return 1;
1618         }
1619         iq->state = DSNS_FIND_STATE;
1620
1621         /* spawn NS lookup (validation not needed, this is for DS lookup) */
1622         log_nametypeclass(VERB_ALGO, "fetch nameservers", 
1623                 iq->dsns_point, LDNS_RR_TYPE_NS, iq->qchase.qclass);
1624         if(!generate_sub_request(iq->dsns_point, iq->dsns_point_len, 
1625                 LDNS_RR_TYPE_NS, iq->qchase.qclass, qstate, id, iq,
1626                 INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) {
1627                 return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL);
1628         }
1629
1630         return 0;
1631 }
1632         
1633 /** 
1634  * This is the request event state where the request will be sent to one of
1635  * its current query targets. This state also handles issuing target lookup
1636  * queries for missing target IP addresses. Queries typically iterate on
1637  * this state, both when they are just trying different targets for a given
1638  * delegation point, and when they change delegation points. This state
1639  * roughly corresponds to RFC 1034 algorithm steps 3 and 4.
1640  *
1641  * @param qstate: query state.
1642  * @param iq: iterator query state.
1643  * @param ie: iterator shared global environment.
1644  * @param id: module id.
1645  * @return true if the event requires more request processing immediately,
1646  *         false if not. This state only returns true when it is generating
1647  *         a SERVFAIL response because the query has hit a dead end.
1648  */
1649 static int
1650 processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
1651         struct iter_env* ie, int id)
1652 {
1653         int tf_policy;
1654         struct delegpt_addr* target;
1655         struct outbound_entry* outq;
1656
1657         /* NOTE: a request will encounter this state for each target it 
1658          * needs to send a query to. That is, at least one per referral, 
1659          * more if some targets timeout or return throwaway answers. */
1660
1661         log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
1662         verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
1663                 "currentqueries %d sentcount %d", iq->num_target_queries, 
1664                 iq->num_current_queries, iq->sent_count);
1665
1666         /* Make sure that we haven't run away */
1667         /* FIXME: is this check even necessary? */
1668         if(iq->referral_count > MAX_REFERRAL_COUNT) {
1669                 verbose(VERB_QUERY, "request has exceeded the maximum "
1670                         "number of referrrals with %d", iq->referral_count);
1671                 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1672         }
1673         if(iq->sent_count > MAX_SENT_COUNT) {
1674                 verbose(VERB_QUERY, "request has exceeded the maximum "
1675                         "number of sends with %d", iq->sent_count);
1676                 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1677         }
1678         
1679         /* Make sure we have a delegation point, otherwise priming failed
1680          * or another failure occurred */
1681         if(!iq->dp) {
1682                 verbose(VERB_QUERY, "Failed to get a delegation, giving up");
1683                 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1684         }
1685         if(!ie->supports_ipv6)
1686                 delegpt_no_ipv6(iq->dp);
1687         if(!ie->supports_ipv4)
1688                 delegpt_no_ipv4(iq->dp);
1689         delegpt_log(VERB_ALGO, iq->dp);
1690
1691         if(iq->num_current_queries>0) {
1692                 /* already busy answering a query, this restart is because
1693                  * more delegpt addrs became available, wait for existing
1694                  * query. */
1695                 verbose(VERB_ALGO, "woke up, but wait for outstanding query");
1696                 qstate->ext_state[id] = module_wait_reply;
1697                 return 0;
1698         }
1699
1700         tf_policy = 0;
1701         /* < not <=, because although the array is large enough for <=, the
1702          * generated query will immediately be discarded due to depth and
1703          * that servfail is cached, which is not good as opportunism goes. */
1704         if(iq->depth < ie->max_dependency_depth
1705                 && iq->sent_count < TARGET_FETCH_STOP) {
1706                 tf_policy = ie->target_fetch_policy[iq->depth];
1707         }
1708
1709         /* if in 0x20 fallback get as many targets as possible */
1710         if(iq->caps_fallback) {
1711                 int extra = 0;
1712                 size_t naddr, nres, navail;
1713                 if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
1714                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
1715                 }
1716                 iq->num_target_queries += extra;
1717                 if(iq->num_target_queries > 0) {
1718                         /* wait to get all targets, we want to try em */
1719                         verbose(VERB_ALGO, "wait for all targets for fallback");
1720                         qstate->ext_state[id] = module_wait_reply;
1721                         return 0;
1722                 }
1723                 /* did we do enough fallback queries already? */
1724                 delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
1725                 /* the current caps_server is the number of fallbacks sent.
1726                  * the original query is one that matched too, so we have
1727                  * caps_server+1 number of matching queries now */
1728                 if(iq->caps_server+1 >= naddr*3 ||
1729                         iq->caps_server+1 >= MAX_SENT_COUNT) {
1730                         /* we're done, process the response */
1731                         verbose(VERB_ALGO, "0x20 fallback had %d responses "
1732                                 "match for %d wanted, done.", 
1733                                 (int)iq->caps_server+1, (int)naddr*3);
1734                         iq->caps_fallback = 0;
1735                         iter_dec_attempts(iq->dp, 3); /* space for fallback */
1736                         iq->num_current_queries++; /* RespState decrements it*/
1737                         iq->referral_count++; /* make sure we don't loop */
1738                         iq->sent_count = 0;
1739                         iq->state = QUERY_RESP_STATE;
1740                         return 1;
1741                 }
1742                 verbose(VERB_ALGO, "0x20 fallback number %d", 
1743                         (int)iq->caps_server);
1744
1745         /* if there is a policy to fetch missing targets 
1746          * opportunistically, do it. we rely on the fact that once a 
1747          * query (or queries) for a missing name have been issued, 
1748          * they will not show up again. */
1749         } else if(tf_policy != 0) {
1750                 int extra = 0;
1751                 verbose(VERB_ALGO, "attempt to get extra %d targets", 
1752                         tf_policy);
1753                 (void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
1754                 /* errors ignored, these targets are not strictly necessary for
1755                  * this result, we do not have to reply with SERVFAIL */
1756                 iq->num_target_queries += extra;
1757         }
1758
1759         /* Add the current set of unused targets to our queue. */
1760         delegpt_add_unused_targets(iq->dp);
1761
1762         /* Select the next usable target, filtering out unsuitable targets. */
1763         target = iter_server_selection(ie, qstate->env, iq->dp, 
1764                 iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
1765                 &iq->dnssec_lame_query, &iq->chase_to_rd, 
1766                 iq->num_target_queries, qstate->blacklist);
1767
1768         /* If no usable target was selected... */
1769         if(!target) {
1770                 /* Here we distinguish between three states: generate a new 
1771                  * target query, just wait, or quit (with a SERVFAIL).
1772                  * We have the following information: number of active 
1773                  * target queries, number of active current queries, 
1774                  * the presence of missing targets at this delegation 
1775                  * point, and the given query target policy. */
1776                 
1777                 /* Check for the wait condition. If this is true, then 
1778                  * an action must be taken. */
1779                 if(iq->num_target_queries==0 && iq->num_current_queries==0) {
1780                         /* If there is nothing to wait for, then we need 
1781                          * to distinguish between generating (a) new target 
1782                          * query, or failing. */
1783                         if(delegpt_count_missing_targets(iq->dp) > 0) {
1784                                 int qs = 0;
1785                                 verbose(VERB_ALGO, "querying for next "
1786                                         "missing target");
1787                                 if(!query_for_targets(qstate, iq, ie, id, 
1788                                         1, &qs)) {
1789                                         return error_response(qstate, id,
1790                                                 LDNS_RCODE_SERVFAIL);
1791                                 }
1792                                 if(qs == 0 && 
1793                                    delegpt_count_missing_targets(iq->dp) == 0){
1794                                         /* it looked like there were missing
1795                                          * targets, but they did not turn up.
1796                                          * Try the bad choices again (if any),
1797                                          * when we get back here missing==0,
1798                                          * so this is not a loop. */
1799                                         return 1;
1800                                 }
1801                                 iq->num_target_queries += qs;
1802                         }
1803                         /* Since a target query might have been made, we 
1804                          * need to check again. */
1805                         if(iq->num_target_queries == 0) {
1806                                 return processLastResort(qstate, iq, ie, id);
1807                         }
1808                 }
1809
1810                 /* otherwise, we have no current targets, so submerge 
1811                  * until one of the target or direct queries return. */
1812                 if(iq->num_target_queries>0 && iq->num_current_queries>0) {
1813                         verbose(VERB_ALGO, "no current targets -- waiting "
1814                                 "for %d targets to resolve or %d outstanding"
1815                                 " queries to respond", iq->num_target_queries, 
1816                                 iq->num_current_queries);
1817                         qstate->ext_state[id] = module_wait_reply;
1818                 } else if(iq->num_target_queries>0) {
1819                         verbose(VERB_ALGO, "no current targets -- waiting "
1820                                 "for %d targets to resolve.",
1821                                 iq->num_target_queries);
1822                         qstate->ext_state[id] = module_wait_subquery;
1823                 } else {
1824                         verbose(VERB_ALGO, "no current targets -- waiting "
1825                                 "for %d outstanding queries to respond.",
1826                                 iq->num_current_queries);
1827                         qstate->ext_state[id] = module_wait_reply;
1828                 }
1829                 return 0;
1830         }
1831
1832         /* We have a valid target. */
1833         if(verbosity >= VERB_QUERY) {
1834                 log_query_info(VERB_QUERY, "sending query:", &iq->qchase);
1835                 log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name, 
1836                         &target->addr, target->addrlen);
1837                 verbose(VERB_ALGO, "dnssec status: %s%s",
1838                         iq->dnssec_expected?"expected": "not expected",
1839                         iq->dnssec_lame_query?" but lame_query anyway": "");
1840         }
1841         fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
1842         outq = (*qstate->env->send_query)(
1843                 iq->qchase.qname, iq->qchase.qname_len, 
1844                 iq->qchase.qtype, iq->qchase.qclass, 
1845                 iq->chase_flags | (iq->chase_to_rd?BIT_RD:0), EDNS_DO|BIT_CD, 
1846                 iq->dnssec_expected, &target->addr, target->addrlen,
1847                 iq->dp->name, iq->dp->namelen, qstate);
1848         if(!outq) {
1849                 log_addr(VERB_DETAIL, "error sending query to auth server", 
1850                         &target->addr, target->addrlen);
1851                 return next_state(iq, QUERYTARGETS_STATE);
1852         }
1853         outbound_list_insert(&iq->outlist, outq);
1854         iq->num_current_queries++;
1855         iq->sent_count++;
1856         qstate->ext_state[id] = module_wait_reply;
1857
1858         return 0;
1859 }
1860
1861 /** find NS rrset in given list */
1862 static struct ub_packed_rrset_key*
1863 find_NS(struct reply_info* rep, size_t from, size_t to)
1864 {
1865         size_t i;
1866         for(i=from; i<to; i++) {
1867                 if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
1868                         return rep->rrsets[i];
1869         }
1870         return NULL;
1871 }
1872
1873
1874 /** 
1875  * Process the query response. All queries end up at this state first. This
1876  * process generally consists of analyzing the response and routing the
1877  * event to the next state (either bouncing it back to a request state, or
1878  * terminating the processing for this event).
1879  * 
1880  * @param qstate: query state.
1881  * @param iq: iterator query state.
1882  * @param id: module id.
1883  * @return true if the event requires more immediate processing, false if
1884  *         not. This is generally only true when forwarding the request to
1885  *         the final state (i.e., on answer).
1886  */
1887 static int
1888 processQueryResponse(struct module_qstate* qstate, struct iter_qstate* iq,
1889         int id)
1890 {
1891         int dnsseclame = 0;
1892         enum response_type type;
1893         iq->num_current_queries--;
1894         if(iq->response == NULL) {
1895                 iq->chase_to_rd = 0;
1896                 iq->dnssec_lame_query = 0;
1897                 verbose(VERB_ALGO, "query response was timeout");
1898                 return next_state(iq, QUERYTARGETS_STATE);
1899         }
1900         type = response_type_from_server(
1901                 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd),
1902                 iq->response, &iq->qchase, iq->dp);
1903         iq->chase_to_rd = 0;
1904         if(type == RESPONSE_TYPE_REFERRAL && (iq->chase_flags&BIT_RD)) {
1905                 /* When forwarding (RD bit is set), we handle referrals 
1906                  * differently. No queries should be sent elsewhere */
1907                 type = RESPONSE_TYPE_ANSWER;
1908         }
1909         if(iq->dnssec_expected && !iq->dnssec_lame_query &&
1910                 !(iq->chase_flags&BIT_RD) 
1911                 && type != RESPONSE_TYPE_LAME 
1912                 && type != RESPONSE_TYPE_REC_LAME 
1913                 && type != RESPONSE_TYPE_THROWAWAY 
1914                 && type != RESPONSE_TYPE_UNTYPED) {
1915                 /* a possible answer, see if it is missing DNSSEC */
1916                 /* but not when forwarding, so we dont mark fwder lame */
1917                 if(!iter_msg_has_dnssec(iq->response)) {
1918                         /* Mark this address as dnsseclame in this dp,
1919                          * because that will make serverselection disprefer
1920                          * it, but also, once it is the only final option,
1921                          * use dnssec-lame-bypass if it needs to query there.*/
1922                         if(qstate->reply) {
1923                                 struct delegpt_addr* a = delegpt_find_addr(
1924                                         iq->dp, &qstate->reply->addr,
1925                                         qstate->reply->addrlen);
1926                                 if(a) a->dnsseclame = 1;
1927                         }
1928                         /* test the answer is from the zone we expected,
1929                          * otherwise, (due to parent,child on same server), we
1930                          * might mark the server,zone lame inappropriately */
1931                         if(!iter_msg_from_zone(iq->response, iq->dp, type,
1932                                 iq->qchase.qclass))
1933                                 qstate->reply = NULL;
1934                         type = RESPONSE_TYPE_LAME;
1935                         dnsseclame = 1;
1936                 }
1937         } else iq->dnssec_lame_query = 0;
1938         /* see if referral brings us close to the target */
1939         if(type == RESPONSE_TYPE_REFERRAL) {
1940                 struct ub_packed_rrset_key* ns = find_NS(
1941                         iq->response->rep, iq->response->rep->an_numrrsets,
1942                         iq->response->rep->an_numrrsets 
1943                         + iq->response->rep->ns_numrrsets);
1944                 if(!ns) ns = find_NS(iq->response->rep, 0, 
1945                                 iq->response->rep->an_numrrsets);
1946                 if(!ns || !dname_strict_subdomain_c(ns->rk.dname, iq->dp->name) 
1947                         || !dname_subdomain_c(iq->qchase.qname, ns->rk.dname)){
1948                         verbose(VERB_ALGO, "bad referral, throwaway");
1949                         type = RESPONSE_TYPE_THROWAWAY;
1950                 } else
1951                         iter_scrub_ds(iq->response, ns, iq->dp->name);
1952         } else iter_scrub_ds(iq->response, NULL, NULL);
1953
1954         /* handle each of the type cases */
1955         if(type == RESPONSE_TYPE_ANSWER) {
1956                 /* ANSWER type responses terminate the query algorithm, 
1957                  * so they sent on their */
1958                 if(verbosity >= VERB_DETAIL) {
1959                         verbose(VERB_DETAIL, "query response was %s",
1960                                 FLAGS_GET_RCODE(iq->response->rep->flags)
1961                                 ==LDNS_RCODE_NXDOMAIN?"NXDOMAIN ANSWER":
1962                                 (iq->response->rep->an_numrrsets?"ANSWER":
1963                                 "nodata ANSWER"));
1964                 }
1965                 /* if qtype is DS, check we have the right level of answer,
1966                  * like grandchild answer but we need the middle, reject it */
1967                 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
1968                         && !(iq->chase_flags&BIT_RD)
1969                         && iter_ds_toolow(iq->response, iq->dp)
1970                         && iter_dp_cangodown(&iq->qchase, iq->dp)) {
1971                         /* close down outstanding requests to be discarded */
1972                         outbound_list_clear(&iq->outlist);
1973                         iq->num_current_queries = 0;
1974                         fptr_ok(fptr_whitelist_modenv_detach_subs(
1975                                 qstate->env->detach_subs));
1976                         (*qstate->env->detach_subs)(qstate);
1977                         iq->num_target_queries = 0;
1978                         return processDSNSFind(qstate, iq, id);
1979                 }
1980                 iter_dns_store(qstate->env, &iq->response->qinfo,
1981                         iq->response->rep, 0, qstate->prefetch_leeway,
1982                         iq->dp&&iq->dp->has_parent_side_NS,
1983                         qstate->region);
1984                 /* close down outstanding requests to be discarded */
1985                 outbound_list_clear(&iq->outlist);
1986                 iq->num_current_queries = 0;
1987                 fptr_ok(fptr_whitelist_modenv_detach_subs(
1988                         qstate->env->detach_subs));
1989                 (*qstate->env->detach_subs)(qstate);
1990                 iq->num_target_queries = 0;
1991                 if(qstate->reply)
1992                         sock_list_insert(&qstate->reply_origin, 
1993                                 &qstate->reply->addr, qstate->reply->addrlen, 
1994                                 qstate->region);
1995                 return final_state(iq);
1996         } else if(type == RESPONSE_TYPE_REFERRAL) {
1997                 /* REFERRAL type responses get a reset of the 
1998                  * delegation point, and back to the QUERYTARGETS_STATE. */
1999                 verbose(VERB_DETAIL, "query response was REFERRAL");
2000
2001                 /* if hardened, only store referral if we asked for it */
2002                 if(!qstate->env->cfg->harden_referral_path ||
2003                     (  qstate->qinfo.qtype == LDNS_RR_TYPE_NS 
2004                         && (qstate->query_flags&BIT_RD) 
2005                         && !(qstate->query_flags&BIT_CD)
2006                            /* we know that all other NS rrsets are scrubbed
2007                             * away, thus on referral only one is left.
2008                             * see if that equals the query name... */
2009                         && ( /* auth section, but sometimes in answer section*/
2010                           reply_find_rrset_section_ns(iq->response->rep,
2011                                 iq->qchase.qname, iq->qchase.qname_len,
2012                                 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2013                           || reply_find_rrset_section_an(iq->response->rep,
2014                                 iq->qchase.qname, iq->qchase.qname_len,
2015                                 LDNS_RR_TYPE_NS, iq->qchase.qclass)
2016                           )
2017                     )) {
2018                         /* Store the referral under the current query */
2019                         /* no prefetch-leeway, since its not the answer */
2020                         iter_dns_store(qstate->env, &iq->response->qinfo,
2021                                 iq->response->rep, 1, 0, 0, NULL);
2022                         if(iq->store_parent_NS)
2023                                 iter_store_parentside_NS(qstate->env, 
2024                                         iq->response->rep);
2025                         if(qstate->env->neg_cache)
2026                                 val_neg_addreferral(qstate->env->neg_cache, 
2027                                         iq->response->rep, iq->dp->name);
2028                 }
2029                 /* store parent-side-in-zone-glue, if directly queried for */
2030                 if(iq->query_for_pside_glue && !iq->pside_glue) {
2031                         iq->pside_glue = reply_find_rrset(iq->response->rep, 
2032                                 iq->qchase.qname, iq->qchase.qname_len, 
2033                                 iq->qchase.qtype, iq->qchase.qclass);
2034                         if(iq->pside_glue) {
2035                                 log_rrset_key(VERB_ALGO, "found parent-side "
2036                                         "glue", iq->pside_glue);
2037                                 iter_store_parentside_rrset(qstate->env,
2038                                         iq->pside_glue);
2039                         }
2040                 }
2041
2042                 /* Reset the event state, setting the current delegation 
2043                  * point to the referral. */
2044                 iq->deleg_msg = iq->response;
2045                 iq->dp = delegpt_from_message(iq->response, qstate->region);
2046                 if(!iq->dp)
2047                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2048                 if(!cache_fill_missing(qstate->env, iq->qchase.qclass, 
2049                         qstate->region, iq->dp))
2050                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2051                 if(iq->store_parent_NS && query_dname_compare(iq->dp->name,
2052                         iq->store_parent_NS->name) == 0)
2053                         iter_merge_retry_counts(iq->dp, iq->store_parent_NS);
2054                 delegpt_log(VERB_ALGO, iq->dp);
2055                 /* Count this as a referral. */
2056                 iq->referral_count++;
2057                 iq->sent_count = 0;
2058                 /* see if the next dp is a trust anchor, or a DS was sent
2059                  * along, indicating dnssec is expected for next zone */
2060                 iq->dnssec_expected = iter_indicates_dnssec(qstate->env, 
2061                         iq->dp, iq->response, iq->qchase.qclass);
2062                 /* if dnssec, validating then also fetch the key for the DS */
2063                 if(iq->dnssec_expected && qstate->env->cfg->prefetch_key &&
2064                         !(qstate->query_flags&BIT_CD))
2065                         generate_dnskey_prefetch(qstate, iq, id);
2066
2067                 /* spawn off NS and addr to auth servers for the NS we just
2068                  * got in the referral. This gets authoritative answer
2069                  * (answer section trust level) rrset. 
2070                  * right after, we detach the subs, answer goes to cache. */
2071                 if(qstate->env->cfg->harden_referral_path)
2072                         generate_ns_check(qstate, iq, id);
2073
2074                 /* stop current outstanding queries. 
2075                  * FIXME: should the outstanding queries be waited for and
2076                  * handled? Say by a subquery that inherits the outbound_entry.
2077                  */
2078                 outbound_list_clear(&iq->outlist);
2079                 iq->num_current_queries = 0;
2080                 fptr_ok(fptr_whitelist_modenv_detach_subs(
2081                         qstate->env->detach_subs));
2082                 (*qstate->env->detach_subs)(qstate);
2083                 iq->num_target_queries = 0;
2084                 verbose(VERB_ALGO, "cleared outbound list for next round");
2085                 return next_state(iq, QUERYTARGETS_STATE);
2086         } else if(type == RESPONSE_TYPE_CNAME) {
2087                 uint8_t* sname = NULL;
2088                 size_t snamelen = 0;
2089                 /* CNAME type responses get a query restart (i.e., get a 
2090                  * reset of the query state and go back to INIT_REQUEST_STATE).
2091                  */
2092                 verbose(VERB_DETAIL, "query response was CNAME");
2093                 if(verbosity >= VERB_ALGO)
2094                         log_dns_msg("cname msg", &iq->response->qinfo, 
2095                                 iq->response->rep);
2096                 /* if qtype is DS, check we have the right level of answer,
2097                  * like grandchild answer but we need the middle, reject it */
2098                 if(iq->qchase.qtype == LDNS_RR_TYPE_DS && !iq->dsns_point
2099                         && !(iq->chase_flags&BIT_RD)
2100                         && iter_ds_toolow(iq->response, iq->dp)
2101                         && iter_dp_cangodown(&iq->qchase, iq->dp)) {
2102                         outbound_list_clear(&iq->outlist);
2103                         iq->num_current_queries = 0;
2104                         fptr_ok(fptr_whitelist_modenv_detach_subs(
2105                                 qstate->env->detach_subs));
2106                         (*qstate->env->detach_subs)(qstate);
2107                         iq->num_target_queries = 0;
2108                         return processDSNSFind(qstate, iq, id);
2109                 }
2110                 /* Process the CNAME response. */
2111                 if(!handle_cname_response(qstate, iq, iq->response, 
2112                         &sname, &snamelen))
2113                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2114                 /* cache the CNAME response under the current query */
2115                 /* NOTE : set referral=1, so that rrsets get stored but not 
2116                  * the partial query answer (CNAME only). */
2117                 /* prefetchleeway applied because this updates answer parts */
2118                 iter_dns_store(qstate->env, &iq->response->qinfo,
2119                         iq->response->rep, 1, qstate->prefetch_leeway,
2120                         iq->dp&&iq->dp->has_parent_side_NS, NULL);
2121                 /* set the current request's qname to the new value. */
2122                 iq->qchase.qname = sname;
2123                 iq->qchase.qname_len = snamelen;
2124                 /* Clear the query state, since this is a query restart. */
2125                 iq->deleg_msg = NULL;
2126                 iq->dp = NULL;
2127                 iq->dsns_point = NULL;
2128                 /* Note the query restart. */
2129                 iq->query_restart_count++;
2130                 iq->sent_count = 0;
2131
2132                 /* stop current outstanding queries. 
2133                  * FIXME: should the outstanding queries be waited for and
2134                  * handled? Say by a subquery that inherits the outbound_entry.
2135                  */
2136                 outbound_list_clear(&iq->outlist);
2137                 iq->num_current_queries = 0;
2138                 fptr_ok(fptr_whitelist_modenv_detach_subs(
2139                         qstate->env->detach_subs));
2140                 (*qstate->env->detach_subs)(qstate);
2141                 iq->num_target_queries = 0;
2142                 if(qstate->reply)
2143                         sock_list_insert(&qstate->reply_origin, 
2144                                 &qstate->reply->addr, qstate->reply->addrlen, 
2145                                 qstate->region);
2146                 verbose(VERB_ALGO, "cleared outbound list for query restart");
2147                 /* go to INIT_REQUEST_STATE for new qname. */
2148                 return next_state(iq, INIT_REQUEST_STATE);
2149         } else if(type == RESPONSE_TYPE_LAME) {
2150                 /* Cache the LAMEness. */
2151                 verbose(VERB_DETAIL, "query response was %sLAME",
2152                         dnsseclame?"DNSSEC ":"");
2153                 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2154                         log_err("mark lame: mismatch in qname and dpname");
2155                         /* throwaway this reply below */
2156                 } else if(qstate->reply) {
2157                         /* need addr for lameness cache, but we may have
2158                          * gotten this from cache, so test to be sure */
2159                         if(!infra_set_lame(qstate->env->infra_cache, 
2160                                 &qstate->reply->addr, qstate->reply->addrlen, 
2161                                 iq->dp->name, iq->dp->namelen, 
2162                                 *qstate->env->now, dnsseclame, 0,
2163                                 iq->qchase.qtype))
2164                                 log_err("mark host lame: out of memory");
2165                 }
2166         } else if(type == RESPONSE_TYPE_REC_LAME) {
2167                 /* Cache the LAMEness. */
2168                 verbose(VERB_DETAIL, "query response REC_LAME: "
2169                         "recursive but not authoritative server");
2170                 if(!dname_subdomain_c(iq->qchase.qname, iq->dp->name)) {
2171                         log_err("mark rec_lame: mismatch in qname and dpname");
2172                         /* throwaway this reply below */
2173                 } else if(qstate->reply) {
2174                         /* need addr for lameness cache, but we may have
2175                          * gotten this from cache, so test to be sure */
2176                         verbose(VERB_DETAIL, "mark as REC_LAME");
2177                         if(!infra_set_lame(qstate->env->infra_cache, 
2178                                 &qstate->reply->addr, qstate->reply->addrlen, 
2179                                 iq->dp->name, iq->dp->namelen, 
2180                                 *qstate->env->now, 0, 1, iq->qchase.qtype))
2181                                 log_err("mark host lame: out of memory");
2182                 } 
2183         } else if(type == RESPONSE_TYPE_THROWAWAY) {
2184                 /* LAME and THROWAWAY responses are handled the same way. 
2185                  * In this case, the event is just sent directly back to 
2186                  * the QUERYTARGETS_STATE without resetting anything, 
2187                  * because, clearly, the next target must be tried. */
2188                 verbose(VERB_DETAIL, "query response was THROWAWAY");
2189         } else {
2190                 log_warn("A query response came back with an unknown type: %d",
2191                         (int)type);
2192         }
2193
2194         /* LAME, THROWAWAY and "unknown" all end up here.
2195          * Recycle to the QUERYTARGETS state to hopefully try a 
2196          * different target. */
2197         return next_state(iq, QUERYTARGETS_STATE);
2198 }
2199
2200 /**
2201  * Return priming query results to interestes super querystates.
2202  * 
2203  * Sets the delegation point and delegation message (not nonRD queries).
2204  * This is a callback from walk_supers.
2205  *
2206  * @param qstate: priming query state that finished.
2207  * @param id: module id.
2208  * @param forq: the qstate for which priming has been done.
2209  */
2210 static void
2211 prime_supers(struct module_qstate* qstate, int id, struct module_qstate* forq)
2212 {
2213         struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2214         struct delegpt* dp = NULL;
2215
2216         log_assert(qstate->is_priming || foriq->wait_priming_stub);
2217         log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2218         /* Convert our response to a delegation point */
2219         dp = delegpt_from_message(qstate->return_msg, forq->region);
2220         if(!dp) {
2221                 /* if there is no convertable delegation point, then 
2222                  * the ANSWER type was (presumably) a negative answer. */
2223                 verbose(VERB_ALGO, "prime response was not a positive "
2224                         "ANSWER; failing");
2225                 foriq->dp = NULL;
2226                 foriq->state = QUERYTARGETS_STATE;
2227                 return;
2228         }
2229
2230         log_query_info(VERB_DETAIL, "priming successful for", &qstate->qinfo);
2231         delegpt_log(VERB_ALGO, dp);
2232         foriq->dp = dp;
2233         foriq->deleg_msg = dns_copy_msg(qstate->return_msg, forq->region);
2234         if(!foriq->deleg_msg) {
2235                 log_err("copy prime response: out of memory");
2236                 foriq->dp = NULL;
2237                 foriq->state = QUERYTARGETS_STATE;
2238                 return;
2239         }
2240
2241         /* root priming responses go to init stage 2, priming stub 
2242          * responses to to stage 3. */
2243         if(foriq->wait_priming_stub) {
2244                 foriq->state = INIT_REQUEST_3_STATE;
2245                 foriq->wait_priming_stub = 0;
2246         } else  foriq->state = INIT_REQUEST_2_STATE;
2247         /* because we are finished, the parent will be reactivated */
2248 }
2249
2250 /** 
2251  * This handles the response to a priming query. This is used to handle both
2252  * root and stub priming responses. This is basically the equivalent of the
2253  * QUERY_RESP_STATE, but will not handle CNAME responses and will treat
2254  * REFERRALs as ANSWERS. It will also update and reactivate the originating
2255  * event.
2256  *
2257  * @param qstate: query state.
2258  * @param id: module id.
2259  * @return true if the event needs more immediate processing, false if not.
2260  *         This state always returns false.
2261  */
2262 static int
2263 processPrimeResponse(struct module_qstate* qstate, int id)
2264 {
2265         struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2266         enum response_type type;
2267         iq->response->rep->flags &= ~(BIT_RD|BIT_RA); /* ignore rec-lame */
2268         type = response_type_from_server(
2269                 (int)((iq->chase_flags&BIT_RD) || iq->chase_to_rd), 
2270                 iq->response, &iq->qchase, iq->dp);
2271         if(type == RESPONSE_TYPE_ANSWER) {
2272                 qstate->return_rcode = LDNS_RCODE_NOERROR;
2273                 qstate->return_msg = iq->response;
2274         } else {
2275                 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
2276                 qstate->return_msg = NULL;
2277         }
2278
2279         /* validate the root or stub after priming (if enabled).
2280          * This is the same query as the prime query, but with validation.
2281          * Now that we are primed, the additional queries that validation
2282          * may need can be resolved, such as DLV. */
2283         if(qstate->env->cfg->harden_referral_path) {
2284                 struct module_qstate* subq = NULL;
2285                 log_nametypeclass(VERB_ALGO, "schedule prime validation", 
2286                         qstate->qinfo.qname, qstate->qinfo.qtype,
2287                         qstate->qinfo.qclass);
2288                 if(!generate_sub_request(qstate->qinfo.qname, 
2289                         qstate->qinfo.qname_len, qstate->qinfo.qtype,
2290                         qstate->qinfo.qclass, qstate, id, iq,
2291                         INIT_REQUEST_STATE, FINISHED_STATE, &subq, 1)) {
2292                         verbose(VERB_ALGO, "could not generate prime check");
2293                 }
2294                 generate_a_aaaa_check(qstate, iq, id);
2295         }
2296
2297         /* This event is finished. */
2298         qstate->ext_state[id] = module_finished;
2299         return 0;
2300 }
2301
2302 /** 
2303  * Do final processing on responses to target queries. Events reach this
2304  * state after the iterative resolution algorithm terminates. This state is
2305  * responsible for reactiving the original event, and housekeeping related
2306  * to received target responses (caching, updating the current delegation
2307  * point, etc).
2308  * Callback from walk_supers for every super state that is interested in 
2309  * the results from this query.
2310  *
2311  * @param qstate: query state.
2312  * @param id: module id.
2313  * @param forq: super query state.
2314  */
2315 static void
2316 processTargetResponse(struct module_qstate* qstate, int id,
2317         struct module_qstate* forq)
2318 {
2319         struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2320         struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2321         struct ub_packed_rrset_key* rrset;
2322         struct delegpt_ns* dpns;
2323         log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR);
2324
2325         foriq->state = QUERYTARGETS_STATE;
2326         log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo);
2327         log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo);
2328
2329         /* check to see if parent event is still interested (in orig name).  */
2330         if(!foriq->dp) {
2331                 verbose(VERB_ALGO, "subq: parent not interested, was reset");
2332                 return; /* not interested anymore */
2333         }
2334         dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname,
2335                         qstate->qinfo.qname_len);
2336         if(!dpns) {
2337                 /* If not interested, just stop processing this event */
2338                 verbose(VERB_ALGO, "subq: parent not interested anymore");
2339                 /* could be because parent was jostled out of the cache,
2340                    and a new identical query arrived, that does not want it*/
2341                 return;
2342         }
2343
2344         /* Tell the originating event that this target query has finished
2345          * (regardless if it succeeded or not). */
2346         foriq->num_target_queries--;
2347
2348         /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */
2349         if(iq->pside_glue) {
2350                 /* if the pside_glue is NULL, then it could not be found,
2351                  * the done_pside is already set when created and a cache
2352                  * entry created in processFinished so nothing to do here */
2353                 log_rrset_key(VERB_ALGO, "add parentside glue to dp", 
2354                         iq->pside_glue);
2355                 if(!delegpt_add_rrset(foriq->dp, forq->region, 
2356                         iq->pside_glue, 1))
2357                         log_err("out of memory adding pside glue");
2358         }
2359
2360         /* This response is relevant to the current query, so we 
2361          * add (attempt to add, anyway) this target(s) and reactivate 
2362          * the original event. 
2363          * NOTE: we could only look for the AnswerRRset if the 
2364          * response type was ANSWER. */
2365         rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep);
2366         if(rrset) {
2367                 /* if CNAMEs have been followed - add new NS to delegpt. */
2368                 /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */
2369                 if(!delegpt_find_ns(foriq->dp, rrset->rk.dname, 
2370                         rrset->rk.dname_len)) {
2371                         /* if dpns->lame then set newcname ns lame too */
2372                         if(!delegpt_add_ns(foriq->dp, forq->region, 
2373                                 rrset->rk.dname, dpns->lame))
2374                                 log_err("out of memory adding cnamed-ns");
2375                 }
2376                 /* if dpns->lame then set the address(es) lame too */
2377                 if(!delegpt_add_rrset(foriq->dp, forq->region, rrset, 
2378                         dpns->lame))
2379                         log_err("out of memory adding targets");
2380                 verbose(VERB_ALGO, "added target response");
2381                 delegpt_log(VERB_ALGO, foriq->dp);
2382         } else {
2383                 verbose(VERB_ALGO, "iterator TargetResponse failed");
2384                 dpns->resolved = 1; /* fail the target */
2385         }
2386 }
2387
2388 /**
2389  * Process response for DS NS Find queries, that attempt to find the delegation
2390  * point where we ask the DS query from.
2391  *
2392  * @param qstate: query state.
2393  * @param id: module id.
2394  * @param forq: super query state.
2395  */
2396 static void
2397 processDSNSResponse(struct module_qstate* qstate, int id,
2398         struct module_qstate* forq)
2399 {
2400         struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2401
2402         /* if the finished (iq->response) query has no NS set: continue
2403          * up to look for the right dp; nothing to change, do DPNSstate */
2404         if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2405                 return; /* seek further */
2406         /* find the NS RRset (without allowing CNAMEs) */
2407         if(!reply_find_rrset(qstate->return_msg->rep, qstate->qinfo.qname,
2408                 qstate->qinfo.qname_len, LDNS_RR_TYPE_NS,
2409                 qstate->qinfo.qclass)){
2410                 return; /* seek further */
2411         }
2412
2413         /* else, store as DP and continue at querytargets */
2414         foriq->state = QUERYTARGETS_STATE;
2415         foriq->dp = delegpt_from_message(qstate->return_msg, forq->region);
2416         if(!foriq->dp) {
2417                 log_err("out of memory in dsns dp alloc");
2418                 return; /* dp==NULL in QUERYTARGETS makes SERVFAIL */
2419         }
2420         /* success, go query the querytargets in the new dp (and go down) */
2421 }
2422
2423 /**
2424  * Process response for qclass=ANY queries for a particular class.
2425  * Append to result or error-exit.
2426  *
2427  * @param qstate: query state.
2428  * @param id: module id.
2429  * @param forq: super query state.
2430  */
2431 static void
2432 processClassResponse(struct module_qstate* qstate, int id,
2433         struct module_qstate* forq)
2434 {
2435         struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id];
2436         struct dns_msg* from = qstate->return_msg;
2437         log_query_info(VERB_ALGO, "processClassResponse", &qstate->qinfo);
2438         log_query_info(VERB_ALGO, "processClassResponse super", &forq->qinfo);
2439         if(qstate->return_rcode != LDNS_RCODE_NOERROR) {
2440                 /* cause servfail for qclass ANY query */
2441                 foriq->response = NULL;
2442                 foriq->state = FINISHED_STATE;
2443                 return;
2444         }
2445         /* append result */
2446         if(!foriq->response) {
2447                 /* allocate the response: copy RCODE, sec_state */
2448                 foriq->response = dns_copy_msg(from, forq->region);
2449                 if(!foriq->response) {
2450                         log_err("malloc failed for qclass ANY response"); 
2451                         foriq->state = FINISHED_STATE;
2452                         return;
2453                 }
2454                 foriq->response->qinfo.qclass = forq->qinfo.qclass;
2455                 /* qclass ANY does not receive the AA flag on replies */
2456                 foriq->response->rep->authoritative = 0; 
2457         } else {
2458                 struct dns_msg* to = foriq->response;
2459                 /* add _from_ this response _to_ existing collection */
2460                 /* if there are records, copy RCODE */
2461                 /* lower sec_state if this message is lower */
2462                 if(from->rep->rrset_count != 0) {
2463                         size_t n = from->rep->rrset_count+to->rep->rrset_count;
2464                         struct ub_packed_rrset_key** dest, **d;
2465                         /* copy appropriate rcode */
2466                         to->rep->flags = from->rep->flags;
2467                         /* copy rrsets */
2468                         dest = regional_alloc(forq->region, sizeof(dest[0])*n);
2469                         if(!dest) {
2470                                 log_err("malloc failed in collect ANY"); 
2471                                 foriq->state = FINISHED_STATE;
2472                                 return;
2473                         }
2474                         d = dest;
2475                         /* copy AN */
2476                         memcpy(dest, to->rep->rrsets, to->rep->an_numrrsets
2477                                 * sizeof(dest[0]));
2478                         dest += to->rep->an_numrrsets;
2479                         memcpy(dest, from->rep->rrsets, from->rep->an_numrrsets
2480                                 * sizeof(dest[0]));
2481                         dest += from->rep->an_numrrsets;
2482                         /* copy NS */
2483                         memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets,
2484                                 to->rep->ns_numrrsets * sizeof(dest[0]));
2485                         dest += to->rep->ns_numrrsets;
2486                         memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets,
2487                                 from->rep->ns_numrrsets * sizeof(dest[0]));
2488                         dest += from->rep->ns_numrrsets;
2489                         /* copy AR */
2490                         memcpy(dest, to->rep->rrsets+to->rep->an_numrrsets+
2491                                 to->rep->ns_numrrsets,
2492                                 to->rep->ar_numrrsets * sizeof(dest[0]));
2493                         dest += to->rep->ar_numrrsets;
2494                         memcpy(dest, from->rep->rrsets+from->rep->an_numrrsets+
2495                                 from->rep->ns_numrrsets,
2496                                 from->rep->ar_numrrsets * sizeof(dest[0]));
2497                         /* update counts */
2498                         to->rep->rrsets = d;
2499                         to->rep->an_numrrsets += from->rep->an_numrrsets;
2500                         to->rep->ns_numrrsets += from->rep->ns_numrrsets;
2501                         to->rep->ar_numrrsets += from->rep->ar_numrrsets;
2502                         to->rep->rrset_count = n;
2503                 }
2504                 if(from->rep->security < to->rep->security) /* lowest sec */
2505                         to->rep->security = from->rep->security;
2506                 if(from->rep->qdcount != 0) /* insert qd if appropriate */
2507                         to->rep->qdcount = from->rep->qdcount;
2508                 if(from->rep->ttl < to->rep->ttl) /* use smallest TTL */
2509                         to->rep->ttl = from->rep->ttl;
2510                 if(from->rep->prefetch_ttl < to->rep->prefetch_ttl)
2511                         to->rep->prefetch_ttl = from->rep->prefetch_ttl;
2512         }
2513         /* are we done? */
2514         foriq->num_current_queries --;
2515         if(foriq->num_current_queries == 0)
2516                 foriq->state = FINISHED_STATE;
2517 }
2518         
2519 /** 
2520  * Collect class ANY responses and make them into one response.  This
2521  * state is started and it creates queries for all classes (that have
2522  * root hints).  The answers are then collected.
2523  *
2524  * @param qstate: query state.
2525  * @param id: module id.
2526  * @return true if the event needs more immediate processing, false if not.
2527  */
2528 static int
2529 processCollectClass(struct module_qstate* qstate, int id)
2530 {
2531         struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2532         struct module_qstate* subq;
2533         /* If qchase.qclass == 0 then send out queries for all classes.
2534          * Otherwise, do nothing (wait for all answers to arrive and the
2535          * processClassResponse to put them together, and that moves us
2536          * towards the Finished state when done. */
2537         if(iq->qchase.qclass == 0) {
2538                 uint16_t c = 0;
2539                 iq->qchase.qclass = LDNS_RR_CLASS_ANY;
2540                 while(iter_get_next_root(qstate->env->hints,
2541                         qstate->env->fwds, &c)) {
2542                         /* generate query for this class */
2543                         log_nametypeclass(VERB_ALGO, "spawn collect query",
2544                                 qstate->qinfo.qname, qstate->qinfo.qtype, c);
2545                         if(!generate_sub_request(qstate->qinfo.qname,
2546                                 qstate->qinfo.qname_len, qstate->qinfo.qtype,
2547                                 c, qstate, id, iq, INIT_REQUEST_STATE,
2548                                 FINISHED_STATE, &subq, 
2549                                 (int)!(qstate->query_flags&BIT_CD))) {
2550                                 return error_response(qstate, id, 
2551                                         LDNS_RCODE_SERVFAIL);
2552                         }
2553                         /* ignore subq, no special init required */
2554                         iq->num_current_queries ++;
2555                         if(c == 0xffff)
2556                                 break;
2557                         else c++;
2558                 }
2559                 /* if no roots are configured at all, return */
2560                 if(iq->num_current_queries == 0) {
2561                         verbose(VERB_ALGO, "No root hints or fwds, giving up "
2562                                 "on qclass ANY");
2563                         return error_response(qstate, id, LDNS_RCODE_REFUSED);
2564                 }
2565                 /* return false, wait for queries to return */
2566         }
2567         /* if woke up here because of an answer, wait for more answers */
2568         return 0;
2569 }
2570
2571 /** 
2572  * This handles the final state for first-tier responses (i.e., responses to
2573  * externally generated queries).
2574  *
2575  * @param qstate: query state.
2576  * @param iq: iterator query state.
2577  * @param id: module id.
2578  * @return true if the event needs more processing, false if not. Since this
2579  *         is the final state for an event, it always returns false.
2580  */
2581 static int
2582 processFinished(struct module_qstate* qstate, struct iter_qstate* iq,
2583         int id)
2584 {
2585         log_query_info(VERB_QUERY, "finishing processing for", 
2586                 &qstate->qinfo);
2587
2588         /* store negative cache element for parent side glue. */
2589         if(iq->query_for_pside_glue && !iq->pside_glue)
2590                 iter_store_parentside_neg(qstate->env, &qstate->qinfo,
2591                         iq->deleg_msg?iq->deleg_msg->rep:
2592                         (iq->response?iq->response->rep:NULL));
2593         if(!iq->response) {
2594                 verbose(VERB_ALGO, "No response is set, servfail");
2595                 return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2596         }
2597
2598         /* Make sure that the RA flag is set (since the presence of 
2599          * this module means that recursion is available) */
2600         iq->response->rep->flags |= BIT_RA;
2601
2602         /* Clear the AA flag */
2603         /* FIXME: does this action go here or in some other module? */
2604         iq->response->rep->flags &= ~BIT_AA;
2605
2606         /* make sure QR flag is on */
2607         iq->response->rep->flags |= BIT_QR;
2608
2609         /* we have finished processing this query */
2610         qstate->ext_state[id] = module_finished;
2611
2612         /* TODO:  we are using a private TTL, trim the response. */
2613         /* if (mPrivateTTL > 0){IterUtils.setPrivateTTL(resp, mPrivateTTL); } */
2614
2615         /* prepend any items we have accumulated */
2616         if(iq->an_prepend_list || iq->ns_prepend_list) {
2617                 if(!iter_prepend(iq, iq->response, qstate->region)) {
2618                         log_err("prepend rrsets: out of memory");
2619                         return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2620                 }
2621                 /* reset the query name back */
2622                 iq->response->qinfo = qstate->qinfo;
2623                 /* the security state depends on the combination */
2624                 iq->response->rep->security = sec_status_unchecked;
2625                 /* store message with the finished prepended items,
2626                  * but only if we did recursion. The nonrecursion referral
2627                  * from cache does not need to be stored in the msg cache. */
2628                 if(qstate->query_flags&BIT_RD) {
2629                         iter_dns_store(qstate->env, &qstate->qinfo, 
2630                                 iq->response->rep, 0, qstate->prefetch_leeway,
2631                                 iq->dp&&iq->dp->has_parent_side_NS,
2632                                 qstate->region);
2633                 }
2634         }
2635         qstate->return_rcode = LDNS_RCODE_NOERROR;
2636         qstate->return_msg = iq->response;
2637         return 0;
2638 }
2639
2640 /*
2641  * Return priming query results to interestes super querystates.
2642  * 
2643  * Sets the delegation point and delegation message (not nonRD queries).
2644  * This is a callback from walk_supers.
2645  *
2646  * @param qstate: query state that finished.
2647  * @param id: module id.
2648  * @param super: the qstate to inform.
2649  */
2650 void
2651 iter_inform_super(struct module_qstate* qstate, int id, 
2652         struct module_qstate* super)
2653 {
2654         if(!qstate->is_priming && super->qinfo.qclass == LDNS_RR_CLASS_ANY)
2655                 processClassResponse(qstate, id, super);
2656         else if(super->qinfo.qtype == LDNS_RR_TYPE_DS && ((struct iter_qstate*)
2657                 super->minfo[id])->state == DSNS_FIND_STATE)
2658                 processDSNSResponse(qstate, id, super);
2659         else if(qstate->return_rcode != LDNS_RCODE_NOERROR)
2660                 error_supers(qstate, id, super);
2661         else if(qstate->is_priming)
2662                 prime_supers(qstate, id, super);
2663         else    processTargetResponse(qstate, id, super);
2664 }
2665
2666 /**
2667  * Handle iterator state.
2668  * Handle events. This is the real processing loop for events, responsible
2669  * for moving events through the various states. If a processing method
2670  * returns true, then it will be advanced to the next state. If false, then
2671  * processing will stop.
2672  *
2673  * @param qstate: query state.
2674  * @param ie: iterator shared global environment.
2675  * @param iq: iterator query state.
2676  * @param id: module id.
2677  */
2678 static void
2679 iter_handle(struct module_qstate* qstate, struct iter_qstate* iq,
2680         struct iter_env* ie, int id)
2681 {
2682         int cont = 1;
2683         while(cont) {
2684                 verbose(VERB_ALGO, "iter_handle processing q with state %s",
2685                         iter_state_to_string(iq->state));
2686                 switch(iq->state) {
2687                         case INIT_REQUEST_STATE:
2688                                 cont = processInitRequest(qstate, iq, ie, id);
2689                                 break;
2690                         case INIT_REQUEST_2_STATE:
2691                                 cont = processInitRequest2(qstate, iq, id);
2692                                 break;
2693                         case INIT_REQUEST_3_STATE:
2694                                 cont = processInitRequest3(qstate, iq, id);
2695                                 break;
2696                         case QUERYTARGETS_STATE:
2697                                 cont = processQueryTargets(qstate, iq, ie, id);
2698                                 break;
2699                         case QUERY_RESP_STATE:
2700                                 cont = processQueryResponse(qstate, iq, id);
2701                                 break;
2702                         case PRIME_RESP_STATE:
2703                                 cont = processPrimeResponse(qstate, id);
2704                                 break;
2705                         case COLLECT_CLASS_STATE:
2706                                 cont = processCollectClass(qstate, id);
2707                                 break;
2708                         case DSNS_FIND_STATE:
2709                                 cont = processDSNSFind(qstate, iq, id);
2710                                 break;
2711                         case FINISHED_STATE:
2712                                 cont = processFinished(qstate, iq, id);
2713                                 break;
2714                         default:
2715                                 log_warn("iterator: invalid state: %d",
2716                                         iq->state);
2717                                 cont = 0;
2718                                 break;
2719                 }
2720         }
2721 }
2722
2723 /** 
2724  * This is the primary entry point for processing request events. Note that
2725  * this method should only be used by external modules.
2726  * @param qstate: query state.
2727  * @param ie: iterator shared global environment.
2728  * @param iq: iterator query state.
2729  * @param id: module id.
2730  */
2731 static void
2732 process_request(struct module_qstate* qstate, struct iter_qstate* iq,
2733         struct iter_env* ie, int id)
2734 {
2735         /* external requests start in the INIT state, and finish using the
2736          * FINISHED state. */
2737         iq->state = INIT_REQUEST_STATE;
2738         iq->final_state = FINISHED_STATE;
2739         verbose(VERB_ALGO, "process_request: new external request event");
2740         iter_handle(qstate, iq, ie, id);
2741 }
2742
2743 /** process authoritative server reply */
2744 static void
2745 process_response(struct module_qstate* qstate, struct iter_qstate* iq, 
2746         struct iter_env* ie, int id, struct outbound_entry* outbound,
2747         enum module_ev event)
2748 {
2749         struct msg_parse* prs;
2750         struct edns_data edns;
2751         ldns_buffer* pkt;
2752
2753         verbose(VERB_ALGO, "process_response: new external response event");
2754         iq->response = NULL;
2755         iq->state = QUERY_RESP_STATE;
2756         if(event == module_event_noreply || event == module_event_error) {
2757                 goto handle_it;
2758         }
2759         if( (event != module_event_reply && event != module_event_capsfail)
2760                 || !qstate->reply) {
2761                 log_err("Bad event combined with response");
2762                 outbound_list_remove(&iq->outlist, outbound);
2763                 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2764                 return;
2765         }
2766
2767         /* parse message */
2768         prs = (struct msg_parse*)regional_alloc(qstate->env->scratch, 
2769                 sizeof(struct msg_parse));
2770         if(!prs) {
2771                 log_err("out of memory on incoming message");
2772                 /* like packet got dropped */
2773                 goto handle_it;
2774         }
2775         memset(prs, 0, sizeof(*prs));
2776         memset(&edns, 0, sizeof(edns));
2777         pkt = qstate->reply->c->buffer;
2778         ldns_buffer_set_position(pkt, 0);
2779         if(parse_packet(pkt, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
2780                 verbose(VERB_ALGO, "parse error on reply packet");
2781                 goto handle_it;
2782         }
2783         /* edns is not examined, but removed from message to help cache */
2784         if(parse_extract_edns(prs, &edns) != LDNS_RCODE_NOERROR)
2785                 goto handle_it;
2786         /* remove CD-bit, we asked for in case we handle validation ourself */
2787         prs->flags &= ~BIT_CD;
2788
2789         /* normalize and sanitize: easy to delete items from linked lists */
2790         if(!scrub_message(pkt, prs, &iq->qchase, iq->dp->name, 
2791                 qstate->env->scratch, qstate->env, ie))
2792                 goto handle_it;
2793
2794         /* allocate response dns_msg in region */
2795         iq->response = dns_alloc_msg(pkt, prs, qstate->region);
2796         if(!iq->response)
2797                 goto handle_it;
2798         log_query_info(VERB_DETAIL, "response for", &qstate->qinfo);
2799         log_name_addr(VERB_DETAIL, "reply from", iq->dp->name, 
2800                 &qstate->reply->addr, qstate->reply->addrlen);
2801         if(verbosity >= VERB_ALGO)
2802                 log_dns_msg("incoming scrubbed packet:", &iq->response->qinfo, 
2803                         iq->response->rep);
2804         
2805         if(event == module_event_capsfail) {
2806                 if(!iq->caps_fallback) {
2807                         /* start fallback */
2808                         iq->caps_fallback = 1;
2809                         iq->caps_server = 0;
2810                         iq->caps_reply = iq->response->rep;
2811                         iq->state = QUERYTARGETS_STATE;
2812                         iq->num_current_queries--;
2813                         verbose(VERB_DETAIL, "Capsforid: starting fallback");
2814                         goto handle_it;
2815                 } else {
2816                         /* check if reply is the same, otherwise, fail */
2817                         if(!reply_equal(iq->response->rep, iq->caps_reply,
2818                                 qstate->env->scratch_buffer)) {
2819                                 verbose(VERB_DETAIL, "Capsforid fallback: "
2820                                         "getting different replies, failed");
2821                                 outbound_list_remove(&iq->outlist, outbound);
2822                                 (void)error_response(qstate, id, 
2823                                         LDNS_RCODE_SERVFAIL);
2824                                 return;
2825                         }
2826                         /* continue the fallback procedure at next server */
2827                         iq->caps_server++;
2828                         iq->state = QUERYTARGETS_STATE;
2829                         iq->num_current_queries--;
2830                         verbose(VERB_DETAIL, "Capsforid: reply is equal. "
2831                                 "go to next fallback");
2832                         goto handle_it;
2833                 }
2834         }
2835         iq->caps_fallback = 0; /* if we were in fallback, 0x20 is OK now */
2836
2837 handle_it:
2838         outbound_list_remove(&iq->outlist, outbound);
2839         iter_handle(qstate, iq, ie, id);
2840 }
2841
2842 void 
2843 iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
2844         struct outbound_entry* outbound)
2845 {
2846         struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
2847         struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id];
2848         verbose(VERB_QUERY, "iterator[module %d] operate: extstate:%s event:%s", 
2849                 id, strextstate(qstate->ext_state[id]), strmodulevent(event));
2850         if(iq) log_query_info(VERB_QUERY, "iterator operate: query", 
2851                 &qstate->qinfo);
2852         if(iq && qstate->qinfo.qname != iq->qchase.qname)
2853                 log_query_info(VERB_QUERY, "iterator operate: chased to", 
2854                         &iq->qchase);
2855
2856         /* perform iterator state machine */
2857         if((event == module_event_new || event == module_event_pass) && 
2858                 iq == NULL) {
2859                 if(!iter_new(qstate, id)) {
2860                         (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2861                         return;
2862                 }
2863                 iq = (struct iter_qstate*)qstate->minfo[id];
2864                 process_request(qstate, iq, ie, id);
2865                 return;
2866         }
2867         if(iq && event == module_event_pass) {
2868                 iter_handle(qstate, iq, ie, id);
2869                 return;
2870         }
2871         if(iq && outbound) {
2872                 process_response(qstate, iq, ie, id, outbound, event);
2873                 return;
2874         }
2875         if(event == module_event_error) {
2876                 verbose(VERB_ALGO, "got called with event error, giving up");
2877                 (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2878                 return;
2879         }
2880
2881         log_err("bad event for iterator");
2882         (void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
2883 }
2884
2885 void 
2886 iter_clear(struct module_qstate* qstate, int id)
2887 {
2888         struct iter_qstate* iq;
2889         if(!qstate)
2890                 return;
2891         iq = (struct iter_qstate*)qstate->minfo[id];
2892         if(iq) {
2893                 outbound_list_clear(&iq->outlist);
2894                 iq->num_current_queries = 0;
2895         }
2896         qstate->minfo[id] = NULL;
2897 }
2898
2899 size_t 
2900 iter_get_mem(struct module_env* env, int id)
2901 {
2902         struct iter_env* ie = (struct iter_env*)env->modinfo[id];
2903         if(!ie)
2904                 return 0;
2905         return sizeof(*ie) + sizeof(int)*((size_t)ie->max_dependency_depth+1)
2906                 + donotq_get_mem(ie->donotq) + priv_get_mem(ie->priv);
2907 }
2908
2909 /**
2910  * The iterator function block 
2911  */
2912 static struct module_func_block iter_block = {
2913         "iterator",
2914         &iter_init, &iter_deinit, &iter_operate, &iter_inform_super, 
2915         &iter_clear, &iter_get_mem
2916 };
2917
2918 struct module_func_block* 
2919 iter_get_funcblock(void)
2920 {
2921         return &iter_block;
2922 }
2923
2924 const char* 
2925 iter_state_to_string(enum iter_state state)
2926 {
2927         switch (state)
2928         {
2929         case INIT_REQUEST_STATE :
2930                 return "INIT REQUEST STATE";
2931         case INIT_REQUEST_2_STATE :
2932                 return "INIT REQUEST STATE (stage 2)";
2933         case INIT_REQUEST_3_STATE:
2934                 return "INIT REQUEST STATE (stage 3)";
2935         case QUERYTARGETS_STATE :
2936                 return "QUERY TARGETS STATE";
2937         case PRIME_RESP_STATE :
2938                 return "PRIME RESPONSE STATE";
2939         case COLLECT_CLASS_STATE :
2940                 return "COLLECT CLASS STATE";
2941         case DSNS_FIND_STATE :
2942                 return "DSNS FIND STATE";
2943         case QUERY_RESP_STATE :
2944                 return "QUERY RESPONSE STATE";
2945         case FINISHED_STATE :
2946                 return "FINISHED RESPONSE STATE";
2947         default :
2948                 return "UNKNOWN ITER STATE";
2949         }
2950 }
2951
2952 int 
2953 iter_state_is_responsestate(enum iter_state s)
2954 {
2955         switch(s) {
2956                 case INIT_REQUEST_STATE :
2957                 case INIT_REQUEST_2_STATE :
2958                 case INIT_REQUEST_3_STATE :
2959                 case QUERYTARGETS_STATE :
2960                 case COLLECT_CLASS_STATE :
2961                         return 0;
2962                 default:
2963                         break;
2964         }
2965         return 1;
2966 }