2 * services/outside_network.h - listen to answers from the network
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 has functions to send queries to authoritative servers,
40 * and wait for the pending answer, with timeouts.
43 #ifndef OUTSIDE_NETWORK_H
44 #define OUTSIDE_NETWORK_H
46 #include "util/rbtree.h"
47 #include "util/netevent.h"
48 #include "dnstap/dnstap_config.h"
50 struct pending_timeout;
59 struct serviced_query;
67 * Send queries to outside servers and wait for answers from servers.
68 * Contains answer-listen sockets.
70 struct outside_network {
71 /** Base for select calls */
72 struct comm_base* base;
73 /** pointer to time in seconds */
75 /** pointer to time in microseconds */
76 struct timeval* now_tv;
78 /** buffer shared by UDP connections, since there is only one
79 datagram at any time. */
80 struct sldns_buffer* udp_buff;
81 /** serviced_callbacks malloc overhead when processing multiple
82 * identical serviced queries to the same server. */
84 /** use x20 bits to encode additional ID random bits */
86 /** outside network wants to quit. Stop queued msgs from sent. */
89 /** number of unwanted replies received (for statistics) */
90 size_t unwanted_replies;
91 /** cumulative total of unwanted replies (for defense) */
92 size_t unwanted_total;
93 /** threshold when to take defensive action. If 0 then never. */
94 size_t unwanted_threshold;
95 /** what action to take, called when defensive action is needed */
96 void (*unwanted_action)(void*);
97 /** user param for action */
100 /** linked list of available commpoints, unused file descriptors,
101 * for use as outgoing UDP ports. cp.fd=-1 in them. */
102 struct port_comm* unused_fds;
103 /** if udp is done */
105 /** if udp is delay-closed (delayed answers do not meet closed port)*/
107 /** timeout for delayclose */
108 struct timeval delay_tv;
110 /** array of outgoing IP4 interfaces */
111 struct port_if* ip4_ifs;
112 /** number of outgoing IP4 interfaces */
115 /** array of outgoing IP6 interfaces */
116 struct port_if* ip6_ifs;
117 /** number of outgoing IP6 interfaces */
120 /** pending udp queries waiting to be sent out, waiting for fd */
121 struct pending* udp_wait_first;
122 /** last pending udp query in list */
123 struct pending* udp_wait_last;
125 /** pending udp answers. sorted by id, addr */
126 rbtree_type* pending;
127 /** serviced queries, sorted by qbuf, addr, dnssec */
128 rbtree_type* serviced;
129 /** host cache, pointer but not owned by outnet. */
130 struct infra_cache* infra;
131 /** where to get random numbers */
132 struct ub_randstate* rnd;
133 /** ssl context to create ssl wrapped TCP with DNS connections */
136 /** dnstap environment */
137 struct dt_env* dtenv;
139 /** maximum segment size of tcp socket */
143 * Array of tcp pending used for outgoing TCP connections.
144 * Each can be used to establish a TCP connection with a server.
145 * The file descriptors are -1 if they are free, and need to be
146 * opened for the tcp connection. Can be used for ip4 and ip6.
148 struct pending_tcp **tcp_conns;
149 /** number of tcp communication points. */
151 /** number of tcp communication points in use. */
152 size_t num_tcp_outgoing;
153 /** list of tcp comm points that are free for use */
154 struct pending_tcp* tcp_free;
155 /** list of tcp queries waiting for a buffer */
156 struct waiting_tcp* tcp_wait_first;
157 /** last of waiting query list */
158 struct waiting_tcp* tcp_wait_last;
162 * Outgoing interface. Ports available and currently used are tracked
166 /** address ready to allocate new socket (except port no). */
167 struct sockaddr_storage addr;
168 /** length of addr field */
171 /** prefix length of network address (in bits), for randomisation.
172 * if 0, no randomisation. */
175 /** the available ports array. These are unused.
176 * Only the first total-inuse part is filled. */
178 /** the total number of available ports (size of the array) */
181 /** array of the commpoints currently in use.
182 * allocated for max number of fds, first part in use. */
183 struct port_comm** out;
184 /** max number of fds, size of out array */
186 /** number of commpoints (and thus also ports) in use */
191 * Outgoing commpoint for UDP port.
194 /** next in free list */
195 struct port_comm* next;
196 /** which port number (when in use) */
198 /** interface it is used in */
200 /** index in the out array of the interface */
202 /** number of outstanding queries on this port */
204 /** UDP commpoint, fd=-1 if not in use */
205 struct comm_point* cp;
209 * A query that has an answer pending for it.
212 /** redblacktree entry, key is the pending struct(id, addr). */
214 /** the ID for the query. int so that a value out of range can
215 * be used to signify a pending that is for certain not present in
216 * the rbtree. (and for which deletion is safe). */
218 /** remote address. */
219 struct sockaddr_storage addr;
220 /** length of addr field in use. */
222 /** comm point it was sent on (and reply must come back on). */
223 struct port_comm* pc;
225 struct comm_timer* timer;
226 /** callback for the timeout, error or reply to the message */
227 comm_point_callback_type* cb;
228 /** callback user argument */
230 /** the outside network it is part of */
231 struct outside_network* outnet;
232 /** the corresponding serviced_query */
233 struct serviced_query* sq;
235 /*---- filled if udp pending is waiting -----*/
236 /** next in waiting list. */
237 struct pending* next_waiting;
238 /** timeout in msec */
240 /** The query itself, the query packet to send. */
242 /** length of query packet. */
247 * Pending TCP query to server.
250 /** next in list of free tcp comm points, or NULL. */
251 struct pending_tcp* next_free;
252 /** the ID for the query; checked in reply */
254 /** tcp comm point it was sent on (and reply must come back on). */
255 struct comm_point* c;
256 /** the query being serviced, NULL if the pending_tcp is unused. */
257 struct waiting_tcp* query;
261 * Query waiting for TCP buffer.
265 * next in waiting list.
266 * if pkt==0, this points to the pending_tcp structure.
268 struct waiting_tcp* next_waiting;
269 /** timeout event; timer keeps running whether the query is
270 * waiting for a buffer or the tcp reply is pending */
271 struct comm_timer* timer;
272 /** the outside network it is part of */
273 struct outside_network* outnet;
274 /** remote address. */
275 struct sockaddr_storage addr;
276 /** length of addr field in use. */
279 * The query itself, the query packet to send.
280 * allocated after the waiting_tcp structure.
281 * set to NULL when the query is serviced and it part of pending_tcp.
282 * if this is NULL, the next_waiting points to the pending_tcp.
285 /** length of query packet. */
287 /** callback for the timeout, error or reply to the message */
288 comm_point_callback_type* cb;
289 /** callback user argument */
291 /** if it uses ssl upstream */
293 /** ref to the tls_auth_name from the serviced_query */
298 * Callback to party interested in serviced query results.
300 struct service_callback {
301 /** next in callback list */
302 struct service_callback* next;
303 /** callback function */
304 comm_point_callback_type* cb;
305 /** user argument for callback function */
309 /** fallback size for fragmentation for EDNS in IPv4 */
310 #define EDNS_FRAG_SIZE_IP4 1472
311 /** fallback size for EDNS in IPv6, fits one fragment with ip6-tunnel-ids */
312 #define EDNS_FRAG_SIZE_IP6 1232
315 * Query service record.
316 * Contains query and destination. UDP, TCP, EDNS are all tried.
317 * complete with retries and timeouts. A number of interested parties can
318 * receive a callback.
320 struct serviced_query {
321 /** The rbtree node, key is this record */
323 /** The query that needs to be answered. Starts with flags u16,
324 * then qdcount, ..., including qname, qtype, qclass. Does not include
327 /** length of qbuf. */
329 /** If an EDNS section is included, the DO/CD bit will be turned on. */
331 /** We want signatures, or else the answer is likely useless */
333 /** ignore capsforid */
335 /** tcp upstream used, use tcp, or ssl_upstream for SSL */
336 int tcp_upstream, ssl_upstream;
337 /** the name of the tls authentication name, eg. 'ns.example.com'
340 /** where to send it */
341 struct sockaddr_storage addr;
342 /** length of addr field in use. */
344 /** zone name, uncompressed domain name in wireformat */
346 /** length of zone name */
350 /** current status */
351 enum serviced_query_status {
352 /** initial status */
354 /** UDP with EDNS sent */
355 serviced_query_UDP_EDNS,
356 /** UDP without EDNS sent */
358 /** TCP with EDNS sent */
359 serviced_query_TCP_EDNS,
360 /** TCP without EDNS sent */
362 /** probe to test EDNS lameness (EDNS is dropped) */
363 serviced_query_PROBE_EDNS,
364 /** probe to test noEDNS0 (EDNS gives FORMERRorNOTIMP) */
365 serviced_query_UDP_EDNS_fallback,
366 /** probe to test TCP noEDNS0 (EDNS gives FORMERRorNOTIMP) */
367 serviced_query_TCP_EDNS_fallback,
368 /** send UDP query with EDNS1480 (or 1280) */
369 serviced_query_UDP_EDNS_FRAG
371 /** variable with current status */
373 /** true if serviced_query is scheduled for deletion already */
375 /** number of UDP retries */
377 /** time last UDP was sent */
378 struct timeval last_sent_time;
379 /** rtt of last message */
381 /** do we know edns probe status already, for UDP_EDNS queries */
383 /** edns options to use for sending upstream packet */
384 struct edns_option* opt_list;
385 /** outside network this is part of */
386 struct outside_network* outnet;
387 /** list of interested parties that need callback on results. */
388 struct service_callback* cblist;
389 /** the UDP or TCP query that is pending, see status which */
394 * Create outside_network structure with N udp ports.
395 * @param base: the communication base to use for event handling.
396 * @param bufsize: size for network buffers.
397 * @param num_ports: number of udp ports to open per interface.
398 * @param ifs: interface names (or NULL for default interface).
399 * These interfaces must be able to access all authoritative servers.
400 * @param num_ifs: number of names in array ifs.
401 * @param do_ip4: service IP4.
402 * @param do_ip6: service IP6.
403 * @param num_tcp: number of outgoing tcp buffers to preallocate.
404 * @param infra: pointer to infra cached used for serviced queries.
405 * @param rnd: stored to create random numbers for serviced queries.
406 * @param use_caps_for_id: enable to use 0x20 bits to encode id randomness.
407 * @param availports: array of available ports.
408 * @param numavailports: number of available ports in array.
409 * @param unwanted_threshold: when to take defensive action.
410 * @param unwanted_action: the action to take.
411 * @param unwanted_param: user parameter to action.
412 * @param tcp_mss: maximum segment size of tcp socket.
413 * @param do_udp: if udp is done.
414 * @param sslctx: context to create outgoing connections with (if enabled).
415 * @param delayclose: if not 0, udp sockets are delayed before timeout closure.
416 * msec to wait on timeouted udp sockets.
417 * @param dtenv: environment to send dnstap events with (if enabled).
418 * @return: the new structure (with no pending answers) or NULL on error.
420 struct outside_network* outside_network_create(struct comm_base* base,
421 size_t bufsize, size_t num_ports, char** ifs, int num_ifs,
422 int do_ip4, int do_ip6, size_t num_tcp, struct infra_cache* infra,
423 struct ub_randstate* rnd, int use_caps_for_id, int* availports,
424 int numavailports, size_t unwanted_threshold, int tcp_mss,
425 void (*unwanted_action)(void*), void* unwanted_param, int do_udp,
426 void* sslctx, int delayclose, struct dt_env *dtenv);
429 * Delete outside_network structure.
430 * @param outnet: object to delete.
432 void outside_network_delete(struct outside_network* outnet);
435 * Prepare for quit. Sends no more queries, even if queued up.
436 * @param outnet: object to prepare for removal
438 void outside_network_quit_prepare(struct outside_network* outnet);
441 * Send UDP query, create pending answer.
442 * Changes the ID for the query to be random and unique for that destination.
443 * @param sq: serviced query.
444 * @param packet: wireformat query to send to destination.
445 * @param timeout: in milliseconds from now.
446 * @param callback: function to call on error, timeout or reply.
447 * @param callback_arg: user argument for callback function.
448 * @return: NULL on error for malloc or socket. Else the pending query object.
450 struct pending* pending_udp_query(struct serviced_query* sq,
451 struct sldns_buffer* packet, int timeout, comm_point_callback_type* callback,
455 * Send TCP query. May wait for TCP buffer. Selects ID to be random, and
457 * @param sq: serviced query.
458 * @param packet: wireformat query to send to destination. copied from.
459 * @param timeout: in milliseconds from now.
460 * Timer starts running now. Timer may expire if all buffers are used,
461 * without any query been sent to the server yet.
462 * @param callback: function to call on error, timeout or reply.
463 * @param callback_arg: user argument for callback function.
464 * @return: false on error for malloc or socket. Else the pending TCP object.
466 struct waiting_tcp* pending_tcp_query(struct serviced_query* sq,
467 struct sldns_buffer* packet, int timeout, comm_point_callback_type* callback,
471 * Delete pending answer.
472 * @param outnet: outside network the pending query is part of.
473 * Internal feature: if outnet is NULL, p is not unlinked from rbtree.
476 void pending_delete(struct outside_network* outnet, struct pending* p);
479 * Perform a serviced query to the authoritative servers.
480 * Duplicate efforts are detected, and EDNS, TCP and UDP retry is performed.
481 * @param outnet: outside network, with rbtree of serviced queries.
482 * @param qinfo: query info.
483 * @param flags: flags u16 (host format), includes opcode, CD bit.
484 * @param dnssec: if set, DO bit is set in EDNS queries.
485 * If the value includes BIT_CD, CD bit is set when in EDNS queries.
486 * If the value includes BIT_DO, DO bit is set when in EDNS queries.
487 * @param want_dnssec: signatures are needed, without EDNS the answer is
488 * likely to be useless.
489 * @param nocaps: ignore use_caps_for_id and use unperturbed qname.
490 * @param tcp_upstream: use TCP for upstream queries.
491 * @param ssl_upstream: use SSL for upstream queries.
492 * @param tls_auth_name: when ssl_upstream is true, use this name to check
493 * the server's peer certificate.
494 * @param addr: to which server to send the query.
495 * @param addrlen: length of addr.
496 * @param zone: name of the zone of the delegation point. wireformat dname.
497 This is the delegation point name for which the server is deemed
499 * @param zonelen: length of zone.
500 * @param qstate: module qstate. Mainly for inspecting the available
502 * @param callback: callback function.
503 * @param callback_arg: user argument to callback function.
504 * @param buff: scratch buffer to create query contents in. Empty on exit.
505 * @param env: the module environment.
506 * @return 0 on error, or pointer to serviced query that is used to answer
507 * this serviced query may be shared with other callbacks as well.
509 struct serviced_query* outnet_serviced_query(struct outside_network* outnet,
510 struct query_info* qinfo, uint16_t flags, int dnssec, int want_dnssec,
511 int nocaps, int tcp_upstream, int ssl_upstream, char* tls_auth_name,
512 struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
513 size_t zonelen, struct module_qstate* qstate,
514 comm_point_callback_type* callback, void* callback_arg,
515 struct sldns_buffer* buff, struct module_env* env);
518 * Remove service query callback.
519 * If that leads to zero callbacks, the query is completely cancelled.
520 * @param sq: serviced query to adjust.
521 * @param cb_arg: callback argument of callback that needs removal.
522 * same as the callback_arg to outnet_serviced_query().
524 void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg);
527 * Get memory size in use by outside network.
528 * Counts buffers and outstanding query (serviced queries) malloced data.
529 * @param outnet: outside network structure.
530 * @return size in bytes.
532 size_t outnet_get_mem(struct outside_network* outnet);
535 * Get memory size in use by serviced query while it is servicing callbacks.
536 * This takes into account the pre-deleted status of it; it will be deleted
537 * when the callbacks are done.
538 * @param sq: serviced query.
539 * @return size in bytes.
541 size_t serviced_get_mem(struct serviced_query* sq);
543 /** get TCP file descriptor for address, returns -1 on failure,
544 * tcp_mss is 0 or maxseg size to set for TCP packets. */
545 int outnet_get_tcp_fd(struct sockaddr_storage* addr, socklen_t addrlen, int tcp_mss);
548 * Create udp commpoint suitable for sending packets to the destination.
549 * @param outnet: outside_network with the comm_base it is attached to,
550 * with the outgoing interfaces chosen from, and rnd gen for random.
551 * @param cb: callback function for the commpoint.
552 * @param cb_arg: callback argument for cb.
553 * @param to_addr: intended destination.
554 * @param to_addrlen: length of to_addr.
555 * @return commpoint that you can comm_point_send_udp_msg with, or NULL.
557 struct comm_point* outnet_comm_point_for_udp(struct outside_network* outnet,
558 comm_point_callback_type* cb, void* cb_arg,
559 struct sockaddr_storage* to_addr, socklen_t to_addrlen);
562 * Create tcp commpoint suitable for communication to the destination.
563 * It also performs connect() to the to_addr.
564 * @param outnet: outside_network with the comm_base it is attached to,
566 * @param cb: callback function for the commpoint.
567 * @param cb_arg: callback argument for cb.
568 * @param to_addr: intended destination.
569 * @param to_addrlen: length of to_addr.
570 * @param query: initial packet to send writing, in buffer. It is copied
571 * to the commpoint buffer that is created.
572 * @param timeout: timeout for the TCP connection.
573 * timeout in milliseconds, or -1 for no (change to the) timeout.
575 * @return tcp_out commpoint, or NULL.
577 struct comm_point* outnet_comm_point_for_tcp(struct outside_network* outnet,
578 comm_point_callback_type* cb, void* cb_arg,
579 struct sockaddr_storage* to_addr, socklen_t to_addrlen,
580 struct sldns_buffer* query, int timeout);
583 * Create http commpoint suitable for communication to the destination.
584 * Creates the http request buffer. It also performs connect() to the to_addr.
585 * @param outnet: outside_network with the comm_base it is attached to,
587 * @param cb: callback function for the commpoint.
588 * @param cb_arg: callback argument for cb.
589 * @param to_addr: intended destination.
590 * @param to_addrlen: length of to_addr.
591 * @param timeout: timeout for the TCP connection.
592 * timeout in milliseconds, or -1 for no (change to the) timeout.
594 * @param ssl: set to true for https.
595 * @param host: hostname to use for the destination. part of http request.
596 * @param path: pathname to lookup, eg. name of the file on the destination.
597 * @return http_out commpoint, or NULL.
599 struct comm_point* outnet_comm_point_for_http(struct outside_network* outnet,
600 comm_point_callback_type* cb, void* cb_arg,
601 struct sockaddr_storage* to_addr, socklen_t to_addrlen, int timeout,
602 int ssl, char* host, char* path);
604 /** connect tcp connection to addr, 0 on failure */
605 int outnet_tcp_connect(int s, struct sockaddr_storage* addr, socklen_t addrlen);
607 /** callback for incoming udp answers from the network */
608 int outnet_udp_cb(struct comm_point* c, void* arg, int error,
609 struct comm_reply *reply_info);
611 /** callback for pending tcp connections */
612 int outnet_tcp_cb(struct comm_point* c, void* arg, int error,
613 struct comm_reply *reply_info);
615 /** callback for udp timeout */
616 void pending_udp_timer_cb(void *arg);
618 /** callback for udp delay for timeout */
619 void pending_udp_timer_delay_cb(void *arg);
621 /** callback for outgoing TCP timer event */
622 void outnet_tcptimer(void* arg);
624 /** callback for serviced query UDP answers */
625 int serviced_udp_callback(struct comm_point* c, void* arg, int error,
626 struct comm_reply* rep);
628 /** TCP reply or error callback for serviced queries */
629 int serviced_tcp_callback(struct comm_point* c, void* arg, int error,
630 struct comm_reply* rep);
632 /** compare function of pending rbtree */
633 int pending_cmp(const void* key1, const void* key2);
635 /** compare function of serviced query rbtree */
636 int serviced_cmp(const void* key1, const void* key2);
638 #endif /* OUTSIDE_NETWORK_H */