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