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