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;
233 /** send query to this http2 stream, if set */
234 struct http2_stream* h2_stream;
238 * Mesh result callback func.
239 * called as func(cb_arg, rcode, buffer_with_reply, security, why_bogus,
242 typedef void (*mesh_cb_func_type)(void* cb_arg, int rcode, struct sldns_buffer*,
243 enum sec_status, char* why_bogus, int was_ratelimited);
246 * Callback to result routine
250 struct mesh_cb* next;
251 /** edns data from query */
252 struct edns_data edns;
253 /** id of query, in network byteorder. */
255 /** flags of query, for reply flags */
257 /** buffer for reply */
258 struct sldns_buffer* buf;
259 /** callback routine for results. if rcode != 0 buf has message.
260 * called as cb(cb_arg, rcode, buf, sec_state, why_bogus, was_ratelimited);
262 mesh_cb_func_type cb;
263 /** user arg for callback */
267 /* ------------------- Functions for worker -------------------- */
270 * Allocate mesh, to empty.
271 * @param stack: module stack to activate, copied (as readonly reference).
272 * @param env: environment for new queries.
273 * @return mesh: the new mesh or NULL on error.
275 struct mesh_area* mesh_create(struct module_stack* stack,
276 struct module_env* env);
279 * Delete mesh, and all query states and replies in it.
280 * @param mesh: the mesh to delete.
282 void mesh_delete(struct mesh_area* mesh);
285 * New query incoming from clients. Create new query state if needed, and
286 * add mesh_reply to it. Returns error to client on malloc failures.
287 * Will run the mesh area queries to process if a new query state is created.
289 * @param mesh: the mesh.
290 * @param qinfo: query from client.
291 * @param cinfo: additional information associated with the query client.
292 * 'cinfo' itself is ephemeral but data pointed to by its members
293 * can be assumed to be valid and unchanged until the query processing is
295 * @param qflags: flags from client query.
296 * @param edns: edns data from client query.
297 * @param rep: where to reply to.
298 * @param qid: query id to reply with.
300 void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
301 struct respip_client_info* cinfo, uint16_t qflags,
302 struct edns_data* edns, struct comm_reply* rep, uint16_t qid);
305 * New query with callback. Create new query state if needed, and
307 * Will run the mesh area queries to process if a new query state is created.
309 * @param mesh: the mesh.
310 * @param qinfo: query from client.
311 * @param qflags: flags from client query.
312 * @param edns: edns data from client query.
313 * @param buf: buffer for reply contents.
314 * @param qid: query id to reply with.
315 * @param cb: callback function.
316 * @param cb_arg: callback user arg.
317 * @return 0 on error.
319 int mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
320 uint16_t qflags, struct edns_data* edns, struct sldns_buffer* buf,
321 uint16_t qid, mesh_cb_func_type cb, void* cb_arg);
324 * New prefetch message. Create new query state if needed.
325 * Will run the mesh area queries to process if a new query state is created.
327 * @param mesh: the mesh.
328 * @param qinfo: query from client.
329 * @param qflags: flags from client query.
330 * @param leeway: TTL leeway what to expire earlier for this update.
332 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
333 uint16_t qflags, time_t leeway);
336 * Handle new event from the wire. A serviced query has returned.
337 * The query state will be made runnable, and the mesh_area will process
338 * query states until processing is complete.
340 * @param mesh: the query mesh.
341 * @param e: outbound entry, with query state to run and reply pointer.
342 * @param reply: the comm point reply info.
343 * @param what: NETEVENT_* error code (if not 0, what is wrong, TIMEOUT).
345 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
346 struct comm_reply* reply, int what);
348 /* ------------------- Functions for module environment --------------- */
352 * Remove all sub-query references from this query state.
353 * Keeps super-references of those sub-queries correct.
354 * Updates stat items in mesh_area structure.
355 * @param qstate: used to find mesh state.
357 void mesh_detach_subs(struct module_qstate* qstate);
361 * Creates it if it does not exist already.
362 * Keeps sub and super references correct.
363 * Performs a cycle detection - for double check - and fails if there is one.
364 * Also fails if the sub-sub-references become too large.
365 * Updates stat items in mesh_area structure.
366 * Pass if it is priming query or not.
368 * o if error (malloc) happened.
369 * o need to initialise the new state (module init; it is a new state).
370 * so that the next run of the query with this module is successful.
371 * o no init needed, attachment successful.
373 * @param qstate: the state to find mesh state, and that wants to receive
374 * the results from the new subquery.
375 * @param qinfo: what to query for (copied).
376 * @param qflags: what flags to use (RD / CD flag or not).
377 * @param prime: if it is a (stub) priming query.
378 * @param valrec: if it is a validation recursion query (lookup of key, DS).
379 * @param newq: If the new subquery needs initialisation, it is returned,
380 * otherwise NULL is returned.
381 * @return: false on error, true if success (and init may be needed).
383 int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
384 uint16_t qflags, int prime, int valrec, struct module_qstate** newq);
387 * Add detached query.
388 * Creates it if it does not exist already.
389 * Does not make super/sub references.
390 * Performs a cycle detection - for double check - and fails if there is one.
391 * Updates stat items in mesh_area structure.
392 * Pass if it is priming query or not.
394 * o if error (malloc) happened.
395 * o need to initialise the new state (module init; it is a new state).
396 * so that the next run of the query with this module is successful.
397 * o no init needed, attachment successful.
398 * o added subquery, created if it did not exist already.
400 * @param qstate: the state to find mesh state, and that wants to receive
401 * the results from the new subquery.
402 * @param qinfo: what to query for (copied).
403 * @param qflags: what flags to use (RD / CD flag or not).
404 * @param prime: if it is a (stub) priming query.
405 * @param valrec: if it is a validation recursion query (lookup of key, DS).
406 * @param newq: If the new subquery needs initialisation, it is returned,
407 * otherwise NULL is returned.
408 * @param sub: The added mesh state, created if it did not exist already.
409 * @return: false on error, true if success (and init may be needed).
411 int mesh_add_sub(struct module_qstate* qstate, struct query_info* qinfo,
412 uint16_t qflags, int prime, int valrec, struct module_qstate** newq,
413 struct mesh_state** sub);
416 * Query state is done, send messages to reply entries.
417 * Encode messages using reply entry values and the querystate (with original
418 * qinfo), using given reply_info.
419 * Pass errcode != 0 if an error reply is needed.
420 * If no reply entries, nothing is done.
421 * Must be called before a module can module_finished or return module_error.
422 * The module must handle the super query states itself as well.
424 * @param mstate: mesh state that is done. return_rcode and return_msg
425 * are used for replies.
426 * return_rcode: if not 0 (NOERROR) an error is sent back (and
427 * return_msg is ignored).
428 * return_msg: reply to encode and send back to clients.
430 void mesh_query_done(struct mesh_state* mstate);
433 * Call inform_super for the super query states that are interested in the
434 * results from this query state. These can then be changed for error
436 * Called when a module is module_finished or returns module_error.
437 * The super query states become runnable with event module_event_pass,
438 * it calls the current module for the super with the inform_super event.
440 * @param mesh: mesh area to add newly runnable modules to.
441 * @param mstate: the state that has results, used to find mesh state.
443 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate);
446 * Delete mesh state, cleanup and also rbtrees and so on.
447 * Will detach from all super/subnodes.
448 * @param qstate: to remove.
450 void mesh_state_delete(struct module_qstate* qstate);
452 /* ------------------- Functions for mesh -------------------- */
455 * Create and initialize a new mesh state and its query state
456 * Does not put the mesh state into rbtrees and so on.
457 * @param env: module environment to set.
458 * @param qinfo: query info that the mesh is for.
459 * @param cinfo: control info for the query client (can be NULL).
460 * @param qflags: flags for query (RD / CD flag).
461 * @param prime: if true, it is a priming query, set is_priming on mesh state.
462 * @param valrec: if true, it is a validation recursion query, and sets
463 * is_valrec on the mesh state.
464 * @return: new mesh state or NULL on allocation error.
466 struct mesh_state* mesh_state_create(struct module_env* env,
467 struct query_info* qinfo, struct respip_client_info* cinfo,
468 uint16_t qflags, int prime, int valrec);
471 * Check if the mesh state is unique.
472 * A unique mesh state uses it's unique member to point to itself, else NULL.
473 * @param mstate: mesh state to check.
474 * @return true if the mesh state is unique, false otherwise.
476 int mesh_state_is_unique(struct mesh_state* mstate);
479 * Make a mesh state unique.
480 * A unique mesh state uses it's unique member to point to itself.
481 * @param mstate: mesh state to check.
483 void mesh_state_make_unique(struct mesh_state* mstate);
486 * Cleanup a mesh state and its query state. Does not do rbtree or
488 * @param mstate: mesh state to cleanup. Its pointer may no longer be used
489 * afterwards. Cleanup rbtrees before calling this function.
491 void mesh_state_cleanup(struct mesh_state* mstate);
494 * Delete all mesh states from the mesh.
495 * @param mesh: the mesh area to clear
497 void mesh_delete_all(struct mesh_area* mesh);
500 * Find a mesh state in the mesh area. Pass relevant flags.
502 * @param mesh: the mesh area to look in.
503 * @param cinfo: if non-NULL client specific info that may affect IP-based
504 * actions that apply to the query result.
505 * @param qinfo: what query
506 * @param qflags: if RD / CD bit is set or not.
507 * @param prime: if it is a priming query.
508 * @param valrec: if it is a validation-recursion query.
509 * @return: mesh state or NULL if not found.
511 struct mesh_state* mesh_area_find(struct mesh_area* mesh,
512 struct respip_client_info* cinfo, struct query_info* qinfo,
513 uint16_t qflags, int prime, int valrec);
516 * Setup attachment super/sub relation between super and sub mesh state.
517 * The relation must not be present when calling the function.
518 * Does not update stat items in mesh_area.
519 * @param super: super state.
520 * @param sub: sub state.
521 * @return: 0 on alloc error.
523 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub);
526 * Create new reply structure and attach it to a mesh state.
527 * Does not update stat items in mesh area.
528 * @param s: the mesh state.
529 * @param edns: edns data for reply (bufsize).
530 * @param rep: comm point reply info.
531 * @param qid: ID of reply.
532 * @param qflags: original query flags.
533 * @param qinfo: original query info.
534 * @return: 0 on alloc error.
536 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
537 struct comm_reply* rep, uint16_t qid, uint16_t qflags,
538 const struct query_info* qinfo);
541 * Create new callback structure and attach it to a mesh state.
542 * Does not update stat items in mesh area.
543 * @param s: the mesh state.
544 * @param edns: edns data for reply (bufsize).
545 * @param buf: buffer for reply
546 * @param cb: callback to call with results.
547 * @param cb_arg: callback user arg.
548 * @param qid: ID of reply.
549 * @param qflags: original query flags.
550 * @return: 0 on alloc error.
552 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
553 struct sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg,
554 uint16_t qid, uint16_t qflags);
557 * Run the mesh. Run all runnable mesh states. Which can create new
558 * runnable mesh states. Until completion. Automatically called by
559 * mesh_report_reply and mesh_new_client as needed.
560 * @param mesh: mesh area.
561 * @param mstate: first mesh state to run.
562 * @param ev: event the mstate. Others get event_pass.
563 * @param e: if a reply, its outbound entry.
565 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
566 enum module_ev ev, struct outbound_entry* e);
569 * Print some stats about the mesh to the log.
570 * @param mesh: the mesh to print it for.
571 * @param str: descriptive string to go with it.
573 void mesh_stats(struct mesh_area* mesh, const char* str);
576 * Clear the stats that the mesh keeps (number of queries serviced)
577 * @param mesh: the mesh
579 void mesh_stats_clear(struct mesh_area* mesh);
582 * Print all the states in the mesh to the log.
583 * @param mesh: the mesh to print all states of.
585 void mesh_log_list(struct mesh_area* mesh);
588 * Calculate memory size in use by mesh and all queries inside it.
589 * @param mesh: the mesh to examine.
590 * @return size in bytes.
592 size_t mesh_get_mem(struct mesh_area* mesh);
595 * Find cycle; see if the given mesh is in the targets sub, or sub-sub, ...
597 * If the sub-sub structure is too large, it returns 'a cycle'=2.
598 * @param qstate: given mesh querystate.
599 * @param qinfo: query info for dependency.
600 * @param flags: query flags of dependency.
601 * @param prime: if dependency is a priming query or not.
602 * @param valrec: if it is a validation recursion query (lookup of key, DS).
603 * @return true if the name,type,class exists and the given qstate mesh exists
604 * as a dependency of that name. Thus if qstate becomes dependent on
605 * name,type,class then a cycle is created, this is return value 1.
606 * Too large to search is value 2 (also true).
608 int mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
609 uint16_t flags, int prime, int valrec);
611 /** compare two mesh_states */
612 int mesh_state_compare(const void* ap, const void* bp);
614 /** compare two mesh references */
615 int mesh_state_ref_compare(const void* ap, const void* bp);
618 * Make space for another recursion state for a reply in the mesh
619 * @param mesh: mesh area
620 * @param qbuf: query buffer to save if recursion is invoked to make space.
621 * This buffer is necessary, because the following sequence in calls
622 * can result in an overwrite of the incoming query:
623 * delete_other_mesh_query - iter_clean - serviced_delete - waiting
624 * udp query is sent - on error callback - callback sends SERVFAIL reply
625 * over the same network channel, and shared UDP buffer is overwritten.
626 * You can pass NULL if there is no buffer that must be backed up.
627 * @return false if no space is available.
629 int mesh_make_new_space(struct mesh_area* mesh, struct sldns_buffer* qbuf);
632 * Insert mesh state into a double linked list. Inserted at end.
633 * @param m: mesh state.
634 * @param fp: pointer to the first-elem-pointer of the list.
635 * @param lp: pointer to the last-elem-pointer of the list.
637 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
638 struct mesh_state** lp);
641 * Remove mesh state from a double linked list. Remove from any position.
642 * @param m: mesh state.
643 * @param fp: pointer to the first-elem-pointer of the list.
644 * @param lp: pointer to the last-elem-pointer of the list.
646 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
647 struct mesh_state** lp);
650 * Remove mesh reply entry from the reply entry list. Searches for
651 * the comm_point pointer.
652 * @param mesh: to update the counters.
653 * @param m: the mesh state.
654 * @param cp: the comm_point to remove from the list.
656 void mesh_state_remove_reply(struct mesh_area* mesh, struct mesh_state* m,
657 struct comm_point* cp);
659 /** Callback for when the serve expired client timer has run out. Tries to
660 * find an expired answer in the cache and reply that to the client.
661 * @param arg: the argument passed to the callback.
663 void mesh_serve_expired_callback(void* arg);
666 * Try to get a (expired) cached answer.
667 * This needs to behave like the worker's answer_from_cache() in order to have
668 * the same behavior as when replying from cache.
669 * @param qstate: the module qstate.
670 * @param lookup_qinfo: the query info to look for in the cache.
671 * @return dns_msg if a cached answer was found, otherwise NULL.
674 mesh_serve_expired_lookup(struct module_qstate* qstate,
675 struct query_info* lookup_qinfo);
677 #endif /* SERVICES_MESH_H */