2 * services/mesh.h - deal with mesh of query states and handle events for that.
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
39 * This file contains functions to assist in dealing with a mesh of
40 * query states. This mesh is supposed to be thread-specific.
41 * It consists of query states (per qname, qtype, qclass) and connections
42 * between query states and the super and subquery states, and replies to
43 * send back to clients.
46 #ifndef SERVICES_MESH_H
47 #define SERVICES_MESH_H
49 #include "util/rbtree.h"
50 #include "util/netevent.h"
51 #include "util/data/msgparse.h"
52 #include "util/module.h"
53 #include "services/modstack.h"
54 #include "services/rpz.h"
55 #include "libunbound/unbound.h"
62 struct outbound_entry;
64 struct respip_client_info;
67 * Maximum number of mesh state activations. Any more is likely an
68 * infinite loop in the module. It is then terminated.
70 #define MESH_MAX_ACTIVATION 10000
73 * Max number of references-to-references-to-references.. search size.
74 * Any more is treated like 'too large', and the creation of a new
75 * dependency is failed (so that no loops can be created).
77 #define MESH_MAX_SUBSUB 1024
80 * Mesh of query states
83 /** active module stack */
84 struct module_stack mods;
85 /** environment for new states */
86 struct module_env* env;
88 /** set of runnable queries (mesh_state.run_node) */
90 /** rbtree of all current queries (mesh_state.node)*/
93 /** count of the total number of mesh_reply entries */
94 size_t num_reply_addrs;
95 /** count of the number of mesh_states that have mesh_replies
96 * Because a state can send results to multiple reply addresses,
97 * this number must be equal or lower than num_reply_addrs. */
98 size_t num_reply_states;
99 /** number of mesh_states that have no mesh_replies, and also
100 * an empty set of super-states, thus are 'toplevel' or detached
101 * internal opportunistic queries */
102 size_t num_detached_states;
103 /** number of reply states in the forever list */
104 size_t num_forever_states;
106 /** max total number of reply states to have */
107 size_t max_reply_states;
108 /** max forever number of reply states to have */
109 size_t max_forever_states;
111 /** stats, cumulative number of reply states jostled out */
112 size_t stats_jostled;
113 /** stats, cumulative number of incoming client msgs dropped */
114 size_t stats_dropped;
115 /** stats, number of expired replies sent */
117 /** number of replies sent */
119 /** sum of waiting times for the replies */
120 struct timeval replies_sum_wait;
121 /** histogram of time values */
122 struct timehist* histogram;
123 /** (extended stats) secure replies */
125 /** (extended stats) bogus replies */
127 /** (extended stats) rcodes in replies */
128 size_t ans_rcode[UB_STATS_RCODE_NUM];
129 /** (extended stats) rcode nodata in replies */
131 /** (extended stats) type of applied RPZ action */
132 size_t rpz_action[UB_STATS_RPZ_ACTION_NUM];
134 /** backup of query if other operations recurse and need the
136 struct sldns_buffer* qbuf_bak;
138 /** double linked list of the run-to-completion query states.
139 * These are query states with a reply */
140 struct mesh_state* forever_first;
141 /** last entry in run forever list */
142 struct mesh_state* forever_last;
144 /** double linked list of the query states that can be jostled out
145 * by new queries if too old. These are query states with a reply */
146 struct mesh_state* jostle_first;
147 /** last entry in jostle list - this is the entry that is newest */
148 struct mesh_state* jostle_last;
149 /** timeout for jostling. if age is lower, it does not get jostled. */
150 struct timeval jostle_max;
152 /** If we need to use response ip (value passed from daemon)*/
154 /** If we need to use RPZ (value passed from daemon) */
160 * Unique per qname, qtype, qclass (from the qstate).
161 * And RD / CD flag; in case a client turns it off.
162 * And priming queries are different from ordinary queries (because of hints).
164 * The entire structure is allocated in a region, this region is the qstate
165 * region. All parts (rbtree nodes etc) are also allocated in the region.
168 /** node in mesh_area all tree, key is this struct. Must be first. */
170 /** node in mesh_area runnable tree, key is this struct */
171 rbnode_type run_node;
172 /** the query state. Note that the qinfo and query_flags
174 struct module_qstate s;
175 /** the list of replies to clients for the results */
176 struct mesh_reply* reply_list;
177 /** the list of callbacks for the results */
178 struct mesh_cb* cb_list;
179 /** set of superstates (that want this state's result)
180 * contains struct mesh_state_ref* */
181 rbtree_type super_set;
182 /** set of substates (that this state needs to continue)
183 * contains struct mesh_state_ref* */
185 /** number of activations for the mesh state */
186 size_t num_activated;
188 /** previous in linked list for reply states */
189 struct mesh_state* prev;
190 /** next in linked list for reply states */
191 struct mesh_state* next;
192 /** if this state is in the forever list, jostle list, or neither */
193 enum mesh_list_select { mesh_no_list, mesh_forever_list,
194 mesh_jostle_list } list_select;
195 /** pointer to this state for uniqueness or NULL */
196 struct mesh_state* unique;
198 /** true if replies have been sent out (at end for alignment) */
199 uint8_t replies_sent;
203 * Rbtree reference to a mesh_state.
204 * Used in super_set and sub_set.
206 struct mesh_state_ref {
207 /** node in rbtree for set, key is this structure */
209 /** the mesh state */
210 struct mesh_state* s;
217 /** next in reply list */
218 struct mesh_reply* next;
219 /** the query reply destination, packet buffer and where to send. */
220 struct comm_reply query_reply;
221 /** edns data from query */
222 struct edns_data edns;
223 /** the time when request was entered */
224 struct timeval start_time;
225 /** id of query, in network byteorder. */
227 /** flags of query, for reply flags */
229 /** qname from this query. len same as mesh qinfo. */
231 /** same as that in query_info. */
232 struct local_rrset* local_alias;
236 * Mesh result callback func.
237 * called as func(cb_arg, rcode, buffer_with_reply, security, why_bogus,
240 typedef void (*mesh_cb_func_type)(void* cb_arg, int rcode, struct sldns_buffer*,
241 enum sec_status, char* why_bogus, int was_ratelimited);
244 * Callback to result routine
248 struct mesh_cb* next;
249 /** edns data from query */
250 struct edns_data edns;
251 /** id of query, in network byteorder. */
253 /** flags of query, for reply flags */
255 /** buffer for reply */
256 struct sldns_buffer* buf;
257 /** callback routine for results. if rcode != 0 buf has message.
258 * called as cb(cb_arg, rcode, buf, sec_state, why_bogus, was_ratelimited);
260 mesh_cb_func_type cb;
261 /** user arg for callback */
265 /* ------------------- Functions for worker -------------------- */
268 * Allocate mesh, to empty.
269 * @param stack: module stack to activate, copied (as readonly reference).
270 * @param env: environment for new queries.
271 * @return mesh: the new mesh or NULL on error.
273 struct mesh_area* mesh_create(struct module_stack* stack,
274 struct module_env* env);
277 * Delete mesh, and all query states and replies in it.
278 * @param mesh: the mesh to delete.
280 void mesh_delete(struct mesh_area* mesh);
283 * New query incoming from clients. Create new query state if needed, and
284 * add mesh_reply to it. Returns error to client on malloc failures.
285 * Will run the mesh area queries to process if a new query state is created.
287 * @param mesh: the mesh.
288 * @param qinfo: query from client.
289 * @param cinfo: additional information associated with the query client.
290 * 'cinfo' itself is ephemeral but data pointed to by its members
291 * can be assumed to be valid and unchanged until the query processing is
293 * @param qflags: flags from client query.
294 * @param edns: edns data from client query.
295 * @param rep: where to reply to.
296 * @param qid: query id to reply with.
298 void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
299 struct respip_client_info* cinfo, uint16_t qflags,
300 struct edns_data* edns, struct comm_reply* rep, uint16_t qid);
303 * New query with callback. Create new query state if needed, and
305 * Will run the mesh area queries to process if a new query state is created.
307 * @param mesh: the mesh.
308 * @param qinfo: query from client.
309 * @param qflags: flags from client query.
310 * @param edns: edns data from client query.
311 * @param buf: buffer for reply contents.
312 * @param qid: query id to reply with.
313 * @param cb: callback function.
314 * @param cb_arg: callback user arg.
315 * @return 0 on error.
317 int mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
318 uint16_t qflags, struct edns_data* edns, struct sldns_buffer* buf,
319 uint16_t qid, mesh_cb_func_type cb, void* cb_arg);
322 * New prefetch message. Create new query state if needed.
323 * Will run the mesh area queries to process if a new query state is created.
325 * @param mesh: the mesh.
326 * @param qinfo: query from client.
327 * @param qflags: flags from client query.
328 * @param leeway: TTL leeway what to expire earlier for this update.
330 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
331 uint16_t qflags, time_t leeway);
334 * Handle new event from the wire. A serviced query has returned.
335 * The query state will be made runnable, and the mesh_area will process
336 * query states until processing is complete.
338 * @param mesh: the query mesh.
339 * @param e: outbound entry, with query state to run and reply pointer.
340 * @param reply: the comm point reply info.
341 * @param what: NETEVENT_* error code (if not 0, what is wrong, TIMEOUT).
343 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
344 struct comm_reply* reply, int what);
346 /* ------------------- Functions for module environment --------------- */
350 * Remove all sub-query references from this query state.
351 * Keeps super-references of those sub-queries correct.
352 * Updates stat items in mesh_area structure.
353 * @param qstate: used to find mesh state.
355 void mesh_detach_subs(struct module_qstate* qstate);
359 * Creates it if it does not exist already.
360 * Keeps sub and super references correct.
361 * Performs a cycle detection - for double check - and fails if there is one.
362 * Also fails if the sub-sub-references become too large.
363 * Updates stat items in mesh_area structure.
364 * Pass if it is priming query or not.
366 * o if error (malloc) happened.
367 * o need to initialise the new state (module init; it is a new state).
368 * so that the next run of the query with this module is successful.
369 * o no init needed, attachment successful.
371 * @param qstate: the state to find mesh state, and that wants to receive
372 * the results from the new subquery.
373 * @param qinfo: what to query for (copied).
374 * @param qflags: what flags to use (RD / CD flag or not).
375 * @param prime: if it is a (stub) priming query.
376 * @param valrec: if it is a validation recursion query (lookup of key, DS).
377 * @param newq: If the new subquery needs initialisation, it is returned,
378 * otherwise NULL is returned.
379 * @return: false on error, true if success (and init may be needed).
381 int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
382 uint16_t qflags, int prime, int valrec, struct module_qstate** newq);
385 * Add detached query.
386 * Creates it if it does not exist already.
387 * Does not make super/sub references.
388 * Performs a cycle detection - for double check - and fails if there is one.
389 * Updates stat items in mesh_area structure.
390 * Pass if it is priming query or not.
392 * o if error (malloc) happened.
393 * o need to initialise the new state (module init; it is a new state).
394 * so that the next run of the query with this module is successful.
395 * o no init needed, attachment successful.
396 * o added subquery, created if it did not exist already.
398 * @param qstate: the state to find mesh state, and that wants to receive
399 * 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: if it is a validation recursion query (lookup of key, DS).
404 * @param newq: If the new subquery needs initialisation, it is returned,
405 * otherwise NULL is returned.
406 * @param sub: The added mesh state, created if it did not exist already.
407 * @return: false on error, true if success (and init may be needed).
409 int mesh_add_sub(struct module_qstate* qstate, struct query_info* qinfo,
410 uint16_t qflags, int prime, int valrec, struct module_qstate** newq,
411 struct mesh_state** sub);
414 * Query state is done, send messages to reply entries.
415 * Encode messages using reply entry values and the querystate (with original
416 * qinfo), using given reply_info.
417 * Pass errcode != 0 if an error reply is needed.
418 * If no reply entries, nothing is done.
419 * Must be called before a module can module_finished or return module_error.
420 * The module must handle the super query states itself as well.
422 * @param mstate: mesh state that is done. return_rcode and return_msg
423 * are used for replies.
424 * return_rcode: if not 0 (NOERROR) an error is sent back (and
425 * return_msg is ignored).
426 * return_msg: reply to encode and send back to clients.
428 void mesh_query_done(struct mesh_state* mstate);
431 * Call inform_super for the super query states that are interested in the
432 * results from this query state. These can then be changed for error
434 * Called when a module is module_finished or returns module_error.
435 * The super query states become runnable with event module_event_pass,
436 * it calls the current module for the super with the inform_super event.
438 * @param mesh: mesh area to add newly runnable modules to.
439 * @param mstate: the state that has results, used to find mesh state.
441 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate);
444 * Delete mesh state, cleanup and also rbtrees and so on.
445 * Will detach from all super/subnodes.
446 * @param qstate: to remove.
448 void mesh_state_delete(struct module_qstate* qstate);
450 /* ------------------- Functions for mesh -------------------- */
453 * Create and initialize a new mesh state and its query state
454 * Does not put the mesh state into rbtrees and so on.
455 * @param env: module environment to set.
456 * @param qinfo: query info that the mesh is for.
457 * @param cinfo: control info for the query client (can be NULL).
458 * @param qflags: flags for query (RD / CD flag).
459 * @param prime: if true, it is a priming query, set is_priming on mesh state.
460 * @param valrec: if true, it is a validation recursion query, and sets
461 * is_valrec on the mesh state.
462 * @return: new mesh state or NULL on allocation error.
464 struct mesh_state* mesh_state_create(struct module_env* env,
465 struct query_info* qinfo, struct respip_client_info* cinfo,
466 uint16_t qflags, int prime, int valrec);
469 * Check if the mesh state is unique.
470 * A unique mesh state uses it's unique member to point to itself, else NULL.
471 * @param mstate: mesh state to check.
472 * @return true if the mesh state is unique, false otherwise.
474 int mesh_state_is_unique(struct mesh_state* mstate);
477 * Make a mesh state unique.
478 * A unique mesh state uses it's unique member to point to itself.
479 * @param mstate: mesh state to check.
481 void mesh_state_make_unique(struct mesh_state* mstate);
484 * Cleanup a mesh state and its query state. Does not do rbtree or
486 * @param mstate: mesh state to cleanup. Its pointer may no longer be used
487 * afterwards. Cleanup rbtrees before calling this function.
489 void mesh_state_cleanup(struct mesh_state* mstate);
492 * Delete all mesh states from the mesh.
493 * @param mesh: the mesh area to clear
495 void mesh_delete_all(struct mesh_area* mesh);
498 * Find a mesh state in the mesh area. Pass relevant flags.
500 * @param mesh: the mesh area to look in.
501 * @param cinfo: if non-NULL client specific info that may affect IP-based
502 * actions that apply to the query result.
503 * @param qinfo: what query
504 * @param qflags: if RD / CD bit is set or not.
505 * @param prime: if it is a priming query.
506 * @param valrec: if it is a validation-recursion query.
507 * @return: mesh state or NULL if not found.
509 struct mesh_state* mesh_area_find(struct mesh_area* mesh,
510 struct respip_client_info* cinfo, struct query_info* qinfo,
511 uint16_t qflags, int prime, int valrec);
514 * Setup attachment super/sub relation between super and sub mesh state.
515 * The relation must not be present when calling the function.
516 * Does not update stat items in mesh_area.
517 * @param super: super state.
518 * @param sub: sub state.
519 * @return: 0 on alloc error.
521 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub);
524 * Create new reply structure and attach it to a mesh state.
525 * Does not update stat items in mesh area.
526 * @param s: the mesh state.
527 * @param edns: edns data for reply (bufsize).
528 * @param rep: comm point reply info.
529 * @param qid: ID of reply.
530 * @param qflags: original query flags.
531 * @param qinfo: original query info.
532 * @return: 0 on alloc error.
534 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
535 struct comm_reply* rep, uint16_t qid, uint16_t qflags,
536 const struct query_info* qinfo);
539 * Create new callback structure and attach it to a mesh state.
540 * Does not update stat items in mesh area.
541 * @param s: the mesh state.
542 * @param edns: edns data for reply (bufsize).
543 * @param buf: buffer for reply
544 * @param cb: callback to call with results.
545 * @param cb_arg: callback user arg.
546 * @param qid: ID of reply.
547 * @param qflags: original query flags.
548 * @return: 0 on alloc error.
550 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
551 struct sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg,
552 uint16_t qid, uint16_t qflags);
555 * Run the mesh. Run all runnable mesh states. Which can create new
556 * runnable mesh states. Until completion. Automatically called by
557 * mesh_report_reply and mesh_new_client as needed.
558 * @param mesh: mesh area.
559 * @param mstate: first mesh state to run.
560 * @param ev: event the mstate. Others get event_pass.
561 * @param e: if a reply, its outbound entry.
563 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
564 enum module_ev ev, struct outbound_entry* e);
567 * Print some stats about the mesh to the log.
568 * @param mesh: the mesh to print it for.
569 * @param str: descriptive string to go with it.
571 void mesh_stats(struct mesh_area* mesh, const char* str);
574 * Clear the stats that the mesh keeps (number of queries serviced)
575 * @param mesh: the mesh
577 void mesh_stats_clear(struct mesh_area* mesh);
580 * Print all the states in the mesh to the log.
581 * @param mesh: the mesh to print all states of.
583 void mesh_log_list(struct mesh_area* mesh);
586 * Calculate memory size in use by mesh and all queries inside it.
587 * @param mesh: the mesh to examine.
588 * @return size in bytes.
590 size_t mesh_get_mem(struct mesh_area* mesh);
593 * Find cycle; see if the given mesh is in the targets sub, or sub-sub, ...
595 * If the sub-sub structure is too large, it returns 'a cycle'=2.
596 * @param qstate: given mesh querystate.
597 * @param qinfo: query info for dependency.
598 * @param flags: query flags of dependency.
599 * @param prime: if dependency is a priming query or not.
600 * @param valrec: if it is a validation recursion query (lookup of key, DS).
601 * @return true if the name,type,class exists and the given qstate mesh exists
602 * as a dependency of that name. Thus if qstate becomes dependent on
603 * name,type,class then a cycle is created, this is return value 1.
604 * Too large to search is value 2 (also true).
606 int mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
607 uint16_t flags, int prime, int valrec);
609 /** compare two mesh_states */
610 int mesh_state_compare(const void* ap, const void* bp);
612 /** compare two mesh references */
613 int mesh_state_ref_compare(const void* ap, const void* bp);
616 * Make space for another recursion state for a reply in the mesh
617 * @param mesh: mesh area
618 * @param qbuf: query buffer to save if recursion is invoked to make space.
619 * This buffer is necessary, because the following sequence in calls
620 * can result in an overwrite of the incoming query:
621 * delete_other_mesh_query - iter_clean - serviced_delete - waiting
622 * udp query is sent - on error callback - callback sends SERVFAIL reply
623 * over the same network channel, and shared UDP buffer is overwritten.
624 * You can pass NULL if there is no buffer that must be backed up.
625 * @return false if no space is available.
627 int mesh_make_new_space(struct mesh_area* mesh, struct sldns_buffer* qbuf);
630 * Insert mesh state into a double linked list. Inserted at end.
631 * @param m: mesh state.
632 * @param fp: pointer to the first-elem-pointer of the list.
633 * @param lp: pointer to the last-elem-pointer of the list.
635 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
636 struct mesh_state** lp);
639 * Remove mesh state from a double linked list. Remove from any position.
640 * @param m: mesh state.
641 * @param fp: pointer to the first-elem-pointer of the list.
642 * @param lp: pointer to the last-elem-pointer of the list.
644 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
645 struct mesh_state** lp);
648 * Remove mesh reply entry from the reply entry list. Searches for
649 * the comm_point pointer.
650 * @param mesh: to update the counters.
651 * @param m: the mesh state.
652 * @param cp: the comm_point to remove from the list.
654 void mesh_state_remove_reply(struct mesh_area* mesh, struct mesh_state* m,
655 struct comm_point* cp);
657 /** Callback for when the serve expired client timer has run out. Tries to
658 * find an expired answer in the cache and reply that to the client.
659 * @param arg: the argument passed to the callback.
661 void mesh_serve_expired_callback(void* arg);
664 * Try to get a (expired) cached answer.
665 * This needs to behave like the worker's answer_from_cache() in order to have
666 * the same behavior as when replying from cache.
667 * @param qstate: the module qstate.
668 * @param lookup_qinfo: the query info to look for in the cache.
669 * @return dns_msg if a cached answer was found, otherwise NULL.
672 mesh_serve_expired_lookup(struct module_qstate* qstate,
673 struct query_info* lookup_qinfo);
675 #endif /* SERVICES_MESH_H */