outside_network.h revision 302408
1/*
2 * services/outside_network.h - listen to answers from the network
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 has functions to send queries to authoritative servers,
40 * and wait for the pending answer, with timeouts.
41 */
42
43#ifndef OUTSIDE_NETWORK_H
44#define OUTSIDE_NETWORK_H
45
46#include "util/rbtree.h"
47#include "util/netevent.h"
48#include "dnstap/dnstap_config.h"
49struct pending;
50struct pending_timeout;
51struct ub_randstate;
52struct pending_tcp;
53struct waiting_tcp;
54struct waiting_udp;
55struct infra_cache;
56struct port_comm;
57struct port_if;
58struct sldns_buffer;
59struct serviced_query;
60struct dt_env;
61
62/**
63 * Send queries to outside servers and wait for answers from servers.
64 * Contains answer-listen sockets.
65 */
66struct outside_network {
67	/** Base for select calls */
68	struct comm_base* base;
69	/** pointer to time in seconds */
70	time_t* now_secs;
71	/** pointer to time in microseconds */
72	struct timeval* now_tv;
73
74	/** buffer shared by UDP connections, since there is only one
75	    datagram at any time. */
76	struct sldns_buffer* udp_buff;
77	/** serviced_callbacks malloc overhead when processing multiple
78	 * identical serviced queries to the same server. */
79	size_t svcd_overhead;
80	/** use x20 bits to encode additional ID random bits */
81	int use_caps_for_id;
82	/** outside network wants to quit. Stop queued msgs from sent. */
83	int want_to_quit;
84
85	/** number of unwanted replies received (for statistics) */
86	size_t unwanted_replies;
87	/** cumulative total of unwanted replies (for defense) */
88	size_t unwanted_total;
89	/** threshold when to take defensive action. If 0 then never. */
90	size_t unwanted_threshold;
91	/** what action to take, called when defensive action is needed */
92	void (*unwanted_action)(void*);
93	/** user param for action */
94	void* unwanted_param;
95
96	/** linked list of available commpoints, unused file descriptors,
97	 * for use as outgoing UDP ports. cp.fd=-1 in them. */
98	struct port_comm* unused_fds;
99	/** if udp is done */
100	int do_udp;
101	/** if udp is delay-closed (delayed answers do not meet closed port)*/
102	int delayclose;
103	/** timeout for delayclose */
104	struct timeval delay_tv;
105
106	/** array of outgoing IP4 interfaces */
107	struct port_if* ip4_ifs;
108	/** number of outgoing IP4 interfaces */
109	int num_ip4;
110
111	/** array of outgoing IP6 interfaces */
112	struct port_if* ip6_ifs;
113	/** number of outgoing IP6 interfaces */
114	int num_ip6;
115
116	/** pending udp queries waiting to be sent out, waiting for fd */
117	struct pending* udp_wait_first;
118	/** last pending udp query in list */
119	struct pending* udp_wait_last;
120
121	/** pending udp answers. sorted by id, addr */
122	rbtree_t* pending;
123	/** serviced queries, sorted by qbuf, addr, dnssec */
124	rbtree_t* serviced;
125	/** host cache, pointer but not owned by outnet. */
126	struct infra_cache* infra;
127	/** where to get random numbers */
128	struct ub_randstate* rnd;
129	/** ssl context to create ssl wrapped TCP with DNS connections */
130	void* sslctx;
131#ifdef USE_DNSTAP
132	/** dnstap environment */
133	struct dt_env* dtenv;
134#endif
135	/** maximum segment size of tcp socket */
136	int tcp_mss;
137
138	/**
139	 * Array of tcp pending used for outgoing TCP connections.
140	 * Each can be used to establish a TCP connection with a server.
141	 * The file descriptors are -1 if they are free, and need to be
142	 * opened for the tcp connection. Can be used for ip4 and ip6.
143	 */
144	struct pending_tcp **tcp_conns;
145	/** number of tcp communication points. */
146	size_t num_tcp;
147	/** number of tcp communication points in use. */
148	size_t num_tcp_outgoing;
149	/** list of tcp comm points that are free for use */
150	struct pending_tcp* tcp_free;
151	/** list of tcp queries waiting for a buffer */
152	struct waiting_tcp* tcp_wait_first;
153	/** last of waiting query list */
154	struct waiting_tcp* tcp_wait_last;
155};
156
157/**
158 * Outgoing interface. Ports available and currently used are tracked
159 * per interface
160 */
161struct port_if {
162	/** address ready to allocate new socket (except port no). */
163	struct sockaddr_storage addr;
164	/** length of addr field */
165	socklen_t addrlen;
166
167	/** the available ports array. These are unused.
168	 * Only the first total-inuse part is filled. */
169	int* avail_ports;
170	/** the total number of available ports (size of the array) */
171	int avail_total;
172
173	/** array of the commpoints currently in use.
174	 * allocated for max number of fds, first part in use. */
175	struct port_comm** out;
176	/** max number of fds, size of out array */
177	int maxout;
178	/** number of commpoints (and thus also ports) in use */
179	int inuse;
180};
181
182/**
183 * Outgoing commpoint for UDP port.
184 */
185struct port_comm {
186	/** next in free list */
187	struct port_comm* next;
188	/** which port number (when in use) */
189	int number;
190	/** interface it is used in */
191	struct port_if* pif;
192	/** index in the out array of the interface */
193	int index;
194	/** number of outstanding queries on this port */
195	int num_outstanding;
196	/** UDP commpoint, fd=-1 if not in use */
197	struct comm_point* cp;
198};
199
200/**
201 * A query that has an answer pending for it.
202 */
203struct pending {
204	/** redblacktree entry, key is the pending struct(id, addr). */
205	rbnode_t node;
206	/** the ID for the query. int so that a value out of range can
207	 * be used to signify a pending that is for certain not present in
208	 * the rbtree. (and for which deletion is safe). */
209	unsigned int id;
210	/** remote address. */
211	struct sockaddr_storage addr;
212	/** length of addr field in use. */
213	socklen_t addrlen;
214	/** comm point it was sent on (and reply must come back on). */
215	struct port_comm* pc;
216	/** timeout event */
217	struct comm_timer* timer;
218	/** callback for the timeout, error or reply to the message */
219	comm_point_callback_t* cb;
220	/** callback user argument */
221	void* cb_arg;
222	/** the outside network it is part of */
223	struct outside_network* outnet;
224	/** the corresponding serviced_query */
225	struct serviced_query* sq;
226
227	/*---- filled if udp pending is waiting -----*/
228	/** next in waiting list. */
229	struct pending* next_waiting;
230	/** timeout in msec */
231	int timeout;
232	/** The query itself, the query packet to send. */
233	uint8_t* pkt;
234	/** length of query packet. */
235	size_t pkt_len;
236};
237
238/**
239 * Pending TCP query to server.
240 */
241struct pending_tcp {
242	/** next in list of free tcp comm points, or NULL. */
243	struct pending_tcp* next_free;
244	/** the ID for the query; checked in reply */
245	uint16_t id;
246	/** tcp comm point it was sent on (and reply must come back on). */
247	struct comm_point* c;
248	/** the query being serviced, NULL if the pending_tcp is unused. */
249	struct waiting_tcp* query;
250};
251
252/**
253 * Query waiting for TCP buffer.
254 */
255struct waiting_tcp {
256	/**
257	 * next in waiting list.
258	 * if pkt==0, this points to the pending_tcp structure.
259	 */
260	struct waiting_tcp* next_waiting;
261	/** timeout event; timer keeps running whether the query is
262	 * waiting for a buffer or the tcp reply is pending */
263	struct comm_timer* timer;
264	/** the outside network it is part of */
265	struct outside_network* outnet;
266	/** remote address. */
267	struct sockaddr_storage addr;
268	/** length of addr field in use. */
269	socklen_t addrlen;
270	/**
271	 * The query itself, the query packet to send.
272	 * allocated after the waiting_tcp structure.
273	 * set to NULL when the query is serviced and it part of pending_tcp.
274	 * if this is NULL, the next_waiting points to the pending_tcp.
275	 */
276	uint8_t* pkt;
277	/** length of query packet. */
278	size_t pkt_len;
279	/** callback for the timeout, error or reply to the message */
280	comm_point_callback_t* cb;
281	/** callback user argument */
282	void* cb_arg;
283	/** if it uses ssl upstream */
284	int ssl_upstream;
285};
286
287/**
288 * Callback to party interested in serviced query results.
289 */
290struct service_callback {
291	/** next in callback list */
292	struct service_callback* next;
293	/** callback function */
294	comm_point_callback_t* cb;
295	/** user argument for callback function */
296	void* cb_arg;
297};
298
299/** fallback size for fragmentation for EDNS in IPv4 */
300#define EDNS_FRAG_SIZE_IP4 1472
301/** fallback size for EDNS in IPv6, fits one fragment with ip6-tunnel-ids */
302#define EDNS_FRAG_SIZE_IP6 1232
303
304/**
305 * Query service record.
306 * Contains query and destination. UDP, TCP, EDNS are all tried.
307 * complete with retries and timeouts. A number of interested parties can
308 * receive a callback.
309 */
310struct serviced_query {
311	/** The rbtree node, key is this record */
312	rbnode_t node;
313	/** The query that needs to be answered. Starts with flags u16,
314	 * then qdcount, ..., including qname, qtype, qclass. Does not include
315	 * EDNS record. */
316	uint8_t* qbuf;
317	/** length of qbuf. */
318	size_t qbuflen;
319	/** If an EDNS section is included, the DO/CD bit will be turned on. */
320	int dnssec;
321	/** We want signatures, or else the answer is likely useless */
322	int want_dnssec;
323	/** ignore capsforid */
324	int nocaps;
325	/** tcp upstream used, use tcp, or ssl_upstream for SSL */
326	int tcp_upstream, ssl_upstream;
327	/** where to send it */
328	struct sockaddr_storage addr;
329	/** length of addr field in use. */
330	socklen_t addrlen;
331	/** zone name, uncompressed domain name in wireformat */
332	uint8_t* zone;
333	/** length of zone name */
334	size_t zonelen;
335	/** qtype */
336	int qtype;
337	/** current status */
338	enum serviced_query_status {
339		/** initial status */
340		serviced_initial,
341		/** UDP with EDNS sent */
342		serviced_query_UDP_EDNS,
343		/** UDP without EDNS sent */
344		serviced_query_UDP,
345		/** TCP with EDNS sent */
346		serviced_query_TCP_EDNS,
347		/** TCP without EDNS sent */
348		serviced_query_TCP,
349		/** probe to test EDNS lameness (EDNS is dropped) */
350		serviced_query_PROBE_EDNS,
351		/** probe to test noEDNS0 (EDNS gives FORMERRorNOTIMP) */
352		serviced_query_UDP_EDNS_fallback,
353		/** probe to test TCP noEDNS0 (EDNS gives FORMERRorNOTIMP) */
354		serviced_query_TCP_EDNS_fallback,
355		/** send UDP query with EDNS1480 (or 1280) */
356		serviced_query_UDP_EDNS_FRAG
357	}
358		/** variable with current status */
359		status;
360	/** true if serviced_query is scheduled for deletion already */
361	int to_be_deleted;
362	/** number of UDP retries */
363	int retry;
364	/** time last UDP was sent */
365	struct timeval last_sent_time;
366	/** rtt of last (UDP) message */
367	int last_rtt;
368	/** do we know edns probe status already, for UDP_EDNS queries */
369	int edns_lame_known;
370	/** outside network this is part of */
371	struct outside_network* outnet;
372	/** list of interested parties that need callback on results. */
373	struct service_callback* cblist;
374	/** the UDP or TCP query that is pending, see status which */
375	void* pending;
376};
377
378/**
379 * Create outside_network structure with N udp ports.
380 * @param base: the communication base to use for event handling.
381 * @param bufsize: size for network buffers.
382 * @param num_ports: number of udp ports to open per interface.
383 * @param ifs: interface names (or NULL for default interface).
384 *    These interfaces must be able to access all authoritative servers.
385 * @param num_ifs: number of names in array ifs.
386 * @param do_ip4: service IP4.
387 * @param do_ip6: service IP6.
388 * @param num_tcp: number of outgoing tcp buffers to preallocate.
389 * @param infra: pointer to infra cached used for serviced queries.
390 * @param rnd: stored to create random numbers for serviced queries.
391 * @param use_caps_for_id: enable to use 0x20 bits to encode id randomness.
392 * @param availports: array of available ports.
393 * @param numavailports: number of available ports in array.
394 * @param unwanted_threshold: when to take defensive action.
395 * @param unwanted_action: the action to take.
396 * @param unwanted_param: user parameter to action.
397 * @param tcp_mss: maximum segment size of tcp socket.
398 * @param do_udp: if udp is done.
399 * @param sslctx: context to create outgoing connections with (if enabled).
400 * @param delayclose: if not 0, udp sockets are delayed before timeout closure.
401 * 	msec to wait on timeouted udp sockets.
402 * @param dtenv: environment to send dnstap events with (if enabled).
403 * @return: the new structure (with no pending answers) or NULL on error.
404 */
405struct outside_network* outside_network_create(struct comm_base* base,
406	size_t bufsize, size_t num_ports, char** ifs, int num_ifs,
407	int do_ip4, int do_ip6, size_t num_tcp, struct infra_cache* infra,
408	struct ub_randstate* rnd, int use_caps_for_id, int* availports,
409	int numavailports, size_t unwanted_threshold, int tcp_mss,
410	void (*unwanted_action)(void*), void* unwanted_param, int do_udp,
411	void* sslctx, int delayclose, struct dt_env *dtenv);
412
413/**
414 * Delete outside_network structure.
415 * @param outnet: object to delete.
416 */
417void outside_network_delete(struct outside_network* outnet);
418
419/**
420 * Prepare for quit. Sends no more queries, even if queued up.
421 * @param outnet: object to prepare for removal
422 */
423void outside_network_quit_prepare(struct outside_network* outnet);
424
425/**
426 * Send UDP query, create pending answer.
427 * Changes the ID for the query to be random and unique for that destination.
428 * @param sq: serviced query.
429 * @param packet: wireformat query to send to destination.
430 * @param timeout: in milliseconds from now.
431 * @param callback: function to call on error, timeout or reply.
432 * @param callback_arg: user argument for callback function.
433 * @return: NULL on error for malloc or socket. Else the pending query object.
434 */
435struct pending* pending_udp_query(struct serviced_query* sq,
436	struct sldns_buffer* packet, int timeout, comm_point_callback_t* callback,
437	void* callback_arg);
438
439/**
440 * Send TCP query. May wait for TCP buffer. Selects ID to be random, and
441 * checks id.
442 * @param sq: serviced query.
443 * @param packet: wireformat query to send to destination. copied from.
444 * @param timeout: in seconds from now.
445 *    Timer starts running now. Timer may expire if all buffers are used,
446 *    without any query been sent to the server yet.
447 * @param callback: function to call on error, timeout or reply.
448 * @param callback_arg: user argument for callback function.
449 * @return: false on error for malloc or socket. Else the pending TCP object.
450 */
451struct waiting_tcp* pending_tcp_query(struct serviced_query* sq,
452	struct sldns_buffer* packet, int timeout, comm_point_callback_t* callback,
453	void* callback_arg);
454
455/**
456 * Delete pending answer.
457 * @param outnet: outside network the pending query is part of.
458 *    Internal feature: if outnet is NULL, p is not unlinked from rbtree.
459 * @param p: deleted
460 */
461void pending_delete(struct outside_network* outnet, struct pending* p);
462
463/**
464 * Perform a serviced query to the authoritative servers.
465 * Duplicate efforts are detected, and EDNS, TCP and UDP retry is performed.
466 * @param outnet: outside network, with rbtree of serviced queries.
467 * @param qname: what qname to query.
468 * @param qnamelen: length of qname in octets including 0 root label.
469 * @param qtype: rrset type to query (host format)
470 * @param qclass: query class. (host format)
471 * @param flags: flags u16 (host format), includes opcode, CD bit.
472 * @param dnssec: if set, DO bit is set in EDNS queries.
473 *	If the value includes BIT_CD, CD bit is set when in EDNS queries.
474 *	If the value includes BIT_DO, DO bit is set when in EDNS queries.
475 * @param want_dnssec: signatures are needed, without EDNS the answer is
476 * 	likely to be useless.
477 * @param nocaps: ignore use_caps_for_id and use unperturbed qname.
478 * @param tcp_upstream: use TCP for upstream queries.
479 * @param ssl_upstream: use SSL for upstream queries.
480 * @param callback: callback function.
481 * @param callback_arg: user argument to callback function.
482 * @param addr: to which server to send the query.
483 * @param addrlen: length of addr.
484 * @param zone: name of the zone of the delegation point. wireformat dname.
485	This is the delegation point name for which the server is deemed
486	authoritative.
487 * @param zonelen: length of zone.
488 * @param buff: scratch buffer to create query contents in. Empty on exit.
489 * @return 0 on error, or pointer to serviced query that is used to answer
490 *	this serviced query may be shared with other callbacks as well.
491 */
492struct serviced_query* outnet_serviced_query(struct outside_network* outnet,
493	uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
494	uint16_t flags, int dnssec, int want_dnssec, int nocaps,
495	int tcp_upstream, int ssl_upstream, struct sockaddr_storage* addr,
496	socklen_t addrlen, uint8_t* zone, size_t zonelen,
497	comm_point_callback_t* callback, void* callback_arg,
498	struct sldns_buffer* buff);
499
500/**
501 * Remove service query callback.
502 * If that leads to zero callbacks, the query is completely cancelled.
503 * @param sq: serviced query to adjust.
504 * @param cb_arg: callback argument of callback that needs removal.
505 *	same as the callback_arg to outnet_serviced_query().
506 */
507void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg);
508
509/**
510 * Get memory size in use by outside network.
511 * Counts buffers and outstanding query (serviced queries) malloced data.
512 * @param outnet: outside network structure.
513 * @return size in bytes.
514 */
515size_t outnet_get_mem(struct outside_network* outnet);
516
517/**
518 * Get memory size in use by serviced query while it is servicing callbacks.
519 * This takes into account the pre-deleted status of it; it will be deleted
520 * when the callbacks are done.
521 * @param sq: serviced query.
522 * @return size in bytes.
523 */
524size_t serviced_get_mem(struct serviced_query* sq);
525
526/** callback for incoming udp answers from the network */
527int outnet_udp_cb(struct comm_point* c, void* arg, int error,
528	struct comm_reply *reply_info);
529
530/** callback for pending tcp connections */
531int outnet_tcp_cb(struct comm_point* c, void* arg, int error,
532	struct comm_reply *reply_info);
533
534/** callback for udp timeout */
535void pending_udp_timer_cb(void *arg);
536
537/** callback for udp delay for timeout */
538void pending_udp_timer_delay_cb(void *arg);
539
540/** callback for outgoing TCP timer event */
541void outnet_tcptimer(void* arg);
542
543/** callback for serviced query UDP answers */
544int serviced_udp_callback(struct comm_point* c, void* arg, int error,
545        struct comm_reply* rep);
546
547/** TCP reply or error callback for serviced queries */
548int serviced_tcp_callback(struct comm_point* c, void* arg, int error,
549        struct comm_reply* rep);
550
551/** compare function of pending rbtree */
552int pending_cmp(const void* key1, const void* key2);
553
554/** compare function of serviced query rbtree */
555int serviced_cmp(const void* key1, const void* key2);
556
557#endif /* OUTSIDE_NETWORK_H */
558