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