xref: /freebsd/contrib/unbound/util/module.h (revision aa1207ea4f030c50a91bca6a3df950ca25113d5a)
1 /*
2  * util/module.h - DNS handling module interface
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 the interface for DNS handling modules.
40  *
41  * The module interface uses the DNS modules as state machines.  The
42  * state machines are activated in sequence to operate on queries.  Once
43  * they are done, the reply is passed back.  In the usual setup the mesh
44  * is the caller of the state machines and once things are done sends replies
45  * and invokes result callbacks.
46  *
47  * The module provides a number of functions, listed in the module_func_block.
48  * The module is inited and destroyed and memory usage queries, for the
49  * module as a whole, for entire-module state (such as a cache).  And per-query
50  * functions are called, operate to move the state machine and cleanup of
51  * the per-query state.
52  *
53  * Most per-query state should simply be allocated in the query region.
54  * This is destroyed at the end of the query.
55  *
56  * The module environment contains services and information and caches
57  * shared by the modules and the rest of the system.  It also contains
58  * function pointers for module-specific tasks (like sending queries).
59  *
60  * *** Example module calls for a normal query
61  *
62  * In this example, the query does not need recursion, all the other data
63  * can be found in the cache.  This makes the example shorter.
64  *
65  * At the start of the program the iterator module is initialised.
66  * The iterator module sets up its global state, such as donotquery lists
67  * and private address trees.
68  *
69  * A query comes in, and a mesh entry is created for it.  The mesh
70  * starts the resolution process.  The validator module is the first
71  * in the list of modules, and it is started on this new query.  The
72  * operate() function is called.  The validator decides it needs not do
73  * anything yet until there is a result and returns wait_module, that
74  * causes the next module in the list to be started.
75  *
76  * The next module is the iterator.  It is started on the passed query and
77  * decides to perform a lookup.  For this simple example, the delegation
78  * point information is available, and all the iterator wants to do is
79  * send a UDP query.  The iterator uses env.send_query() to send the
80  * query.  Then the iterator suspends (returns from the operate call).
81  *
82  * When the UDP reply comes back (and on errors and timeouts), the
83  * operate function is called for the query, on the iterator module,
84  * with the event that there is a reply.  The iterator decides that this
85  * is enough, the work is done.  It returns the value finished from the
86  * operate call, which causes the previous module to be started.
87  *
88  * The previous module, the validator module, is started with the event
89  * that the iterator module is done.  The validator decides to validate
90  * the query.  Once it is done (which could take recursive lookups, but
91  * in this example no recursive lookups are needed), it returns from the
92  * operate function with finished.
93  *
94  * There is no previous module from the validator module, and the mesh
95  * takes this to mean that the query is finally done.  The mesh invokes
96  * callbacks and sends packets to queriers.
97  *
98  * If other modules had been waiting (recursively) on the answer to this
99  * query, then the mesh will tell them about it.  It calls the inform_super
100  * routine on all the waiting modules, and once that is done it calls all of
101  * them with the operate() call.  During inform_super the query that is done
102  * still exists and information can be copied from it (but the module should
103  * not really re-entry codepoints and services).  During the operate call
104  * the modules can use stored state to continue operation with the results.
105  * (network buffers are used to contain the answer packet during the
106  * inform_super phase, but after that the network buffers will be cleared
107  * of their contents so that other tasks can be performed).
108  *
109  * *** Example module calls for recursion
110  *
111  * A module is called in operate, and it decides that it wants to perform
112  * recursion.  That is, it wants the full state-machine-list to operate on
113  * a different query.  It calls env.attach_sub() to create a new query state.
114  * The routine returns the newly created state, and potentially the module
115  * can edit the module-states for the newly created query (i.e. pass along
116  * some information, like delegation points).  The module then suspends,
117  * returns from the operate routine.
118  *
119  * The mesh meanwhile will have the newly created query (or queries) on
120  * a waiting list, and will call operate() on this query (or queries).
121  * It starts again at the start of the module list for them.  The query
122  * (or queries) continue to operate their state machines, until they are
123  * done.  When they are done the mesh calls inform_super on the module that
124  * wanted the recursion.  After that the mesh calls operate() on the module
125  * that wanted to do the recursion, and during this phase the module could,
126  * for example, decide to create more recursions.
127  *
128  * If the module decides it no longer wants the recursive information
129  * it can call detach_subs.  Those queries will still run to completion,
130  * potentially filling the cache with information.  Inform_super is not
131  * called any more.
132  *
133  * The iterator module will fetch items from the cache, so a recursion
134  * attempt may complete very quickly if the item is in cache.  The calling
135  * module has to wait for completion or eventual timeout.  A recursive query
136  * that times out returns a servfail rcode (servfail is also returned for
137  * other errors during the lookup).
138  *
139  * Results are passed in the qstate, the rcode member is used to pass
140  * errors without requiring memory allocation, so that the code can continue
141  * in out-of-memory conditions.  If the rcode member is 0 (NOERROR) then
142  * the dns_msg entry contains a filled out message.  This message may
143  * also contain an rcode that is nonzero, but in this case additional
144  * information (query, additional) can be passed along.
145  *
146  * The rcode and dns_msg are used to pass the result from the the rightmost
147  * module towards the leftmost modules and then towards the user.
148  *
149  * If you want to avoid recursion-cycles where queries need other queries
150  * that need the first one, use detect_cycle() to see if that will happen.
151  *
152  */
153 
154 #ifndef UTIL_MODULE_H
155 #define UTIL_MODULE_H
156 #include "util/storage/lruhash.h"
157 #include "util/data/msgreply.h"
158 #include "util/data/msgparse.h"
159 struct sldns_buffer;
160 struct alloc_cache;
161 struct rrset_cache;
162 struct key_cache;
163 struct config_file;
164 struct slabhash;
165 struct query_info;
166 struct edns_data;
167 struct regional;
168 struct worker;
169 struct comm_base;
170 struct auth_zones;
171 struct outside_network;
172 struct module_qstate;
173 struct ub_randstate;
174 struct mesh_area;
175 struct mesh_state;
176 struct val_anchors;
177 struct val_neg_cache;
178 struct iter_forwards;
179 struct iter_hints;
180 struct respip_set;
181 struct respip_client_info;
182 struct respip_addr_info;
183 
184 /** Maximum number of modules in operation */
185 #define MAX_MODULE 16
186 
187 /** Maximum number of known edns options */
188 #define MAX_KNOWN_EDNS_OPTS 256
189 
190 struct errinf_strlist {
191     /** next item in list */
192     struct errinf_strlist* next;
193     /** config option string */
194     char* str;
195     /** EDE code companion to the error str */
196     int reason_bogus;
197 };
198 
199 enum inplace_cb_list_type {
200 	/* Inplace callbacks for when a resolved reply is ready to be sent to the
201 	 * front.*/
202 	inplace_cb_reply = 0,
203 	/* Inplace callbacks for when a reply is given from the cache. */
204 	inplace_cb_reply_cache,
205 	/* Inplace callbacks for when a reply is given with local data
206 	 * (or Chaos reply). */
207 	inplace_cb_reply_local,
208 	/* Inplace callbacks for when the reply is servfail. */
209 	inplace_cb_reply_servfail,
210 	/* Inplace callbacks for when a query is ready to be sent to the back.*/
211 	inplace_cb_query,
212 	/* Inplace callback for when a reply is received from the back. */
213 	inplace_cb_query_response,
214 	/* Inplace callback for when EDNS is parsed on a reply received from the
215 	 * back. */
216 	inplace_cb_edns_back_parsed,
217 	/* Total number of types. Used for array initialization.
218 	 * Should always be last. */
219 	inplace_cb_types_total
220 };
221 
222 
223 /** Known edns option. Can be populated during modules' init. */
224 struct edns_known_option {
225 	/** type of this edns option */
226 	uint16_t opt_code;
227 	/** whether the option needs to bypass the cache stage */
228 	int bypass_cache_stage;
229 	/** whether the option needs mesh aggregation */
230 	int no_aggregation;
231 };
232 
233 /**
234  * Inplace callback list of registered routines to be called.
235  */
236 struct inplace_cb {
237 	/** next in list */
238 	struct inplace_cb* next;
239 	/** Inplace callback routine */
240 	void* cb;
241 	void* cb_arg;
242 	/** module id */
243 	int id;
244 };
245 
246 /**
247  * Inplace callback function called before replying.
248  * Called as func(qinfo, qstate, rep, rcode, edns, opt_list_out, repinfo,
249  *                region, id, python_callback)
250  * Where:
251  *	qinfo: the query info.
252  *	qstate: the module state. NULL when calling before the query reaches the
253  *		mesh states.
254  *	rep: reply_info. Could be NULL.
255  *	rcode: the return code.
256  *	edns: the edns_data of the reply. When qstate is NULL, it is also used as
257  *		the edns input.
258  *	opt_list_out: the edns options list for the reply.
259  *	repinfo: reply information for a communication point. NULL when calling
260  *		during the mesh states; the same could be found from
261  *		qstate->mesh_info->reply_list.
262  *	region: region to store data.
263  *	id: module id.
264  *	python_callback: only used for registering a python callback function.
265  */
266 typedef int inplace_cb_reply_func_type(struct query_info* qinfo,
267 	struct module_qstate* qstate, struct reply_info* rep, int rcode,
268 	struct edns_data* edns, struct edns_option** opt_list_out,
269 	struct comm_reply* repinfo, struct regional* region,
270 	struct timeval* start_time, int id, void* callback);
271 
272 /**
273  * Inplace callback function called before sending the query to a nameserver.
274  * Called as func(qinfo, flags, qstate, addr, addrlen, zone, zonelen, region,
275  *                id, python_callback)
276  * Where:
277  *	qinfo: query info.
278  *	flags: flags of the query.
279  *	qstate: query state.
280  *	addr: to which server to send the query.
281  *	addrlen: length of addr.
282  *	zone: name of the zone of the delegation point. wireformat dname.
283  *		This is the delegation point name for which the server is deemed
284  *		authoritative.
285  *	zonelen: length of zone.
286  *	region: region to store data.
287  *	id: module id.
288  *	python_callback: only used for registering a python callback function.
289  */
290 typedef int inplace_cb_query_func_type(struct query_info* qinfo, uint16_t flags,
291 	struct module_qstate* qstate, struct sockaddr_storage* addr,
292 	socklen_t addrlen, uint8_t* zone, size_t zonelen, struct regional* region,
293 	int id, void* callback);
294 
295 /**
296  * Inplace callback function called after parsing edns on query reply.
297  * Called as func(qstate, id, cb_args)
298  * Where:
299  *	qstate: the query state.
300  *	id: module id.
301  *	cb_args: argument passed when registering callback.
302  */
303 typedef int inplace_cb_edns_back_parsed_func_type(struct module_qstate* qstate,
304 	int id, void* cb_args);
305 
306 /**
307  * Inplace callback function called after parsing query response.
308  * Called as func(qstate, response, id, cb_args)
309  * Where:
310  *	qstate: the query state.
311  *	response: query response.
312  *	id: module id.
313  *	cb_args: argument passed when registering callback.
314  */
315 typedef int inplace_cb_query_response_func_type(struct module_qstate* qstate,
316 	struct dns_msg* response, int id, void* cb_args);
317 
318 /**
319  * Function called when looking for (expired) cached answers during the serve
320  * expired logic.
321  * Called as func(qstate, lookup_qinfo)
322  * Where:
323  *	qstate: the query state.
324  *	lookup_qinfo: the qinfo to lookup for.
325  */
326 typedef struct dns_msg* serve_expired_lookup_func_type(
327 	struct module_qstate* qstate, struct query_info* lookup_qinfo);
328 
329 /**
330  * Module environment.
331  * Services and data provided to the module.
332  */
333 struct module_env {
334 	/* --- data --- */
335 	/** config file with config options */
336 	struct config_file* cfg;
337 	/** shared message cache */
338 	struct slabhash* msg_cache;
339 	/** shared rrset cache */
340 	struct rrset_cache* rrset_cache;
341 	/** shared infrastructure cache (edns, lameness) */
342 	struct infra_cache* infra_cache;
343 	/** shared key cache */
344 	struct key_cache* key_cache;
345 
346 	/* --- services --- */
347 	/**
348 	 * Send serviced DNS query to server. UDP/TCP and EDNS is handled.
349 	 * operate() should return with wait_reply. Later on a callback
350 	 * will cause operate() to be called with event timeout or reply.
351 	 * The time until a timeout is calculated from roundtrip timing,
352 	 * several UDP retries are attempted.
353 	 * @param qinfo: query info.
354 	 * @param flags: host order flags word, with opcode and CD bit.
355 	 * @param dnssec: if set, EDNS record will have bits set.
356 	 *	If EDNS_DO bit is set, DO bit is set in EDNS records.
357 	 *	If BIT_CD is set, CD bit is set in queries with EDNS records.
358 	 * @param want_dnssec: if set, the validator wants DNSSEC.  Without
359 	 * 	EDNS, the answer is likely to be useless for this domain.
360 	 * @param nocaps: do not use caps_for_id, use the qname as given.
361 	 *	(ignored if caps_for_id is disabled).
362 	 * @param check_ratelimit: if set, will check ratelimit before sending out.
363 	 * @param addr: where to.
364 	 * @param addrlen: length of addr.
365 	 * @param zone: delegation point name.
366 	 * @param zonelen: length of zone name.
367 	 * @param tcp_upstream: use TCP for upstream queries.
368 	 * @param ssl_upstream: use SSL for upstream queries.
369 	 * @param tls_auth_name: if ssl_upstream, use this name with TLS
370 	 * 	authentication.
371 	 * @param q: which query state to reactivate upon return.
372 	 * @param was_ratelimited: it will signal back if the query failed to pass the
373 	 *	ratelimit check.
374 	 * @return: false on failure (memory or socket related). no query was
375 	 *	sent. Or returns an outbound entry with qsent and qstate set.
376 	 *	This outbound_entry will be used on later module invocations
377 	 *	that involve this query (timeout, error or reply).
378 	 */
379 	struct outbound_entry* (*send_query)(struct query_info* qinfo,
380 		uint16_t flags, int dnssec, int want_dnssec, int nocaps,
381 		int check_ratelimit,
382 		struct sockaddr_storage* addr, socklen_t addrlen,
383 		uint8_t* zone, size_t zonelen, int tcp_upstream, int ssl_upstream,
384 		char* tls_auth_name, struct module_qstate* q, int* was_ratelimited);
385 
386 	/**
387 	 * Detach-subqueries.
388 	 * Remove all sub-query references from this query state.
389 	 * Keeps super-references of those sub-queries correct.
390 	 * Updates stat items in mesh_area structure.
391 	 * @param qstate: used to find mesh state.
392 	 */
393 	void (*detach_subs)(struct module_qstate* qstate);
394 
395 	/**
396 	 * Attach subquery.
397 	 * Creates it if it does not exist already.
398 	 * Keeps sub and super references correct.
399 	 * Updates stat items in mesh_area structure.
400 	 * Pass if it is priming query or not.
401 	 * return:
402 	 * o if error (malloc) happened.
403 	 * o need to initialise the new state (module init; it is a new state).
404 	 *   so that the next run of the query with this module is successful.
405 	 * o no init needed, attachment successful.
406 	 *
407 	 * @param qstate: the state to find mesh state, and that wants to
408 	 * 	receive the results from the new subquery.
409 	 * @param qinfo: what to query for (copied).
410 	 * @param qflags: what flags to use (RD, CD flag or not).
411 	 * @param prime: if it is a (stub) priming query.
412 	 * @param valrec: validation lookup recursion, does not need validation
413 	 * @param newq: If the new subquery needs initialisation, it is
414 	 * 	returned, otherwise NULL is returned.
415 	 * @return: false on error, true if success (and init may be needed).
416 	 */
417 	int (*attach_sub)(struct module_qstate* qstate,
418 		struct query_info* qinfo, uint16_t qflags, int prime,
419 		int valrec, struct module_qstate** newq);
420 
421 	/**
422 	 * Add detached query.
423 	 * Creates it if it does not exist already.
424 	 * Does not make super/sub references.
425 	 * Performs a cycle detection - for double check - and fails if there is
426 	 * 	one.
427 	 * Updates stat items in mesh_area structure.
428 	 * Pass if it is priming query or not.
429 	 * return:
430 	 * 	o if error (malloc) happened.
431 	 * 	o need to initialise the new state (module init; it is a new state).
432 	 * 	  so that the next run of the query with this module is successful.
433 	 * 	o no init needed, attachment successful.
434 	 * 	o added subquery, created if it did not exist already.
435 	 *
436 	 * @param qstate: the state to find mesh state, and that wants to receive
437 	 * 	the results from the new subquery.
438 	 * @param qinfo: what to query for (copied).
439 	 * @param qflags: what flags to use (RD / CD flag or not).
440 	 * @param prime: if it is a (stub) priming query.
441 	 * @param valrec: if it is a validation recursion query (lookup of key, DS).
442 	 * @param newq: If the new subquery needs initialisation, it is returned,
443 	 * 	otherwise NULL is returned.
444 	 * @param sub: The added mesh state, created if it did not exist already.
445 	 * @return: false on error, true if success (and init may be needed).
446 	 */
447 	int (*add_sub)(struct module_qstate* qstate,
448 		struct query_info* qinfo, uint16_t qflags, int prime,
449 		int valrec, struct module_qstate** newq,
450 		struct mesh_state** sub);
451 
452 	/**
453 	 * Kill newly attached sub. If attach_sub returns newq for
454 	 * initialisation, but that fails, then this routine will cleanup and
455 	 * delete the freshly created sub.
456 	 * @param newq: the new subquery that is no longer needed.
457 	 * 	It is removed.
458 	 */
459 	void (*kill_sub)(struct module_qstate* newq);
460 
461 	/**
462 	 * Detect if adding a dependency for qstate on name,type,class will
463 	 * create a dependency cycle.
464 	 * @param qstate: given mesh querystate.
465 	 * @param qinfo: query info for dependency.
466 	 * @param flags: query flags of dependency, RD/CD flags.
467 	 * @param prime: if dependency is a priming query or not.
468 	 * @param valrec: validation lookup recursion, does not need validation
469 	 * @return true if the name,type,class exists and the given
470 	 * 	qstate mesh exists as a dependency of that name. Thus
471 	 * 	if qstate becomes dependent on name,type,class then a
472 	 * 	cycle is created.
473 	 */
474 	int (*detect_cycle)(struct module_qstate* qstate,
475 		struct query_info* qinfo, uint16_t flags, int prime,
476 		int valrec);
477 
478 	/** region for temporary usage. May be cleared after operate() call. */
479 	struct regional* scratch;
480 	/** buffer for temporary usage. May be cleared after operate() call. */
481 	struct sldns_buffer* scratch_buffer;
482 	/** internal data for daemon - worker thread. */
483 	struct worker* worker;
484 	/** the worker event base */
485 	struct comm_base* worker_base;
486 	/** the outside network */
487 	struct outside_network* outnet;
488 	/** mesh area with query state dependencies */
489 	struct mesh_area* mesh;
490 	/** allocation service */
491 	struct alloc_cache* alloc;
492 	/** random table to generate random numbers */
493 	struct ub_randstate* rnd;
494 	/** time in seconds, converted to integer */
495 	time_t* now;
496 	/** time in microseconds. Relatively recent. */
497 	struct timeval* now_tv;
498 	/** is validation required for messages, controls client-facing
499 	 * validation status (AD bits) and servfails */
500 	int need_to_validate;
501 	/** trusted key storage; these are the configured keys, if not NULL,
502 	 * otherwise configured by validator. These are the trust anchors,
503 	 * and are not primed and ready for validation, but on the bright
504 	 * side, they are read only memory, thus no locks and fast. */
505 	struct val_anchors* anchors;
506 	/** negative cache, configured by the validator. if not NULL,
507 	 * contains NSEC record lookup trees. */
508 	struct val_neg_cache* neg_cache;
509 	/** the 5011-probe timer (if any) */
510 	struct comm_timer* probe_timer;
511 	/** auth zones */
512 	struct auth_zones* auth_zones;
513 	/** Mapping of forwarding zones to targets.
514 	 * iterator forwarder information. per-thread, created by worker */
515 	struct iter_forwards* fwds;
516 	/**
517 	 * iterator forwarder information. per-thread, created by worker.
518 	 * The hints -- these aren't stored in the cache because they don't
519 	 * expire. The hints are always used to "prime" the cache. Note
520 	 * that both root hints and stub zone "hints" are stored in this
521 	 * data structure.
522 	 */
523 	struct iter_hints* hints;
524 	/** module specific data. indexed by module id. */
525 	void* modinfo[MAX_MODULE];
526 
527 	/* Shared linked list of inplace callback functions */
528 	struct inplace_cb* inplace_cb_lists[inplace_cb_types_total];
529 
530 	/**
531 	 * Shared array of known edns options (size MAX_KNOWN_EDNS_OPTS).
532 	 * Filled by edns literate modules during init.
533 	 */
534 	struct edns_known_option* edns_known_options;
535 	/* Number of known edns options */
536 	size_t edns_known_options_num;
537 	/** EDNS client string information */
538 	struct edns_strings* edns_strings;
539 
540 	/* Make every mesh state unique, do not aggregate mesh states. */
541 	int unique_mesh;
542 };
543 
544 /**
545  * External visible states of the module state machine
546  * Modules may also have an internal state.
547  * Modules are supposed to run to completion or until blocked.
548  */
549 enum module_ext_state {
550 	/** initial state - new query */
551 	module_state_initial = 0,
552 	/** waiting for reply to outgoing network query */
553 	module_wait_reply,
554 	/** module is waiting for another module */
555 	module_wait_module,
556 	/** module is waiting for another module; that other is restarted */
557 	module_restart_next,
558 	/** module is waiting for sub-query */
559 	module_wait_subquery,
560 	/** module could not finish the query */
561 	module_error,
562 	/** module is finished with query */
563 	module_finished
564 };
565 
566 /**
567  * Events that happen to modules, that start or wakeup modules.
568  */
569 enum module_ev {
570 	/** new query */
571 	module_event_new = 0,
572 	/** query passed by other module */
573 	module_event_pass,
574 	/** reply inbound from server */
575 	module_event_reply,
576 	/** no reply, timeout or other error */
577 	module_event_noreply,
578 	/** reply is there, but capitalisation check failed */
579 	module_event_capsfail,
580 	/** next module is done, and its reply is awaiting you */
581 	module_event_moddone,
582 	/** error */
583 	module_event_error
584 };
585 
586 /**
587  * Linked list of sockaddrs
588  * May be allocated such that only 'len' bytes of addr exist for the structure.
589  */
590 struct sock_list {
591 	/** next in list */
592 	struct sock_list* next;
593 	/** length of addr */
594 	socklen_t len;
595 	/** sockaddr */
596 	struct sockaddr_storage addr;
597 };
598 
599 struct respip_action_info;
600 
601 /**
602  * Struct to hold relevant data for serve expired
603  */
604 struct serve_expired_data {
605 	struct comm_timer* timer;
606 	serve_expired_lookup_func_type* get_cached_answer;
607 };
608 
609 /**
610  * Module state, per query.
611  */
612 struct module_qstate {
613 	/** which query is being answered: name, type, class */
614 	struct query_info qinfo;
615 	/** flags uint16 from query */
616 	uint16_t query_flags;
617 	/** if this is a (stub or root) priming query (with hints) */
618 	int is_priming;
619 	/** if this is a validation recursion query that does not get
620 	 * validation itself */
621 	int is_valrec;
622 #ifdef CLIENT_SUBNET
623 	/** the client network address is needed for the client-subnet option
624 	 *  when prefetching, but we can't use reply_list in mesh_info, because
625 	 *  we don't want to send a reply for the internal query. */
626         struct sockaddr_storage client_addr;
627 #endif
628 
629 	/** comm_reply contains server replies */
630 	struct comm_reply* reply;
631 	/** the reply message, with message for client and calling module */
632 	struct dns_msg* return_msg;
633 	/** the rcode, in case of error, instead of a reply message */
634 	int return_rcode;
635 	/** origin of the reply (can be NULL from cache, list for cnames) */
636 	struct sock_list* reply_origin;
637 	/** IP blacklist for queries */
638 	struct sock_list* blacklist;
639 	/** region for this query. Cleared when query process finishes. */
640 	struct regional* region;
641 	/** failure reason information if val-log-level is high */
642 	struct errinf_strlist* errinf;
643 	/** which module is executing */
644 	int curmod;
645 	/** module states */
646 	enum module_ext_state ext_state[MAX_MODULE];
647 	/** module specific data for query. indexed by module id. */
648 	void* minfo[MAX_MODULE];
649 	/** environment for this query */
650 	struct module_env* env;
651 	/** mesh related information for this query */
652 	struct mesh_state* mesh_info;
653 	/** how many seconds before expiry is this prefetched (0 if not) */
654 	time_t prefetch_leeway;
655 	/** serve expired data */
656 	struct serve_expired_data* serve_expired_data;
657 
658 	/** incoming edns options from the front end */
659 	struct edns_option* edns_opts_front_in;
660 	/** outgoing edns options to the back end */
661 	struct edns_option* edns_opts_back_out;
662 	/** incoming edns options from the back end */
663 	struct edns_option* edns_opts_back_in;
664 	/** outgoing edns options to the front end */
665 	struct edns_option* edns_opts_front_out;
666 	/** whether modules should answer from the cache */
667 	int no_cache_lookup;
668 	/** whether modules should store answer in the cache */
669 	int no_cache_store;
670 	/** whether to refetch a fresh answer on finishing this state*/
671 	int need_refetch;
672 	/** whether the query (or a subquery) was ratelimited */
673 	int was_ratelimited;
674 	/** time when query was started. This is when the qstate is created.
675 	 * This is used so that type NS data cannot be overwritten by them
676 	 * expiring while the lookup is in progress, using data fetched from
677 	 * those servers. By comparing expiry time with qstarttime for type NS.
678 	 */
679 	time_t qstarttime;
680 	/** whether a message from cachedb will be used for the reply */
681 	int is_cachedb_answer;
682 
683 	/**
684 	 * Attributes of clients that share the qstate that may affect IP-based
685 	 * actions.
686 	 */
687 	struct respip_client_info* client_info;
688 
689 	/** Extended result of response-ip action processing, mainly
690 	 *  for logging purposes. */
691 	struct respip_action_info* respip_action_info;
692 	/** if the query is rpz passthru, no further rpz processing for it */
693 	int rpz_passthru;
694 	/* Flag tcp required. */
695 	int tcp_required;
696 
697 	/** whether the reply should be dropped */
698 	int is_drop;
699 };
700 
701 /**
702  * Module functionality block
703  */
704 struct module_func_block {
705 	/** text string name of module */
706 	const char* name;
707 
708 	/**
709 	 * init the module. Called once for the global state.
710 	 * This is the place to apply settings from the config file.
711 	 * @param env: module environment.
712 	 * @param id: module id number.
713 	 * return: 0 on error
714 	 */
715 	int (*init)(struct module_env* env, int id);
716 
717 	/**
718 	 * de-init, delete, the module. Called once for the global state.
719 	 * @param env: module environment.
720 	 * @param id: module id number.
721 	 */
722 	void (*deinit)(struct module_env* env, int id);
723 
724 	/**
725 	 * accept a new query, or work further on existing query.
726 	 * Changes the qstate->ext_state to be correct on exit.
727 	 * @param ev: event that causes the module state machine to
728 	 *	(re-)activate.
729 	 * @param qstate: the query state.
730 	 *	Note that this method is not allowed to change the
731 	 *	query state 'identity', that is query info, qflags,
732 	 *	and priming status.
733 	 *	Attach a subquery to get results to a different query.
734 	 * @param id: module id number that operate() is called on.
735 	 * @param outbound: if not NULL this event is due to the reply/timeout
736 	 *	or error on this outbound query.
737 	 * @return: if at exit the ext_state is:
738 	 *	o wait_module: next module is started. (with pass event).
739 	 *	o error or finished: previous module is resumed.
740 	 *	o otherwise it waits until that event happens (assumes
741 	 *	  the service routine to make subrequest or send message
742 	 *	  have been called.
743 	 */
744 	void (*operate)(struct module_qstate* qstate, enum module_ev event,
745 		int id, struct outbound_entry* outbound);
746 
747 	/**
748 	 * inform super querystate about the results from this subquerystate.
749 	 * Is called when the querystate is finished.  The method invoked is
750 	 * the one from the current module active in the super querystate.
751 	 * @param qstate: the query state that is finished.
752 	 *	Examine return_rcode and return_reply in the qstate.
753 	 * @param id: module id for this module.
754 	 *	This coincides with the current module for the super qstate.
755 	 * @param super: the super querystate that needs to be informed.
756 	 */
757 	void (*inform_super)(struct module_qstate* qstate, int id,
758 		struct module_qstate* super);
759 
760 	/**
761 	 * clear module specific data
762 	 */
763 	void (*clear)(struct module_qstate* qstate, int id);
764 
765 	/**
766 	 * How much memory is the module specific data using.
767 	 * @param env: module environment.
768 	 * @param id: the module id.
769 	 * @return the number of bytes that are alloced.
770 	 */
771 	size_t (*get_mem)(struct module_env* env, int id);
772 };
773 
774 /**
775  * Debug utility: module external qstate to string
776  * @param s: the state value.
777  * @return descriptive string.
778  */
779 const char* strextstate(enum module_ext_state s);
780 
781 /**
782  * Debug utility: module event to string
783  * @param e: the module event value.
784  * @return descriptive string.
785  */
786 const char* strmodulevent(enum module_ev e);
787 
788 /**
789  * Append text to the error info for validation.
790  * @param qstate: query state.
791  * @param str: copied into query region and appended.
792  * Failures to allocate are logged.
793  */
794 void errinf(struct module_qstate* qstate, const char* str);
795 void errinf_ede(struct module_qstate* qstate, const char* str,
796                 sldns_ede_code reason_bogus);
797 
798 /**
799  * Append text to error info:  from 1.2.3.4
800  * @param qstate: query state.
801  * @param origin: sock list with origin of trouble.
802  *  Every element added.
803  *  If NULL: nothing is added.
804  *  if 0len element: 'from cache' is added.
805  */
806 void errinf_origin(struct module_qstate* qstate, struct sock_list *origin);
807 
808 /**
809  * Append text to error info:  for RRset name type class
810  * @param qstate: query state.
811  * @param rr: rrset_key.
812  */
813 void errinf_rrset(struct module_qstate* qstate, struct ub_packed_rrset_key *rr);
814 
815 /**
816  * Append text to error info:  str dname
817  * @param qstate: query state.
818  * @param str: explanation string
819  * @param dname: the dname.
820  */
821 void errinf_dname(struct module_qstate* qstate, const char* str,
822     uint8_t* dname);
823 
824 /**
825  * Create error info in string.  For validation failures.
826  * @param qstate: query state.
827  * @return string or NULL on malloc failure (already logged).
828  *    This string is malloced and has to be freed by caller.
829  */
830 char* errinf_to_str_bogus(struct module_qstate* qstate);
831 
832 /**
833  * Check the sldns_ede_code of the qstate->errinf.
834  * @param qstate: query state.
835  * @return the latest explicitly set sldns_ede_code or LDNS_EDE_NONE.
836  */
837 sldns_ede_code errinf_to_reason_bogus(struct module_qstate* qstate);
838 
839 /**
840  * Create error info in string.  For other servfails.
841  * @param qstate: query state.
842  * @return string or NULL on malloc failure (already logged).
843  *    This string is malloced and has to be freed by caller.
844  */
845 char* errinf_to_str_servfail(struct module_qstate* qstate);
846 
847 /**
848  * Create error info in string.  For misc failures that are not servfail.
849  * @param qstate: query state.
850  * @return string or NULL on malloc failure (already logged).
851  *    This string is malloced and has to be freed by caller.
852  */
853 char* errinf_to_str_misc(struct module_qstate* qstate);
854 
855 /**
856  * Initialize the edns known options by allocating the required space.
857  * @param env: the module environment.
858  * @return false on failure (no memory).
859  */
860 int edns_known_options_init(struct module_env* env);
861 
862 /**
863  * Free the allocated space for the known edns options.
864  * @param env: the module environment.
865  */
866 void edns_known_options_delete(struct module_env* env);
867 
868 /**
869  * Register a known edns option. Overwrite the flags if it is already
870  * registered. Used before creating workers to register known edns options.
871  * @param opt_code: the edns option code.
872  * @param bypass_cache_stage: whether the option interacts with the cache.
873  * @param no_aggregation: whether the option implies more specific
874  *	aggregation.
875  * @param env: the module environment.
876  * @return true on success, false on failure (registering more options than
877  *	allowed or trying to register after the environment is copied to the
878  *	threads.)
879  */
880 int edns_register_option(uint16_t opt_code, int bypass_cache_stage,
881 	int no_aggregation, struct module_env* env);
882 
883 /**
884  * Register an inplace callback function.
885  * @param cb: pointer to the callback function.
886  * @param type: inplace callback type.
887  * @param cbarg: argument for the callback function, or NULL.
888  * @param env: the module environment.
889  * @param id: module id.
890  * @return true on success, false on failure (out of memory or trying to
891  *	register after the environment is copied to the threads.)
892  */
893 int
894 inplace_cb_register(void* cb, enum inplace_cb_list_type type, void* cbarg,
895 	struct module_env* env, int id);
896 
897 /**
898  * Delete callback for specified type and module id.
899  * @param env: the module environment.
900  * @param type: inplace callback type.
901  * @param id: module id.
902  */
903 void
904 inplace_cb_delete(struct module_env* env, enum inplace_cb_list_type type,
905 	int id);
906 
907 /**
908  * Delete all the inplace callback linked lists.
909  * @param env: the module environment.
910  */
911 void inplace_cb_lists_delete(struct module_env* env);
912 
913 /**
914  * Check if an edns option is known.
915  * @param opt_code: the edns option code.
916  * @param env: the module environment.
917  * @return pointer to registered option if the edns option is known,
918  *	NULL otherwise.
919  */
920 struct edns_known_option* edns_option_is_known(uint16_t opt_code,
921 	struct module_env* env);
922 
923 /**
924  * Check if an edns option needs to bypass the reply from cache stage.
925  * @param list: the edns options.
926  * @param env: the module environment.
927  * @return true if an edns option needs to bypass the cache stage,
928  *	false otherwise.
929  */
930 int edns_bypass_cache_stage(struct edns_option* list,
931 	struct module_env* env);
932 
933 /**
934  * Check if an unique mesh state is required. Might be triggered by EDNS option
935  * or set for the complete env.
936  * @param list: the edns options.
937  * @param env: the module environment.
938  * @return true if an edns option needs a unique mesh state,
939  *	false otherwise.
940  */
941 int unique_mesh_state(struct edns_option* list, struct module_env* env);
942 
943 /**
944  * Log the known edns options.
945  * @param level: the desired verbosity level.
946  * @param env: the module environment.
947  */
948 void log_edns_known_options(enum verbosity_value level,
949 	struct module_env* env);
950 
951 /**
952  * Copy state that may have happened in the subquery and is always relevant to
953  * the super.
954  * @param qstate: query state that finished.
955  * @param id: module id.
956  * @param super: the qstate to inform.
957  */
958 void copy_state_to_super(struct module_qstate* qstate, int id,
959 	struct module_qstate* super);
960 
961 #endif /* UTIL_MODULE_H */
962