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