1 /*
2  * iterator/iterator.h - 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 #ifndef ITERATOR_ITERATOR_H
44 #define ITERATOR_ITERATOR_H
45 #include "services/outbound_list.h"
46 #include "util/data/msgreply.h"
47 #include "util/module.h"
48 struct delegpt;
49 struct iter_hints;
50 struct iter_forwards;
51 struct iter_donotq;
52 struct iter_prep_list;
53 struct iter_priv;
54 struct rbtree_type;
55 
56 /** max number of targets spawned for a query and its subqueries */
57 #define MAX_TARGET_COUNT	64
58 /** max number of target lookups per qstate, per delegation point */
59 #define MAX_DP_TARGET_COUNT	16
60 /** max number of nxdomains allowed for target lookups for a query and
61  * its subqueries */
62 #define MAX_TARGET_NX		5
63 /** max number of query restarts. Determines max number of CNAME chain. */
64 #define MAX_RESTART_COUNT	11
65 /** max number of referrals. Makes sure resolver does not run away */
66 #define MAX_REFERRAL_COUNT	130
67 /** max number of queries-sent-out.  Make sure large NS set does not loop */
68 #define MAX_SENT_COUNT		32
69 /** max number of queries for which to perform dnsseclameness detection,
70  * (rrsigs missing detection) after that, just pick up that response */
71 #define DNSSEC_LAME_DETECT_COUNT 4
72 /**
73  * max number of QNAME minimisation iterations. Limits number of queries for
74  * QNAMEs with a lot of labels.
75 */
76 #define MAX_MINIMISE_COUNT	10
77 /* max number of time-outs for minimised query. Prevents resolving failures
78  * when the QNAME minimisation QTYPE is blocked. */
79 #define MAX_MINIMISE_TIMEOUT_COUNT 3
80 /**
81  * number of labels from QNAME that are always send individually when using
82  * QNAME minimisation, even when the number of labels of the QNAME is bigger
83  * tham MAX_MINIMISE_COUNT */
84 #define MINIMISE_ONE_LAB	4
85 #define MINIMISE_MULTIPLE_LABS	(MAX_MINIMISE_COUNT - MINIMISE_ONE_LAB)
86 /** at what query-sent-count to stop target fetch policy */
87 #define TARGET_FETCH_STOP	3
88 /** how nice is a server without further information, in msec
89  * Equals rtt initial timeout value.
90  */
91 extern int UNKNOWN_SERVER_NICENESS;
92 /** maximum timeout before a host is deemed unsuitable, in msec.
93  * After host_ttl this will be timed out and the host will be tried again.
94  * Equals RTT_MAX_TIMEOUT
95  */
96 #define USEFUL_SERVER_TOP_TIMEOUT	120000
97 /** RTT band, within this amount from the best, servers are chosen randomly.
98  * Chosen so that the UNKNOWN_SERVER_NICENESS falls within the band of a
99  * fast server, this causes server exploration as a side benefit. msec. */
100 #define RTT_BAND 400
101 /** Start value for blacklisting a host, 2*USEFUL_SERVER_TOP_TIMEOUT in sec */
102 #define INFRA_BACKOFF_INITIAL 240
103 
104 /**
105  * Global state for the iterator.
106  */
107 struct iter_env {
108 	/** A flag to indicate whether or not we have an IPv6 route */
109 	int supports_ipv6;
110 
111 	/** A flag to indicate whether or not we have an IPv4 route */
112 	int supports_ipv4;
113 
114 	/** A set of inetaddrs that should never be queried. */
115 	struct iter_donotq* donotq;
116 
117 	/** private address space and private domains */
118 	struct iter_priv* priv;
119 
120 	/** whitelist for capsforid names */
121 	struct rbtree_type* caps_white;
122 
123 	/** The maximum dependency depth that this resolver will pursue. */
124 	int max_dependency_depth;
125 
126 	/**
127 	 * The target fetch policy for each dependency level. This is
128 	 * described as a simple number (per dependency level):
129 	 *	negative numbers (usually just -1) mean fetch-all,
130 	 *	0 means only fetch on demand, and
131 	 *	positive numbers mean to fetch at most that many targets.
132 	 * array of max_dependency_depth+1 size.
133 	 */
134 	int* target_fetch_policy;
135 
136 	/** lock on ratelimit counter */
137 	lock_basic_type queries_ratelimit_lock;
138 	/** number of queries that have been ratelimited */
139 	size_t num_queries_ratelimited;
140 
141 	/** number of retries on outgoing queries */
142 	int outbound_msg_retry;
143 };
144 
145 /**
146  * QNAME minimisation state
147  */
148 enum minimisation_state {
149 	/**
150 	 * (Re)start minimisation. Outgoing QNAME should be set to dp->name.
151 	 * State entered on new query or after following referral or CNAME.
152 	 */
153 	INIT_MINIMISE_STATE = 0,
154 	/**
155 	 * QNAME minimisation ongoing. Increase QNAME on every iteration.
156 	 */
157 	MINIMISE_STATE,
158 	/**
159 	 * Don't increment QNAME this iteration
160 	 */
161 	SKIP_MINIMISE_STATE,
162 	/**
163 	 * Send out full QNAME + original QTYPE
164 	 */
165 	DONOT_MINIMISE_STATE,
166 };
167 
168 /**
169  * State of the iterator for a query.
170  */
171 enum iter_state {
172 	/**
173 	 * Externally generated queries start at this state. Query restarts are
174 	 * reset to this state.
175 	 */
176 	INIT_REQUEST_STATE = 0,
177 
178 	/**
179 	 * Root priming events reactivate here, most other events pass
180 	 * through this naturally as the 2nd part of the INIT_REQUEST_STATE.
181 	 */
182 	INIT_REQUEST_2_STATE,
183 
184 	/**
185 	 * Stub priming events reactivate here, most other events pass
186 	 * through this naturally as the 3rd part of the INIT_REQUEST_STATE.
187 	 */
188 	INIT_REQUEST_3_STATE,
189 
190 	/**
191 	 * Each time a delegation point changes for a given query or a
192 	 * query times out and/or wakes up, this state is (re)visited.
193 	 * This state is responsible for iterating through a list of
194 	 * nameserver targets.
195 	 */
196 	QUERYTARGETS_STATE,
197 
198 	/**
199 	 * Responses to queries start at this state. This state handles
200 	 * the decision tree associated with handling responses.
201 	 */
202 	QUERY_RESP_STATE,
203 
204 	/** Responses to priming queries finish at this state. */
205 	PRIME_RESP_STATE,
206 
207 	/** Collecting query class information, for qclass=ANY, when
208 	 * it spawns off queries for every class, it returns here. */
209 	COLLECT_CLASS_STATE,
210 
211 	/** Find NS record to resolve DS record from, walking to the right
212 	 * NS spot until we find it */
213 	DSNS_FIND_STATE,
214 
215 	/** Responses that are to be returned upstream end at this state.
216 	 * As well as responses to target queries. */
217 	FINISHED_STATE
218 };
219 
220 /**
221  * Per query state for the iterator module.
222  */
223 struct iter_qstate {
224 	/**
225 	 * State of the iterator module.
226 	 * This is the state that event is in or should sent to -- all
227 	 * requests should start with the INIT_REQUEST_STATE. All
228 	 * responses should start with QUERY_RESP_STATE. Subsequent
229 	 * processing of the event will change this state.
230 	 */
231 	enum iter_state state;
232 
233 	/**
234 	 * Final state for the iterator module.
235 	 * This is the state that responses should be routed to once the
236 	 * response is final. For externally initiated queries, this
237 	 * will be FINISHED_STATE, locally initiated queries will have
238 	 * different final states.
239 	 */
240 	enum iter_state final_state;
241 
242 	/**
243 	 * The depth of this query, this means the depth of recursion.
244 	 * This address is needed for another query, which is an address
245 	 * needed for another query, etc. Original client query has depth 0.
246 	 */
247 	int depth;
248 
249 	/**
250 	 * The response
251 	 */
252 	struct dns_msg* response;
253 
254 	/**
255 	 * This is a list of RRsets that must be prepended to the
256 	 * ANSWER section of a response before being sent upstream.
257 	 */
258 	struct iter_prep_list* an_prepend_list;
259 	/** Last element of the prepend list */
260 	struct iter_prep_list* an_prepend_last;
261 
262 	/**
263 	 * This is the list of RRsets that must be prepended to the
264 	 * AUTHORITY section of the response before being sent upstream.
265 	 */
266 	struct iter_prep_list* ns_prepend_list;
267 	/** Last element of the authority prepend list */
268 	struct iter_prep_list* ns_prepend_last;
269 
270 	/** query name used for chasing the results. Initially the same as
271 	 * the state qinfo, but after CNAMEs this will be different.
272 	 * The query info used to elicit the results needed. */
273 	struct query_info qchase;
274 	/** query flags to use when chasing the answer (i.e. RD flag) */
275 	uint16_t chase_flags;
276 	/** true if we set RD bit because of last resort recursion lame query*/
277 	int chase_to_rd;
278 
279 	/**
280 	 * This is the current delegation point for an in-progress query. This
281 	 * object retains state as to which delegation targets need to be
282 	 * (sub)queried for vs which ones have already been visited.
283 	 */
284 	struct delegpt* dp;
285 
286 	/** state for 0x20 fallback when capsfail happens, 0 not a fallback */
287 	int caps_fallback;
288 	/** state for capsfail: current server number to try */
289 	size_t caps_server;
290 	/** state for capsfail: stored query for comparisons. Can be NULL if
291 	 * no response had been seen prior to starting the fallback. */
292 	struct reply_info* caps_reply;
293 	struct dns_msg* caps_response;
294 
295 	/** Current delegation message - returned for non-RD queries */
296 	struct dns_msg* deleg_msg;
297 
298 	/** number of outstanding target sub queries */
299 	int num_target_queries;
300 
301 	/** outstanding direct queries */
302 	int num_current_queries;
303 
304 	/** the number of times this query has been restarted. */
305 	int query_restart_count;
306 
307 	/** the number of times this query as followed a referral. */
308 	int referral_count;
309 
310 	/** number of queries fired off */
311 	int sent_count;
312 
313 	/** number of target queries spawned in [1], for this query and its
314 	 * subqueries, the malloced-array is shared, [0] refcount.
315 	 * in [2] the number of nxdomains is counted. */
316 	int* target_count;
317 
318 	/** number of target lookups per delegation point. Reset to 0 after
319 	 * receiving referral answer. Not shared with subqueries. */
320 	int dp_target_count;
321 
322 	/** if true, already tested for ratelimiting and passed the test */
323 	int ratelimit_ok;
324 
325 	/**
326 	 * The query must store NS records from referrals as parentside RRs
327 	 * Enabled once it hits resolution problems, to throttle retries.
328 	 * If enabled it is the pointer to the old delegation point with
329 	 * the old retry counts for bad-nameserver-addresses.
330 	 */
331 	struct delegpt* store_parent_NS;
332 
333 	/**
334 	 * The query is for parent-side glue(A or AAAA) for a nameserver.
335 	 * If the item is seen as glue in a referral, and pside_glue is NULL,
336 	 * then it is stored in pside_glue for later.
337 	 * If it was never seen, at the end, then a negative caching element
338 	 * must be created.
339 	 * The (data or negative) RR cache element then throttles retries.
340 	 */
341 	int query_for_pside_glue;
342 	/** the parent-side-glue element (NULL if none, its first match) */
343 	struct ub_packed_rrset_key* pside_glue;
344 
345 	/** If nonNULL we are walking upwards from DS query to find NS */
346 	uint8_t* dsns_point;
347 	/** length of the dname in dsns_point */
348 	size_t dsns_point_len;
349 
350 	/**
351 	 * expected dnssec information for this iteration step.
352 	 * If dnssec rrsigs are expected and not given, the server is marked
353 	 * lame (dnssec-lame).
354 	 */
355 	int dnssec_expected;
356 
357 	/**
358 	 * We are expecting dnssec information, but we also know the server
359 	 * is DNSSEC lame.  The response need not be marked dnssec-lame again.
360 	 */
361 	int dnssec_lame_query;
362 
363 	/**
364 	 * This is flag that, if true, means that this event is
365 	 * waiting for a stub priming query.
366 	 */
367 	int wait_priming_stub;
368 
369 	/**
370 	 * This is a flag that, if true, means that this query is
371 	 * for (re)fetching glue from a zone. Since the address should
372 	 * have been glue, query again to the servers that should have
373 	 * been returning it as glue.
374 	 * The delegation point must be set to the one that should *not*
375 	 * be used when creating the state. A higher one will be attempted.
376 	 */
377 	int refetch_glue;
378 
379 	/** list of pending queries to authoritative servers. */
380 	struct outbound_list outlist;
381 
382 	/** QNAME minimisation state, RFC7816 */
383 	enum minimisation_state minimisation_state;
384 
385 	/** State for capsfail: QNAME minimisation state for comparisons. */
386 	enum minimisation_state caps_minimisation_state;
387 
388 	/**
389 	 * The query info that is sent upstream. Will be a subset of qchase
390 	 * when qname minimisation is enabled.
391 	 */
392 	struct query_info qinfo_out;
393 
394 	/**
395 	 * Count number of QNAME minimisation iterations. Used to limit number of
396 	 * outgoing queries when QNAME minimisation is enabled.
397 	 */
398 	int minimise_count;
399 
400 	/**
401 	 * Count number of time-outs. Used to prevent resolving failures when
402 	 * the QNAME minimisation QTYPE is blocked. Used to determine if
403 	 * capsforid fallback should be started.*/
404 	int timeout_count;
405 
406 	/** True if the current response is from auth_zone */
407 	int auth_zone_response;
408 	/** True if the auth_zones should not be consulted for the query */
409 	int auth_zone_avoid;
410 	/** true if there have been scrubbing failures of reply packets */
411 	int scrub_failures;
412 	/** true if there have been parse failures of reply packets */
413 	int parse_failures;
414 	/** a failure printout address for last received answer */
415 	struct comm_reply* fail_reply;
416 };
417 
418 /**
419  * List of prepend items
420  */
421 struct iter_prep_list {
422 	/** next in list */
423 	struct iter_prep_list* next;
424 	/** rrset */
425 	struct ub_packed_rrset_key* rrset;
426 };
427 
428 /**
429  * Get the iterator function block.
430  * @return: function block with function pointers to iterator methods.
431  */
432 struct module_func_block* iter_get_funcblock(void);
433 
434 /**
435  * Get iterator state as a string
436  * @param state: to convert
437  * @return constant string that is printable.
438  */
439 const char* iter_state_to_string(enum iter_state state);
440 
441 /**
442  * See if iterator state is a response state
443  * @param s: to inspect
444  * @return true if response state.
445  */
446 int iter_state_is_responsestate(enum iter_state s);
447 
448 /** iterator init */
449 int iter_init(struct module_env* env, int id);
450 
451 /** iterator deinit */
452 void iter_deinit(struct module_env* env, int id);
453 
454 /** iterator operate on a query */
455 void iter_operate(struct module_qstate* qstate, enum module_ev event, int id,
456 	struct outbound_entry* outbound);
457 
458 /**
459  * Return priming query results to interested super querystates.
460  *
461  * Sets the delegation point and delegation message (not nonRD queries).
462  * This is a callback from walk_supers.
463  *
464  * @param qstate: query state that finished.
465  * @param id: module id.
466  * @param super: the qstate to inform.
467  */
468 void iter_inform_super(struct module_qstate* qstate, int id,
469 	struct module_qstate* super);
470 
471 /** iterator cleanup query state */
472 void iter_clear(struct module_qstate* qstate, int id);
473 
474 /** iterator alloc size routine */
475 size_t iter_get_mem(struct module_env* env, int id);
476 
477 #endif /* ITERATOR_ITERATOR_H */
478