xref: /freebsd/contrib/unbound/util/module.h (revision 716fd348e01c5f2ba125f878a634a753436c2994)
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 enum inplace_cb_list_type {
191 	/* Inplace callbacks for when a resolved reply is ready to be sent to the
192 	 * front.*/
193 	inplace_cb_reply = 0,
194 	/* Inplace callbacks for when a reply is given from the cache. */
195 	inplace_cb_reply_cache,
196 	/* Inplace callbacks for when a reply is given with local data
197 	 * (or Chaos reply). */
198 	inplace_cb_reply_local,
199 	/* Inplace callbacks for when the reply is servfail. */
200 	inplace_cb_reply_servfail,
201 	/* Inplace callbacks for when a query is ready to be sent to the back.*/
202 	inplace_cb_query,
203 	/* Inplace callback for when a reply is received from the back. */
204 	inplace_cb_query_response,
205 	/* Inplace callback for when EDNS is parsed on a reply received from the
206 	 * back. */
207 	inplace_cb_edns_back_parsed,
208 	/* Total number of types. Used for array initialization.
209 	 * Should always be last. */
210 	inplace_cb_types_total
211 };
212 
213 
214 /** Known edns option. Can be populated during modules' init. */
215 struct edns_known_option {
216 	/** type of this edns option */
217 	uint16_t opt_code;
218 	/** whether the option needs to bypass the cache stage */
219 	int bypass_cache_stage;
220 	/** whether the option needs mesh aggregation */
221 	int no_aggregation;
222 };
223 
224 /**
225  * Inplace callback list of registered routines to be called.
226  */
227 struct inplace_cb {
228 	/** next in list */
229 	struct inplace_cb* next;
230 	/** Inplace callback routine */
231 	void* cb;
232 	void* cb_arg;
233 	/** module id */
234 	int id;
235 };
236 
237 /**
238  * Inplace callback function called before replying.
239  * Called as func(qinfo, qstate, rep, rcode, edns, opt_list_out, repinfo,
240  *                region, id, python_callback)
241  * Where:
242  *	qinfo: the query info.
243  *	qstate: the module state. NULL when calling before the query reaches the
244  *		mesh states.
245  *	rep: reply_info. Could be NULL.
246  *	rcode: the return code.
247  *	edns: the edns_data of the reply. When qstate is NULL, it is also used as
248  *		the edns input.
249  *	opt_list_out: the edns options list for the reply.
250  *	repinfo: reply information for a communication point. NULL when calling
251  *		during the mesh states; the same could be found from
252  *		qstate->mesh_info->reply_list.
253  *	region: region to store data.
254  *	id: module id.
255  *	python_callback: only used for registering a python callback function.
256  */
257 typedef int inplace_cb_reply_func_type(struct query_info* qinfo,
258 	struct module_qstate* qstate, struct reply_info* rep, int rcode,
259 	struct edns_data* edns, struct edns_option** opt_list_out,
260 	struct comm_reply* repinfo, struct regional* region,
261 	struct timeval* start_time, int id, void* callback);
262 
263 /**
264  * Inplace callback function called before sending the query to a nameserver.
265  * Called as func(qinfo, flags, qstate, addr, addrlen, zone, zonelen, region,
266  *                id, python_callback)
267  * Where:
268  *	qinfo: query info.
269  *	flags: flags of the query.
270  *	qstate: query state.
271  *	addr: to which server to send the query.
272  *	addrlen: length of addr.
273  *	zone: name of the zone of the delegation point. wireformat dname.
274  *		This is the delegation point name for which the server is deemed
275  *		authoritative.
276  *	zonelen: length of zone.
277  *	region: region to store data.
278  *	id: module id.
279  *	python_callback: only used for registering a python callback function.
280  */
281 typedef int inplace_cb_query_func_type(struct query_info* qinfo, uint16_t flags,
282 	struct module_qstate* qstate, struct sockaddr_storage* addr,
283 	socklen_t addrlen, uint8_t* zone, size_t zonelen, struct regional* region,
284 	int id, void* callback);
285 
286 /**
287  * Inplace callback function called after parsing edns on query reply.
288  * Called as func(qstate, id, cb_args)
289  * Where:
290  *	qstate: the query state.
291  *	id: module id.
292  *	cb_args: argument passed when registering callback.
293  */
294 typedef int inplace_cb_edns_back_parsed_func_type(struct module_qstate* qstate,
295 	int id, void* cb_args);
296 
297 /**
298  * Inplace callback function called after parsing query response.
299  * Called as func(qstate, response, id, cb_args)
300  * Where:
301  *	qstate: the query state.
302  *	response: query response.
303  *	id: module id.
304  *	cb_args: argument passed when registering callback.
305  */
306 typedef int inplace_cb_query_response_func_type(struct module_qstate* qstate,
307 	struct dns_msg* response, int id, void* cb_args);
308 
309 /**
310  * Function called when looking for (expired) cached answers during the serve
311  * expired logic.
312  * Called as func(qstate, lookup_qinfo)
313  * Where:
314  *	qstate: the query state.
315  *	lookup_qinfo: the qinfo to lookup for.
316  */
317 typedef struct dns_msg* serve_expired_lookup_func_type(
318 	struct module_qstate* qstate, struct query_info* lookup_qinfo);
319 
320 /**
321  * Module environment.
322  * Services and data provided to the module.
323  */
324 struct module_env {
325 	/* --- data --- */
326 	/** config file with config options */
327 	struct config_file* cfg;
328 	/** shared message cache */
329 	struct slabhash* msg_cache;
330 	/** shared rrset cache */
331 	struct rrset_cache* rrset_cache;
332 	/** shared infrastructure cache (edns, lameness) */
333 	struct infra_cache* infra_cache;
334 	/** shared key cache */
335 	struct key_cache* key_cache;
336 
337 	/* --- services --- */
338 	/**
339 	 * Send serviced DNS query to server. UDP/TCP and EDNS is handled.
340 	 * operate() should return with wait_reply. Later on a callback
341 	 * will cause operate() to be called with event timeout or reply.
342 	 * The time until a timeout is calculated from roundtrip timing,
343 	 * several UDP retries are attempted.
344 	 * @param qinfo: query info.
345 	 * @param flags: host order flags word, with opcode and CD bit.
346 	 * @param dnssec: if set, EDNS record will have bits set.
347 	 *	If EDNS_DO bit is set, DO bit is set in EDNS records.
348 	 *	If BIT_CD is set, CD bit is set in queries with EDNS records.
349 	 * @param want_dnssec: if set, the validator wants DNSSEC.  Without
350 	 * 	EDNS, the answer is likely to be useless for this domain.
351 	 * @param nocaps: do not use caps_for_id, use the qname as given.
352 	 *	(ignored if caps_for_id is disabled).
353 	 * @param check_ratelimit: if set, will check ratelimit before sending out.
354 	 * @param addr: where to.
355 	 * @param addrlen: length of addr.
356 	 * @param zone: delegation point name.
357 	 * @param zonelen: length of zone name.
358 	 * @param tcp_upstream: use TCP for upstream queries.
359 	 * @param ssl_upstream: use SSL for upstream queries.
360 	 * @param tls_auth_name: if ssl_upstream, use this name with TLS
361 	 * 	authentication.
362 	 * @param q: which query state to reactivate upon return.
363 	 * @param was_ratelimited: it will signal back if the query failed to pass the
364 	 *	ratelimit check.
365 	 * @return: false on failure (memory or socket related). no query was
366 	 *	sent. Or returns an outbound entry with qsent and qstate set.
367 	 *	This outbound_entry will be used on later module invocations
368 	 *	that involve this query (timeout, error or reply).
369 	 */
370 	struct outbound_entry* (*send_query)(struct query_info* qinfo,
371 		uint16_t flags, int dnssec, int want_dnssec, int nocaps,
372 		int check_ratelimit,
373 		struct sockaddr_storage* addr, socklen_t addrlen,
374 		uint8_t* zone, size_t zonelen, int tcp_upstream, int ssl_upstream,
375 		char* tls_auth_name, struct module_qstate* q, int* was_ratelimited);
376 
377 	/**
378 	 * Detach-subqueries.
379 	 * Remove all sub-query references from this query state.
380 	 * Keeps super-references of those sub-queries correct.
381 	 * Updates stat items in mesh_area structure.
382 	 * @param qstate: used to find mesh state.
383 	 */
384 	void (*detach_subs)(struct module_qstate* qstate);
385 
386 	/**
387 	 * Attach subquery.
388 	 * Creates it if it does not exist already.
389 	 * Keeps sub and super references correct.
390 	 * Updates stat items in mesh_area structure.
391 	 * Pass if it is priming query or not.
392 	 * return:
393 	 * o if error (malloc) happened.
394 	 * o need to initialise the new state (module init; it is a new state).
395 	 *   so that the next run of the query with this module is successful.
396 	 * o no init needed, attachment successful.
397 	 *
398 	 * @param qstate: the state to find mesh state, and that wants to
399 	 * 	receive the results from the new subquery.
400 	 * @param qinfo: what to query for (copied).
401 	 * @param qflags: what flags to use (RD, CD flag or not).
402 	 * @param prime: if it is a (stub) priming query.
403 	 * @param valrec: validation lookup recursion, does not need validation
404 	 * @param newq: If the new subquery needs initialisation, it is
405 	 * 	returned, otherwise NULL is returned.
406 	 * @return: false on error, true if success (and init may be needed).
407 	 */
408 	int (*attach_sub)(struct module_qstate* qstate,
409 		struct query_info* qinfo, uint16_t qflags, int prime,
410 		int valrec, struct module_qstate** newq);
411 
412 	/**
413 	 * Add detached query.
414 	 * Creates it if it does not exist already.
415 	 * Does not make super/sub references.
416 	 * Performs a cycle detection - for double check - and fails if there is
417 	 * 	one.
418 	 * Updates stat items in mesh_area structure.
419 	 * Pass if it is priming query or not.
420 	 * return:
421 	 * 	o if error (malloc) happened.
422 	 * 	o need to initialise the new state (module init; it is a new state).
423 	 * 	  so that the next run of the query with this module is successful.
424 	 * 	o no init needed, attachment successful.
425 	 * 	o added subquery, created if it did not exist already.
426 	 *
427 	 * @param qstate: the state to find mesh state, and that wants to receive
428 	 * 	the results from the new subquery.
429 	 * @param qinfo: what to query for (copied).
430 	 * @param qflags: what flags to use (RD / CD flag or not).
431 	 * @param prime: if it is a (stub) priming query.
432 	 * @param valrec: if it is a validation recursion query (lookup of key, DS).
433 	 * @param newq: If the new subquery needs initialisation, it is returned,
434 	 * 	otherwise NULL is returned.
435 	 * @param sub: The added mesh state, created if it did not exist already.
436 	 * @return: false on error, true if success (and init may be needed).
437 	 */
438 	int (*add_sub)(struct module_qstate* qstate,
439 		struct query_info* qinfo, uint16_t qflags, int prime,
440 		int valrec, struct module_qstate** newq,
441 		struct mesh_state** sub);
442 
443 	/**
444 	 * Kill newly attached sub. If attach_sub returns newq for
445 	 * initialisation, but that fails, then this routine will cleanup and
446 	 * delete the freshly created sub.
447 	 * @param newq: the new subquery that is no longer needed.
448 	 * 	It is removed.
449 	 */
450 	void (*kill_sub)(struct module_qstate* newq);
451 
452 	/**
453 	 * Detect if adding a dependency for qstate on name,type,class will
454 	 * create a dependency cycle.
455 	 * @param qstate: given mesh querystate.
456 	 * @param qinfo: query info for dependency.
457 	 * @param flags: query flags of dependency, RD/CD flags.
458 	 * @param prime: if dependency is a priming query or not.
459 	 * @param valrec: validation lookup recursion, does not need validation
460 	 * @return true if the name,type,class exists and the given
461 	 * 	qstate mesh exists as a dependency of that name. Thus
462 	 * 	if qstate becomes dependent on name,type,class then a
463 	 * 	cycle is created.
464 	 */
465 	int (*detect_cycle)(struct module_qstate* qstate,
466 		struct query_info* qinfo, uint16_t flags, int prime,
467 		int valrec);
468 
469 	/** region for temporary usage. May be cleared after operate() call. */
470 	struct regional* scratch;
471 	/** buffer for temporary usage. May be cleared after operate() call. */
472 	struct sldns_buffer* scratch_buffer;
473 	/** internal data for daemon - worker thread. */
474 	struct worker* worker;
475 	/** the worker event base */
476 	struct comm_base* worker_base;
477 	/** the outside network */
478 	struct outside_network* outnet;
479 	/** mesh area with query state dependencies */
480 	struct mesh_area* mesh;
481 	/** allocation service */
482 	struct alloc_cache* alloc;
483 	/** random table to generate random numbers */
484 	struct ub_randstate* rnd;
485 	/** time in seconds, converted to integer */
486 	time_t* now;
487 	/** time in microseconds. Relatively recent. */
488 	struct timeval* now_tv;
489 	/** is validation required for messages, controls client-facing
490 	 * validation status (AD bits) and servfails */
491 	int need_to_validate;
492 	/** trusted key storage; these are the configured keys, if not NULL,
493 	 * otherwise configured by validator. These are the trust anchors,
494 	 * and are not primed and ready for validation, but on the bright
495 	 * side, they are read only memory, thus no locks and fast. */
496 	struct val_anchors* anchors;
497 	/** negative cache, configured by the validator. if not NULL,
498 	 * contains NSEC record lookup trees. */
499 	struct val_neg_cache* neg_cache;
500 	/** the 5011-probe timer (if any) */
501 	struct comm_timer* probe_timer;
502 	/** auth zones */
503 	struct auth_zones* auth_zones;
504 	/** Mapping of forwarding zones to targets.
505 	 * iterator forwarder information. per-thread, created by worker */
506 	struct iter_forwards* fwds;
507 	/**
508 	 * iterator forwarder information. per-thread, created by worker.
509 	 * The hints -- these aren't stored in the cache because they don't
510 	 * expire. The hints are always used to "prime" the cache. Note
511 	 * that both root hints and stub zone "hints" are stored in this
512 	 * data structure.
513 	 */
514 	struct iter_hints* hints;
515 	/** module specific data. indexed by module id. */
516 	void* modinfo[MAX_MODULE];
517 
518 	/* Shared linked list of inplace callback functions */
519 	struct inplace_cb* inplace_cb_lists[inplace_cb_types_total];
520 
521 	/**
522 	 * Shared array of known edns options (size MAX_KNOWN_EDNS_OPTS).
523 	 * Filled by edns literate modules during init.
524 	 */
525 	struct edns_known_option* edns_known_options;
526 	/* Number of known edns options */
527 	size_t edns_known_options_num;
528 	/** EDNS client string information */
529 	struct edns_strings* edns_strings;
530 
531 	/* Make every mesh state unique, do not aggregate mesh states. */
532 	int unique_mesh;
533 };
534 
535 /**
536  * External visible states of the module state machine
537  * Modules may also have an internal state.
538  * Modules are supposed to run to completion or until blocked.
539  */
540 enum module_ext_state {
541 	/** initial state - new query */
542 	module_state_initial = 0,
543 	/** waiting for reply to outgoing network query */
544 	module_wait_reply,
545 	/** module is waiting for another module */
546 	module_wait_module,
547 	/** module is waiting for another module; that other is restarted */
548 	module_restart_next,
549 	/** module is waiting for sub-query */
550 	module_wait_subquery,
551 	/** module could not finish the query */
552 	module_error,
553 	/** module is finished with query */
554 	module_finished
555 };
556 
557 /**
558  * Events that happen to modules, that start or wakeup modules.
559  */
560 enum module_ev {
561 	/** new query */
562 	module_event_new = 0,
563 	/** query passed by other module */
564 	module_event_pass,
565 	/** reply inbound from server */
566 	module_event_reply,
567 	/** no reply, timeout or other error */
568 	module_event_noreply,
569 	/** reply is there, but capitalisation check failed */
570 	module_event_capsfail,
571 	/** next module is done, and its reply is awaiting you */
572 	module_event_moddone,
573 	/** error */
574 	module_event_error
575 };
576 
577 /**
578  * Linked list of sockaddrs
579  * May be allocated such that only 'len' bytes of addr exist for the structure.
580  */
581 struct sock_list {
582 	/** next in list */
583 	struct sock_list* next;
584 	/** length of addr */
585 	socklen_t len;
586 	/** sockaddr */
587 	struct sockaddr_storage addr;
588 };
589 
590 struct respip_action_info;
591 
592 /**
593  * Struct to hold relevant data for serve expired
594  */
595 struct serve_expired_data {
596 	struct comm_timer* timer;
597 	serve_expired_lookup_func_type* get_cached_answer;
598 };
599 
600 /**
601  * Module state, per query.
602  */
603 struct module_qstate {
604 	/** which query is being answered: name, type, class */
605 	struct query_info qinfo;
606 	/** flags uint16 from query */
607 	uint16_t query_flags;
608 	/** if this is a (stub or root) priming query (with hints) */
609 	int is_priming;
610 	/** if this is a validation recursion query that does not get
611 	 * validation itself */
612 	int is_valrec;
613 
614 	/** comm_reply contains server replies */
615 	struct comm_reply* reply;
616 	/** the reply message, with message for client and calling module */
617 	struct dns_msg* return_msg;
618 	/** the rcode, in case of error, instead of a reply message */
619 	int return_rcode;
620 	/** origin of the reply (can be NULL from cache, list for cnames) */
621 	struct sock_list* reply_origin;
622 	/** IP blacklist for queries */
623 	struct sock_list* blacklist;
624 	/** region for this query. Cleared when query process finishes. */
625 	struct regional* region;
626 	/** failure reason information if val-log-level is high */
627 	struct config_strlist* errinf;
628 
629 	/** which module is executing */
630 	int curmod;
631 	/** module states */
632 	enum module_ext_state ext_state[MAX_MODULE];
633 	/** module specific data for query. indexed by module id. */
634 	void* minfo[MAX_MODULE];
635 	/** environment for this query */
636 	struct module_env* env;
637 	/** mesh related information for this query */
638 	struct mesh_state* mesh_info;
639 	/** how many seconds before expiry is this prefetched (0 if not) */
640 	time_t prefetch_leeway;
641 	/** serve expired data */
642 	struct serve_expired_data* serve_expired_data;
643 
644 	/** incoming edns options from the front end */
645 	struct edns_option* edns_opts_front_in;
646 	/** outgoing edns options to the back end */
647 	struct edns_option* edns_opts_back_out;
648 	/** incoming edns options from the back end */
649 	struct edns_option* edns_opts_back_in;
650 	/** outgoing edns options to the front end */
651 	struct edns_option* edns_opts_front_out;
652 	/** whether modules should answer from the cache */
653 	int no_cache_lookup;
654 	/** whether modules should store answer in the cache */
655 	int no_cache_store;
656 	/** whether to refetch a fresh answer on finishing this state*/
657 	int need_refetch;
658 	/** whether the query (or a subquery) was ratelimited */
659 	int was_ratelimited;
660 
661 	/**
662 	 * Attributes of clients that share the qstate that may affect IP-based
663 	 * actions.
664 	 */
665 	struct respip_client_info* client_info;
666 
667 	/** Extended result of response-ip action processing, mainly
668 	 *  for logging purposes. */
669 	struct respip_action_info* respip_action_info;
670 
671 	/** whether the reply should be dropped */
672 	int is_drop;
673 };
674 
675 /**
676  * Module functionality block
677  */
678 struct module_func_block {
679 	/** text string name of module */
680 	const char* name;
681 
682 	/**
683 	 * init the module. Called once for the global state.
684 	 * This is the place to apply settings from the config file.
685 	 * @param env: module environment.
686 	 * @param id: module id number.
687 	 * return: 0 on error
688 	 */
689 	int (*init)(struct module_env* env, int id);
690 
691 	/**
692 	 * de-init, delete, the module. Called once for the global state.
693 	 * @param env: module environment.
694 	 * @param id: module id number.
695 	 */
696 	void (*deinit)(struct module_env* env, int id);
697 
698 	/**
699 	 * accept a new query, or work further on existing query.
700 	 * Changes the qstate->ext_state to be correct on exit.
701 	 * @param ev: event that causes the module state machine to
702 	 *	(re-)activate.
703 	 * @param qstate: the query state.
704 	 *	Note that this method is not allowed to change the
705 	 *	query state 'identity', that is query info, qflags,
706 	 *	and priming status.
707 	 *	Attach a subquery to get results to a different query.
708 	 * @param id: module id number that operate() is called on.
709 	 * @param outbound: if not NULL this event is due to the reply/timeout
710 	 *	or error on this outbound query.
711 	 * @return: if at exit the ext_state is:
712 	 *	o wait_module: next module is started. (with pass event).
713 	 *	o error or finished: previous module is resumed.
714 	 *	o otherwise it waits until that event happens (assumes
715 	 *	  the service routine to make subrequest or send message
716 	 *	  have been called.
717 	 */
718 	void (*operate)(struct module_qstate* qstate, enum module_ev event,
719 		int id, struct outbound_entry* outbound);
720 
721 	/**
722 	 * inform super querystate about the results from this subquerystate.
723 	 * Is called when the querystate is finished.  The method invoked is
724 	 * the one from the current module active in the super querystate.
725 	 * @param qstate: the query state that is finished.
726 	 *	Examine return_rcode and return_reply in the qstate.
727 	 * @param id: module id for this module.
728 	 *	This coincides with the current module for the super qstate.
729 	 * @param super: the super querystate that needs to be informed.
730 	 */
731 	void (*inform_super)(struct module_qstate* qstate, int id,
732 		struct module_qstate* super);
733 
734 	/**
735 	 * clear module specific data
736 	 */
737 	void (*clear)(struct module_qstate* qstate, int id);
738 
739 	/**
740 	 * How much memory is the module specific data using.
741 	 * @param env: module environment.
742 	 * @param id: the module id.
743 	 * @return the number of bytes that are alloced.
744 	 */
745 	size_t (*get_mem)(struct module_env* env, int id);
746 };
747 
748 /**
749  * Debug utility: module external qstate to string
750  * @param s: the state value.
751  * @return descriptive string.
752  */
753 const char* strextstate(enum module_ext_state s);
754 
755 /**
756  * Debug utility: module event to string
757  * @param e: the module event value.
758  * @return descriptive string.
759  */
760 const char* strmodulevent(enum module_ev e);
761 
762 /**
763  * Initialize the edns known options by allocating the required space.
764  * @param env: the module environment.
765  * @return false on failure (no memory).
766  */
767 int edns_known_options_init(struct module_env* env);
768 
769 /**
770  * Free the allocated space for the known edns options.
771  * @param env: the module environment.
772  */
773 void edns_known_options_delete(struct module_env* env);
774 
775 /**
776  * Register a known edns option. Overwrite the flags if it is already
777  * registered. Used before creating workers to register known edns options.
778  * @param opt_code: the edns option code.
779  * @param bypass_cache_stage: whether the option interacts with the cache.
780  * @param no_aggregation: whether the option implies more specific
781  *	aggregation.
782  * @param env: the module environment.
783  * @return true on success, false on failure (registering more options than
784  *	allowed or trying to register after the environment is copied to the
785  *	threads.)
786  */
787 int edns_register_option(uint16_t opt_code, int bypass_cache_stage,
788 	int no_aggregation, struct module_env* env);
789 
790 /**
791  * Register an inplace callback function.
792  * @param cb: pointer to the callback function.
793  * @param type: inplace callback type.
794  * @param cbarg: argument for the callback function, or NULL.
795  * @param env: the module environment.
796  * @param id: module id.
797  * @return true on success, false on failure (out of memory or trying to
798  *	register after the environment is copied to the threads.)
799  */
800 int
801 inplace_cb_register(void* cb, enum inplace_cb_list_type type, void* cbarg,
802 	struct module_env* env, int id);
803 
804 /**
805  * Delete callback for specified type and module id.
806  * @param env: the module environment.
807  * @param type: inplace callback type.
808  * @param id: module id.
809  */
810 void
811 inplace_cb_delete(struct module_env* env, enum inplace_cb_list_type type,
812 	int id);
813 
814 /**
815  * Delete all the inplace callback linked lists.
816  * @param env: the module environment.
817  */
818 void inplace_cb_lists_delete(struct module_env* env);
819 
820 /**
821  * Check if an edns option is known.
822  * @param opt_code: the edns option code.
823  * @param env: the module environment.
824  * @return pointer to registered option if the edns option is known,
825  *	NULL otherwise.
826  */
827 struct edns_known_option* edns_option_is_known(uint16_t opt_code,
828 	struct module_env* env);
829 
830 /**
831  * Check if an edns option needs to bypass the reply from cache stage.
832  * @param list: the edns options.
833  * @param env: the module environment.
834  * @return true if an edns option needs to bypass the cache stage,
835  *	false otherwise.
836  */
837 int edns_bypass_cache_stage(struct edns_option* list,
838 	struct module_env* env);
839 
840 /**
841  * Check if an unique mesh state is required. Might be triggered by EDNS option
842  * or set for the complete env.
843  * @param list: the edns options.
844  * @param env: the module environment.
845  * @return true if an edns option needs a unique mesh state,
846  *	false otherwise.
847  */
848 int unique_mesh_state(struct edns_option* list, struct module_env* env);
849 
850 /**
851  * Log the known edns options.
852  * @param level: the desired verbosity level.
853  * @param env: the module environment.
854  */
855 void log_edns_known_options(enum verbosity_value level,
856 	struct module_env* env);
857 
858 /**
859  * Copy state that may have happened in the subquery and is always relevant to
860  * the super.
861  * @param qstate: query state that finished.
862  * @param id: module id.
863  * @param super: the qstate to inform.
864  */
865 void copy_state_to_super(struct module_qstate* qstate, int id,
866 	struct module_qstate* super);
867 
868 #endif /* UTIL_MODULE_H */
869