]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/services/mesh.h
Upgrade Unbound to 1.6.0. More to follow.
[FreeBSD/FreeBSD.git] / contrib / unbound / services / mesh.h
1 /*
2  * services/mesh.h - deal with mesh of query states and handle events for that.
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 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.
44  */
45
46 #ifndef SERVICES_MESH_H
47 #define SERVICES_MESH_H
48
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 struct sldns_buffer;
55 struct mesh_state;
56 struct mesh_reply;
57 struct mesh_cb;
58 struct query_info;
59 struct reply_info;
60 struct outbound_entry;
61 struct timehist;
62
63 /**
64  * Maximum number of mesh state activations. Any more is likely an
65  * infinite loop in the module. It is then terminated.
66  */
67 #define MESH_MAX_ACTIVATION 3000
68
69 /**
70  * Max number of references-to-references-to-references.. search size.
71  * Any more is treated like 'too large', and the creation of a new
72  * dependency is failed (so that no loops can be created).
73  */
74 #define MESH_MAX_SUBSUB 1024
75
76 /** 
77  * Mesh of query states
78  */
79 struct mesh_area {
80         /** active module stack */
81         struct module_stack mods;
82         /** environment for new states */
83         struct module_env* env;
84
85         /** set of runnable queries (mesh_state.run_node) */
86         rbtree_t run;
87         /** rbtree of all current queries (mesh_state.node)*/
88         rbtree_t all;
89
90         /** count of the total number of mesh_reply entries */
91         size_t num_reply_addrs;
92         /** count of the number of mesh_states that have mesh_replies 
93          * Because a state can send results to multiple reply addresses,
94          * this number must be equal or lower than num_reply_addrs. */
95         size_t num_reply_states;
96         /** number of mesh_states that have no mesh_replies, and also
97          * an empty set of super-states, thus are 'toplevel' or detached
98          * internal opportunistic queries */
99         size_t num_detached_states;
100         /** number of reply states in the forever list */
101         size_t num_forever_states;
102
103         /** max total number of reply states to have */
104         size_t max_reply_states;
105         /** max forever number of reply states to have */
106         size_t max_forever_states;
107
108         /** stats, cumulative number of reply states jostled out */
109         size_t stats_jostled;
110         /** stats, cumulative number of incoming client msgs dropped */
111         size_t stats_dropped;
112         /** number of replies sent */
113         size_t replies_sent;
114         /** sum of waiting times for the replies */
115         struct timeval replies_sum_wait;
116         /** histogram of time values */
117         struct timehist* histogram;
118         /** (extended stats) secure replies */
119         size_t ans_secure;
120         /** (extended stats) bogus replies */
121         size_t ans_bogus;
122         /** (extended stats) rcodes in replies */
123         size_t ans_rcode[16];
124         /** (extended stats) rcode nodata in replies */
125         size_t ans_nodata;
126
127         /** backup of query if other operations recurse and need the
128          * network buffers */
129         struct sldns_buffer* qbuf_bak;
130
131         /** double linked list of the run-to-completion query states.
132          * These are query states with a reply */
133         struct mesh_state* forever_first;
134         /** last entry in run forever list */
135         struct mesh_state* forever_last;
136
137         /** double linked list of the query states that can be jostled out
138          * by new queries if too old.  These are query states with a reply */
139         struct mesh_state* jostle_first;
140         /** last entry in jostle list - this is the entry that is newest */
141         struct mesh_state* jostle_last;
142         /** timeout for jostling. if age is lower, it does not get jostled. */
143         struct timeval jostle_max;
144 };
145
146 /**
147  * A mesh query state
148  * Unique per qname, qtype, qclass (from the qstate).
149  * And RD / CD flag; in case a client turns it off.
150  * And priming queries are different from ordinary queries (because of hints).
151  *
152  * The entire structure is allocated in a region, this region is the qstate
153  * region. All parts (rbtree nodes etc) are also allocated in the region.
154  */
155 struct mesh_state {
156         /** node in mesh_area all tree, key is this struct. Must be first. */
157         rbnode_t node;
158         /** node in mesh_area runnable tree, key is this struct */
159         rbnode_t run_node;
160         /** the query state. Note that the qinfo and query_flags 
161          * may not change. */
162         struct module_qstate s;
163         /** the list of replies to clients for the results */
164         struct mesh_reply* reply_list;
165         /** the list of callbacks for the results */
166         struct mesh_cb* cb_list;
167         /** set of superstates (that want this state's result) 
168          * contains struct mesh_state_ref* */
169         rbtree_t super_set;
170         /** set of substates (that this state needs to continue)
171          * contains struct mesh_state_ref* */
172         rbtree_t sub_set;
173         /** number of activations for the mesh state */
174         size_t num_activated;
175
176         /** previous in linked list for reply states */
177         struct mesh_state* prev;
178         /** next in linked list for reply states */
179         struct mesh_state* next;
180         /** if this state is in the forever list, jostle list, or neither */
181         enum mesh_list_select { mesh_no_list, mesh_forever_list, 
182                 mesh_jostle_list } list_select;
183         /** pointer to this state for uniqueness or NULL */
184         struct mesh_state* unique;
185
186         /** true if replies have been sent out (at end for alignment) */
187         uint8_t replies_sent;
188 };
189
190 /**
191  * Rbtree reference to a mesh_state.
192  * Used in super_set and sub_set. 
193  */
194 struct mesh_state_ref {
195         /** node in rbtree for set, key is this structure */
196         rbnode_t node;
197         /** the mesh state */
198         struct mesh_state* s;
199 };
200
201 /**
202  * Reply to a client
203  */
204 struct mesh_reply {
205         /** next in reply list */
206         struct mesh_reply* next;
207         /** the query reply destination, packet buffer and where to send. */
208         struct comm_reply query_reply;
209         /** edns data from query */
210         struct edns_data edns;
211         /** the time when request was entered */
212         struct timeval start_time;
213         /** id of query, in network byteorder. */
214         uint16_t qid;
215         /** flags of query, for reply flags */
216         uint16_t qflags;
217         /** qname from this query. len same as mesh qinfo. */
218         uint8_t* qname;
219         /** same as that in query_info. */
220         struct local_rrset* local_alias;
221 };
222
223 /** 
224  * Mesh result callback func.
225  * called as func(cb_arg, rcode, buffer_with_reply, security, why_bogus);
226  */
227 typedef void (*mesh_cb_func_t)(void*, int, struct sldns_buffer*, enum sec_status, 
228         char*);
229
230 /**
231  * Callback to result routine
232  */
233 struct mesh_cb {
234         /** next in list */
235         struct mesh_cb* next;
236         /** edns data from query */
237         struct edns_data edns;
238         /** id of query, in network byteorder. */
239         uint16_t qid;
240         /** flags of query, for reply flags */
241         uint16_t qflags;
242         /** buffer for reply */
243         struct sldns_buffer* buf;
244
245         /** callback routine for results. if rcode != 0 buf has message.
246          * called as cb(cb_arg, rcode, buf, sec_state);
247          */
248         mesh_cb_func_t cb;
249         /** user arg for callback */
250         void* cb_arg;
251 };
252
253 /* ------------------- Functions for worker -------------------- */
254
255 /**
256  * Allocate mesh, to empty.
257  * @param stack: module stack to activate, copied (as readonly reference).
258  * @param env: environment for new queries.
259  * @return mesh: the new mesh or NULL on error.
260  */
261 struct mesh_area* mesh_create(struct module_stack* stack, 
262         struct module_env* env);
263
264 /**
265  * Delete mesh, and all query states and replies in it.
266  * @param mesh: the mesh to delete.
267  */
268 void mesh_delete(struct mesh_area* mesh);
269
270 /**
271  * New query incoming from clients. Create new query state if needed, and
272  * add mesh_reply to it. Returns error to client on malloc failures.
273  * Will run the mesh area queries to process if a new query state is created.
274  *
275  * @param mesh: the mesh.
276  * @param qinfo: query from client.
277  * @param qflags: flags from client query.
278  * @param edns: edns data from client query.
279  * @param rep: where to reply to.
280  * @param qid: query id to reply with.
281  */
282 void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
283         uint16_t qflags, struct edns_data* edns, struct comm_reply* rep, 
284         uint16_t qid);
285
286 /**
287  * New query with callback. Create new query state if needed, and
288  * add mesh_cb to it. 
289  * Will run the mesh area queries to process if a new query state is created.
290  *
291  * @param mesh: the mesh.
292  * @param qinfo: query from client.
293  * @param qflags: flags from client query.
294  * @param edns: edns data from client query.
295  * @param buf: buffer for reply contents.
296  * @param qid: query id to reply with.
297  * @param cb: callback function.
298  * @param cb_arg: callback user arg.
299  * @return 0 on error.
300  */
301 int mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
302         uint16_t qflags, struct edns_data* edns, struct sldns_buffer* buf, 
303         uint16_t qid, mesh_cb_func_t cb, void* cb_arg);
304
305 /**
306  * New prefetch message. Create new query state if needed.
307  * Will run the mesh area queries to process if a new query state is created.
308  *
309  * @param mesh: the mesh.
310  * @param qinfo: query from client.
311  * @param qflags: flags from client query.
312  * @param leeway: TTL leeway what to expire earlier for this update.
313  */
314 void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
315         uint16_t qflags, time_t leeway);
316
317 /**
318  * Handle new event from the wire. A serviced query has returned.
319  * The query state will be made runnable, and the mesh_area will process
320  * query states until processing is complete.
321  *
322  * @param mesh: the query mesh.
323  * @param e: outbound entry, with query state to run and reply pointer.
324  * @param reply: the comm point reply info.
325  * @param what: NETEVENT_* error code (if not 0, what is wrong, TIMEOUT).
326  */
327 void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
328         struct comm_reply* reply, int what);
329
330 /* ------------------- Functions for module environment --------------- */
331
332 /**
333  * Detach-subqueries.
334  * Remove all sub-query references from this query state.
335  * Keeps super-references of those sub-queries correct.
336  * Updates stat items in mesh_area structure.
337  * @param qstate: used to find mesh state.
338  */
339 void mesh_detach_subs(struct module_qstate* qstate);
340
341 /**
342  * Attach subquery.
343  * Creates it if it does not exist already.
344  * Keeps sub and super references correct.
345  * Performs a cycle detection - for double check - and fails if there is one.
346  * Also fails if the sub-sub-references become too large.
347  * Updates stat items in mesh_area structure.
348  * Pass if it is priming query or not.
349  * return:
350  *      o if error (malloc) happened.
351  *      o need to initialise the new state (module init; it is a new state).
352  *        so that the next run of the query with this module is successful.
353  *      o no init needed, attachment successful.
354  *
355  * @param qstate: the state to find mesh state, and that wants to receive
356  *      the results from the new subquery.
357  * @param qinfo: what to query for (copied).
358  * @param qflags: what flags to use (RD / CD flag or not).
359  * @param prime: if it is a (stub) priming query.
360  * @param valrec: if it is a validation recursion query (lookup of key, DS).
361  * @param newq: If the new subquery needs initialisation, it is returned,
362  *      otherwise NULL is returned.
363  * @return: false on error, true if success (and init may be needed).
364  */
365 int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
366         uint16_t qflags, int prime, int valrec, struct module_qstate** newq);
367
368 /**
369  * Query state is done, send messages to reply entries.
370  * Encode messages using reply entry values and the querystate (with original
371  * qinfo), using given reply_info.
372  * Pass errcode != 0 if an error reply is needed.
373  * If no reply entries, nothing is done.
374  * Must be called before a module can module_finished or return module_error.
375  * The module must handle the super query states itself as well.
376  *
377  * @param mstate: mesh state that is done. return_rcode and return_msg
378  *      are used for replies.
379  *      return_rcode: if not 0 (NOERROR) an error is sent back (and 
380  *              return_msg is ignored).
381  *      return_msg: reply to encode and send back to clients.
382  */
383 void mesh_query_done(struct mesh_state* mstate);
384
385 /**
386  * Call inform_super for the super query states that are interested in the 
387  * results from this query state. These can then be changed for error 
388  * or results.
389  * Called when a module is module_finished or returns module_error.
390  * The super query states become runnable with event module_event_pass,
391  * it calls the current module for the super with the inform_super event.
392  *
393  * @param mesh: mesh area to add newly runnable modules to.
394  * @param mstate: the state that has results, used to find mesh state.
395  */
396 void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate);
397
398 /**
399  * Delete mesh state, cleanup and also rbtrees and so on.
400  * Will detach from all super/subnodes.
401  * @param qstate: to remove.
402  */
403 void mesh_state_delete(struct module_qstate* qstate);
404
405 /* ------------------- Functions for mesh -------------------- */
406
407 /**
408  * Create and initialize a new mesh state and its query state
409  * Does not put the mesh state into rbtrees and so on.
410  * @param env: module environment to set.
411  * @param qinfo: query info that the mesh is for.
412  * @param qflags: flags for query (RD / CD flag).
413  * @param prime: if true, it is a priming query, set is_priming on mesh state.
414  * @param valrec: if true, it is a validation recursion query, and sets
415  *      is_valrec on the mesh state.
416  * @return: new mesh state or NULL on allocation error.
417  */
418 struct mesh_state* mesh_state_create(struct module_env* env, 
419         struct query_info* qinfo, uint16_t qflags, int prime, int valrec);
420
421 /**
422  * Check if the mesh state is unique.
423  * A unique mesh state uses it's unique member to point to itself, else NULL.
424  * @param mstate: mesh state to check.
425  * @return true if the mesh state is unique, false otherwise.
426  */
427 int mesh_state_is_unique(struct mesh_state* mstate);
428
429 /**
430  * Make a mesh state unique.
431  * A unique mesh state uses it's unique member to point to itself.
432  * @param mstate: mesh state to check.
433  */
434 void mesh_state_make_unique(struct mesh_state* mstate);
435
436 /**
437  * Cleanup a mesh state and its query state. Does not do rbtree or 
438  * reference cleanup.
439  * @param mstate: mesh state to cleanup. Its pointer may no longer be used
440  *      afterwards. Cleanup rbtrees before calling this function.
441  */
442 void mesh_state_cleanup(struct mesh_state* mstate);
443
444 /**
445  * Delete all mesh states from the mesh.
446  * @param mesh: the mesh area to clear
447  */
448 void mesh_delete_all(struct mesh_area* mesh);
449
450 /**
451  * Find a mesh state in the mesh area. Pass relevant flags.
452  *
453  * @param mesh: the mesh area to look in.
454  * @param qinfo: what query
455  * @param qflags: if RD / CD bit is set or not.
456  * @param prime: if it is a priming query.
457  * @param valrec: if it is a validation-recursion query.
458  * @return: mesh state or NULL if not found.
459  */
460 struct mesh_state* mesh_area_find(struct mesh_area* mesh, 
461         struct query_info* qinfo, uint16_t qflags, int prime, int valrec);
462
463 /**
464  * Setup attachment super/sub relation between super and sub mesh state.
465  * The relation must not be present when calling the function.
466  * Does not update stat items in mesh_area.
467  * @param super: super state.
468  * @param sub: sub state.
469  * @return: 0 on alloc error.
470  */
471 int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub);
472
473 /**
474  * Create new reply structure and attach it to a mesh state.
475  * Does not update stat items in mesh area.
476  * @param s: the mesh state.
477  * @param edns: edns data for reply (bufsize).
478  * @param rep: comm point reply info.
479  * @param qid: ID of reply.
480  * @param qflags: original query flags.
481  * @param qinfo: original query info.
482  * @return: 0 on alloc error.
483  */
484 int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
485         struct comm_reply* rep, uint16_t qid, uint16_t qflags,
486         const struct query_info* qinfo);
487
488 /**
489  * Create new callback structure and attach it to a mesh state.
490  * Does not update stat items in mesh area.
491  * @param s: the mesh state.
492  * @param edns: edns data for reply (bufsize).
493  * @param buf: buffer for reply
494  * @param cb: callback to call with results.
495  * @param cb_arg: callback user arg.
496  * @param qid: ID of reply.
497  * @param qflags: original query flags.
498  * @return: 0 on alloc error.
499  */
500 int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
501         struct sldns_buffer* buf, mesh_cb_func_t cb, void* cb_arg, uint16_t qid, 
502         uint16_t qflags);
503
504 /**
505  * Run the mesh. Run all runnable mesh states. Which can create new
506  * runnable mesh states. Until completion. Automatically called by
507  * mesh_report_reply and mesh_new_client as needed.
508  * @param mesh: mesh area.
509  * @param mstate: first mesh state to run.
510  * @param ev: event the mstate. Others get event_pass.
511  * @param e: if a reply, its outbound entry.
512  */
513 void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate, 
514         enum module_ev ev, struct outbound_entry* e);
515
516 /**
517  * Print some stats about the mesh to the log.
518  * @param mesh: the mesh to print it for.
519  * @param str: descriptive string to go with it.
520  */
521 void mesh_stats(struct mesh_area* mesh, const char* str);
522
523 /**
524  * Clear the stats that the mesh keeps (number of queries serviced)
525  * @param mesh: the mesh
526  */
527 void mesh_stats_clear(struct mesh_area* mesh);
528
529 /**
530  * Print all the states in the mesh to the log.
531  * @param mesh: the mesh to print all states of.
532  */
533 void mesh_log_list(struct mesh_area* mesh);
534
535 /**
536  * Calculate memory size in use by mesh and all queries inside it.
537  * @param mesh: the mesh to examine.
538  * @return size in bytes.
539  */
540 size_t mesh_get_mem(struct mesh_area* mesh);
541
542 /**
543  * Find cycle; see if the given mesh is in the targets sub, or sub-sub, ...
544  * trees.
545  * If the sub-sub structure is too large, it returns 'a cycle'=2.
546  * @param qstate: given mesh querystate.
547  * @param qinfo: query info for dependency.
548  * @param flags: query flags of dependency.
549  * @param prime: if dependency is a priming query or not.
550  * @param valrec: if it is a validation recursion query (lookup of key, DS).
551  * @return true if the name,type,class exists and the given qstate mesh exists
552  *      as a dependency of that name. Thus if qstate becomes dependent on
553  *      name,type,class then a cycle is created, this is return value 1.
554  *      Too large to search is value 2 (also true).
555  */
556 int mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
557         uint16_t flags, int prime, int valrec);
558
559 /** compare two mesh_states */
560 int mesh_state_compare(const void* ap, const void* bp);
561
562 /** compare two mesh references */
563 int mesh_state_ref_compare(const void* ap, const void* bp);
564
565 /**
566  * Make space for another recursion state for a reply in the mesh
567  * @param mesh: mesh area
568  * @param qbuf: query buffer to save if recursion is invoked to make space.
569  *    This buffer is necessary, because the following sequence in calls
570  *    can result in an overwrite of the incoming query:
571  *    delete_other_mesh_query - iter_clean - serviced_delete - waiting
572  *    udp query is sent - on error callback - callback sends SERVFAIL reply
573  *    over the same network channel, and shared UDP buffer is overwritten.
574  *    You can pass NULL if there is no buffer that must be backed up.
575  * @return false if no space is available.
576  */
577 int mesh_make_new_space(struct mesh_area* mesh, struct sldns_buffer* qbuf);
578
579 /**
580  * Insert mesh state into a double linked list.  Inserted at end.
581  * @param m: mesh state.
582  * @param fp: pointer to the first-elem-pointer of the list.
583  * @param lp: pointer to the last-elem-pointer of the list.
584  */
585 void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
586         struct mesh_state** lp);
587
588 /**
589  * Remove mesh state from a double linked list.  Remove from any position.
590  * @param m: mesh state.
591  * @param fp: pointer to the first-elem-pointer of the list.
592  * @param lp: pointer to the last-elem-pointer of the list.
593  */
594 void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
595         struct mesh_state** lp);
596
597 #endif /* SERVICES_MESH_H */