xref: /freebsd/contrib/unbound/services/outside_network.h (revision c203bd70b5957f85616424b6fa374479372d06e3)
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"
49 struct pending;
50 struct pending_timeout;
51 struct ub_randstate;
52 struct pending_tcp;
53 struct waiting_tcp;
54 struct waiting_udp;
55 struct reuse_tcp;
56 struct infra_cache;
57 struct port_comm;
58 struct port_if;
59 struct sldns_buffer;
60 struct serviced_query;
61 struct dt_env;
62 struct edns_option;
63 struct module_env;
64 struct module_qstate;
65 struct query_info;
66 
67 /**
68  * Send queries to outside servers and wait for answers from servers.
69  * Contains answer-listen sockets.
70  */
71 struct outside_network {
72 	/** Base for select calls */
73 	struct comm_base* base;
74 	/** pointer to time in seconds */
75 	time_t* now_secs;
76 	/** pointer to time in microseconds */
77 	struct timeval* now_tv;
78 
79 	/** buffer shared by UDP connections, since there is only one
80 	    datagram at any time. */
81 	struct sldns_buffer* udp_buff;
82 	/** serviced_callbacks malloc overhead when processing multiple
83 	 * identical serviced queries to the same server. */
84 	size_t svcd_overhead;
85 	/** use x20 bits to encode additional ID random bits */
86 	int use_caps_for_id;
87 	/** outside network wants to quit. Stop queued msgs from sent. */
88 	int want_to_quit;
89 
90 	/** number of unwanted replies received (for statistics) */
91 	size_t unwanted_replies;
92 	/** cumulative total of unwanted replies (for defense) */
93 	size_t unwanted_total;
94 	/** threshold when to take defensive action. If 0 then never. */
95 	size_t unwanted_threshold;
96 	/** what action to take, called when defensive action is needed */
97 	void (*unwanted_action)(void*);
98 	/** user param for action */
99 	void* unwanted_param;
100 
101 	/** linked list of available commpoints, unused file descriptors,
102 	 * for use as outgoing UDP ports. cp.fd=-1 in them. */
103 	struct port_comm* unused_fds;
104 	/** if udp is done */
105 	int do_udp;
106 	/** if udp is delay-closed (delayed answers do not meet closed port)*/
107 	int delayclose;
108 	/** timeout for delayclose */
109 	struct timeval delay_tv;
110 	/** if we perform udp-connect, connect() for UDP socket to mitigate
111 	 * ICMP side channel leakage */
112 	int udp_connect;
113 
114 	/** array of outgoing IP4 interfaces */
115 	struct port_if* ip4_ifs;
116 	/** number of outgoing IP4 interfaces */
117 	int num_ip4;
118 
119 	/** array of outgoing IP6 interfaces */
120 	struct port_if* ip6_ifs;
121 	/** number of outgoing IP6 interfaces */
122 	int num_ip6;
123 
124 	/** pending udp queries waiting to be sent out, waiting for fd */
125 	struct pending* udp_wait_first;
126 	/** last pending udp query in list */
127 	struct pending* udp_wait_last;
128 
129 	/** pending udp answers. sorted by id, addr */
130 	rbtree_type* pending;
131 	/** serviced queries, sorted by qbuf, addr, dnssec */
132 	rbtree_type* serviced;
133 	/** host cache, pointer but not owned by outnet. */
134 	struct infra_cache* infra;
135 	/** where to get random numbers */
136 	struct ub_randstate* rnd;
137 	/** ssl context to create ssl wrapped TCP with DNS connections */
138 	void* sslctx;
139 	/** if SNI will be used for TLS connections */
140 	int tls_use_sni;
141 #ifdef USE_DNSTAP
142 	/** dnstap environment */
143 	struct dt_env* dtenv;
144 #endif
145 	/** maximum segment size of tcp socket */
146 	int tcp_mss;
147 	/** IP_TOS socket option requested on the sockets */
148 	int ip_dscp;
149 
150 	/**
151 	 * Array of tcp pending used for outgoing TCP connections.
152 	 * Each can be used to establish a TCP connection with a server.
153 	 * The file descriptors are -1 if they are free, and need to be
154 	 * opened for the tcp connection. Can be used for ip4 and ip6.
155 	 */
156 	struct pending_tcp **tcp_conns;
157 	/** number of tcp communication points. */
158 	size_t num_tcp;
159 	/** number of tcp communication points in use. */
160 	size_t num_tcp_outgoing;
161 	/**
162 	 * tree of still-open and waiting tcp connections for reuse.
163 	 * can be closed and reopened to get a new tcp connection.
164 	 * or reused to the same destination again.  with timeout to close.
165 	 * Entries are of type struct reuse_tcp.
166 	 * The entries are both active and empty connections.
167 	 */
168 	rbtree_type tcp_reuse;
169 	/** max number of tcp_reuse entries we want to keep open */
170 	size_t tcp_reuse_max;
171 	/** first and last(oldest) in lru list of reuse connections.
172 	 * the oldest can be closed to get a new free pending_tcp if needed
173 	 * The list contains empty connections, that wait for timeout or
174 	 * a new query that can use the existing connection. */
175 	struct reuse_tcp* tcp_reuse_first, *tcp_reuse_last;
176 	/** list of tcp comm points that are free for use */
177 	struct pending_tcp* tcp_free;
178 	/** list of tcp queries waiting for a buffer */
179 	struct waiting_tcp* tcp_wait_first;
180 	/** last of waiting query list */
181 	struct waiting_tcp* tcp_wait_last;
182 };
183 
184 /**
185  * Outgoing interface. Ports available and currently used are tracked
186  * per interface
187  */
188 struct port_if {
189 	/** address ready to allocate new socket (except port no). */
190 	struct sockaddr_storage addr;
191 	/** length of addr field */
192 	socklen_t addrlen;
193 
194 	/** prefix length of network address (in bits), for randomisation.
195 	 * if 0, no randomisation. */
196 	int pfxlen;
197 
198 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
199 	/** the available ports array. These are unused.
200 	 * Only the first total-inuse part is filled. */
201 	int* avail_ports;
202 	/** the total number of available ports (size of the array) */
203 	int avail_total;
204 #endif
205 
206 	/** array of the commpoints currently in use.
207 	 * allocated for max number of fds, first part in use. */
208 	struct port_comm** out;
209 	/** max number of fds, size of out array */
210 	int maxout;
211 	/** number of commpoints (and thus also ports) in use */
212 	int inuse;
213 };
214 
215 /**
216  * Outgoing commpoint for UDP port.
217  */
218 struct port_comm {
219 	/** next in free list */
220 	struct port_comm* next;
221 	/** which port number (when in use) */
222 	int number;
223 	/** interface it is used in */
224 	struct port_if* pif;
225 	/** index in the out array of the interface */
226 	int index;
227 	/** number of outstanding queries on this port */
228 	int num_outstanding;
229 	/** UDP commpoint, fd=-1 if not in use */
230 	struct comm_point* cp;
231 };
232 
233 /**
234  * Reuse TCP connection, still open can be used again.
235  */
236 struct reuse_tcp {
237 	/** rbtree node with links in tcp_reuse tree. key is NULL when not
238 	 * in tree. Both active and empty connections are in the tree.
239 	 * key is a pointer to this structure, the members used to compare
240 	 * are the sockaddr and and then is-ssl bool, and then ptr value is
241 	 * used in case the same address exists several times in the tree
242 	 * when there are multiple connections to the same destination to
243 	 * make the rbtree items unique. */
244 	rbnode_type node;
245 	/** the key for the tcp_reuse tree. address of peer, ip4 or ip6,
246 	 * and port number of peer */
247 	struct sockaddr_storage addr;
248 	/** length of addr */
249 	socklen_t addrlen;
250 	/** also key for tcp_reuse tree, if ssl is used */
251 	int is_ssl;
252 	/** lru chain, so that the oldest can be removed to get a new
253 	 * connection when all are in (re)use. oldest is last in list.
254 	 * The lru only contains empty connections waiting for reuse,
255 	 * the ones with active queries are not on the list because they
256 	 * do not need to be closed to make space for others.  They already
257 	 * service a query so the close for another query does not help
258 	 * service a larger number of queries. */
259 	struct reuse_tcp* lru_next, *lru_prev;
260 	/** true if the reuse_tcp item is on the lru list with empty items */
261 	int item_on_lru_list;
262 	/** the connection to reuse, the fd is non-1 and is open.
263 	 * the addr and port determine where the connection is going,
264 	 * and is key to the rbtree.  The SSL ptr determines if it is
265 	 * a TLS connection or a plain TCP connection there.  And TLS
266 	 * or not is also part of the key to the rbtree.
267 	 * There is a timeout and read event on the fd, to close it. */
268 	struct pending_tcp* pending;
269 	/**
270 	 * The more read again value pointed to by the commpoint
271 	 * tcp_more_read_again pointer, so that it exists after commpoint
272 	 * delete
273 	 */
274 	int cp_more_read_again;
275 	/**
276 	 * The more write again value pointed to by the commpoint
277 	 * tcp_more_write_again pointer, so that it exists after commpoint
278 	 * delete
279 	 */
280 	int cp_more_write_again;
281 	/** rbtree with other queries waiting on the connection, by ID number,
282 	 * of type struct waiting_tcp. It is for looking up received
283 	 * answers to the structure for callback.  And also to see if ID
284 	 * numbers are unused and can be used for a new query.
285 	 * The write_wait elements are also in the tree, so that ID numbers
286 	 * can be looked up also for them.  They are bool write_wait_queued. */
287 	rbtree_type tree_by_id;
288 	/** list of queries waiting to be written on the channel,
289 	 * if NULL no queries are waiting to be written and the pending->query
290 	 * is the query currently serviced.  The first is the next in line.
291 	 * They are also in the tree_by_id. Once written, the are removed
292 	 * from this list, but stay in the tree. */
293 	struct waiting_tcp* write_wait_first, *write_wait_last;
294 	/** the outside network it is part of */
295 	struct outside_network* outnet;
296 };
297 
298 /** max number of queries on a reuse connection */
299 #define MAX_REUSE_TCP_QUERIES 200
300 /** timeout for REUSE entries in milliseconds. */
301 #define REUSE_TIMEOUT 60000
302 
303 /**
304  * A query that has an answer pending for it.
305  */
306 struct pending {
307 	/** redblacktree entry, key is the pending struct(id, addr). */
308 	rbnode_type node;
309 	/** the ID for the query. int so that a value out of range can
310 	 * be used to signify a pending that is for certain not present in
311 	 * the rbtree. (and for which deletion is safe). */
312 	unsigned int id;
313 	/** remote address. */
314 	struct sockaddr_storage addr;
315 	/** length of addr field in use. */
316 	socklen_t addrlen;
317 	/** comm point it was sent on (and reply must come back on). */
318 	struct port_comm* pc;
319 	/** timeout event */
320 	struct comm_timer* timer;
321 	/** callback for the timeout, error or reply to the message */
322 	comm_point_callback_type* cb;
323 	/** callback user argument */
324 	void* cb_arg;
325 	/** the outside network it is part of */
326 	struct outside_network* outnet;
327 	/** the corresponding serviced_query */
328 	struct serviced_query* sq;
329 
330 	/*---- filled if udp pending is waiting -----*/
331 	/** next in waiting list. */
332 	struct pending* next_waiting;
333 	/** timeout in msec */
334 	int timeout;
335 	/** The query itself, the query packet to send. */
336 	uint8_t* pkt;
337 	/** length of query packet. */
338 	size_t pkt_len;
339 };
340 
341 /**
342  * Pending TCP query to server.
343  */
344 struct pending_tcp {
345 	/** next in list of free tcp comm points, or NULL. */
346 	struct pending_tcp* next_free;
347 	/** tcp comm point it was sent on (and reply must come back on). */
348 	struct comm_point* c;
349 	/** the query being serviced, NULL if the pending_tcp is unused. */
350 	struct waiting_tcp* query;
351 	/** the pre-allocated reuse tcp structure.  if ->pending is nonNULL
352 	 * it is in use and the connection is waiting for reuse.
353 	 * It is here for memory pre-allocation, and used to make this
354 	 * pending_tcp wait for reuse. */
355 	struct reuse_tcp reuse;
356 };
357 
358 /**
359  * Query waiting for TCP buffer.
360  */
361 struct waiting_tcp {
362 	/**
363 	 * next in waiting list.
364 	 * if on_tcp_waiting_list==0, this points to the pending_tcp structure.
365 	 */
366 	struct waiting_tcp* next_waiting;
367 	/** if true the item is on the tcp waiting list and next_waiting
368 	 * is used for that.  If false, the next_waiting points to the
369 	 * pending_tcp */
370 	int on_tcp_waiting_list;
371 	/** next and prev in query waiting list for stream connection */
372 	struct waiting_tcp* write_wait_prev, *write_wait_next;
373 	/** true if the waiting_tcp structure is on the write_wait queue */
374 	int write_wait_queued;
375 	/** entry in reuse.tree_by_id, if key is NULL, not in tree, otherwise,
376 	 * this struct is key and sorted by ID (from waiting_tcp.id). */
377 	rbnode_type id_node;
378 	/** the ID for the query; checked in reply */
379 	uint16_t id;
380 	/** timeout event; timer keeps running whether the query is
381 	 * waiting for a buffer or the tcp reply is pending */
382 	struct comm_timer* timer;
383 	/** timeout in msec */
384 	int timeout;
385 	/** the outside network it is part of */
386 	struct outside_network* outnet;
387 	/** remote address. */
388 	struct sockaddr_storage addr;
389 	/** length of addr field in use. */
390 	socklen_t addrlen;
391 	/**
392 	 * The query itself, the query packet to send.
393 	 * allocated after the waiting_tcp structure.
394 	 */
395 	uint8_t* pkt;
396 	/** length of query packet. */
397 	size_t pkt_len;
398 	/** callback for the timeout, error or reply to the message,
399 	 * or NULL if no user is waiting. the entry uses an ID number.
400 	 * a query that was written is no longer needed, but the ID number
401 	 * and a reply will come back and can be ignored if NULL */
402 	comm_point_callback_type* cb;
403 	/** callback user argument */
404 	void* cb_arg;
405 	/** if it uses ssl upstream */
406 	int ssl_upstream;
407 	/** ref to the tls_auth_name from the serviced_query */
408 	char* tls_auth_name;
409 	/** the packet was involved in an error, to stop looping errors */
410 	int error_count;
411 };
412 
413 /**
414  * Callback to party interested in serviced query results.
415  */
416 struct service_callback {
417 	/** next in callback list */
418 	struct service_callback* next;
419 	/** callback function */
420 	comm_point_callback_type* cb;
421 	/** user argument for callback function */
422 	void* cb_arg;
423 };
424 
425 /** fallback size for fragmentation for EDNS in IPv4 */
426 #define EDNS_FRAG_SIZE_IP4 1472
427 /** fallback size for EDNS in IPv6, fits one fragment with ip6-tunnel-ids */
428 #define EDNS_FRAG_SIZE_IP6 1232
429 
430 /**
431  * Query service record.
432  * Contains query and destination. UDP, TCP, EDNS are all tried.
433  * complete with retries and timeouts. A number of interested parties can
434  * receive a callback.
435  */
436 struct serviced_query {
437 	/** The rbtree node, key is this record */
438 	rbnode_type node;
439 	/** The query that needs to be answered. Starts with flags u16,
440 	 * then qdcount, ..., including qname, qtype, qclass. Does not include
441 	 * EDNS record. */
442 	uint8_t* qbuf;
443 	/** length of qbuf. */
444 	size_t qbuflen;
445 	/** If an EDNS section is included, the DO/CD bit will be turned on. */
446 	int dnssec;
447 	/** We want signatures, or else the answer is likely useless */
448 	int want_dnssec;
449 	/** ignore capsforid */
450 	int nocaps;
451 	/** tcp upstream used, use tcp, or ssl_upstream for SSL */
452 	int tcp_upstream, ssl_upstream;
453 	/** the name of the tls authentication name, eg. 'ns.example.com'
454 	 * or NULL */
455 	char* tls_auth_name;
456 	/** where to send it */
457 	struct sockaddr_storage addr;
458 	/** length of addr field in use. */
459 	socklen_t addrlen;
460 	/** zone name, uncompressed domain name in wireformat */
461 	uint8_t* zone;
462 	/** length of zone name */
463 	size_t zonelen;
464 	/** qtype */
465 	int qtype;
466 	/** current status */
467 	enum serviced_query_status {
468 		/** initial status */
469 		serviced_initial,
470 		/** UDP with EDNS sent */
471 		serviced_query_UDP_EDNS,
472 		/** UDP without EDNS sent */
473 		serviced_query_UDP,
474 		/** TCP with EDNS sent */
475 		serviced_query_TCP_EDNS,
476 		/** TCP without EDNS sent */
477 		serviced_query_TCP,
478 		/** probe to test noEDNS0 (EDNS gives FORMERRorNOTIMP) */
479 		serviced_query_UDP_EDNS_fallback,
480 		/** probe to test TCP noEDNS0 (EDNS gives FORMERRorNOTIMP) */
481 		serviced_query_TCP_EDNS_fallback,
482 		/** send UDP query with EDNS1480 (or 1280) */
483 		serviced_query_UDP_EDNS_FRAG
484 	}
485 		/** variable with current status */
486 		status;
487 	/** true if serviced_query is scheduled for deletion already */
488 	int to_be_deleted;
489 	/** number of UDP retries */
490 	int retry;
491 	/** time last UDP was sent */
492 	struct timeval last_sent_time;
493 	/** rtt of last message */
494 	int last_rtt;
495 	/** do we know edns probe status already, for UDP_EDNS queries */
496 	int edns_lame_known;
497 	/** edns options to use for sending upstream packet */
498 	struct edns_option* opt_list;
499 	/** outside network this is part of */
500 	struct outside_network* outnet;
501 	/** list of interested parties that need callback on results. */
502 	struct service_callback* cblist;
503 	/** the UDP or TCP query that is pending, see status which */
504 	void* pending;
505 };
506 
507 /**
508  * Create outside_network structure with N udp ports.
509  * @param base: the communication base to use for event handling.
510  * @param bufsize: size for network buffers.
511  * @param num_ports: number of udp ports to open per interface.
512  * @param ifs: interface names (or NULL for default interface).
513  *    These interfaces must be able to access all authoritative servers.
514  * @param num_ifs: number of names in array ifs.
515  * @param do_ip4: service IP4.
516  * @param do_ip6: service IP6.
517  * @param num_tcp: number of outgoing tcp buffers to preallocate.
518  * @param dscp: DSCP to use.
519  * @param infra: pointer to infra cached used for serviced queries.
520  * @param rnd: stored to create random numbers for serviced queries.
521  * @param use_caps_for_id: enable to use 0x20 bits to encode id randomness.
522  * @param availports: array of available ports.
523  * @param numavailports: number of available ports in array.
524  * @param unwanted_threshold: when to take defensive action.
525  * @param unwanted_action: the action to take.
526  * @param unwanted_param: user parameter to action.
527  * @param tcp_mss: maximum segment size of tcp socket.
528  * @param do_udp: if udp is done.
529  * @param sslctx: context to create outgoing connections with (if enabled).
530  * @param delayclose: if not 0, udp sockets are delayed before timeout closure.
531  * 	msec to wait on timeouted udp sockets.
532  * @param tls_use_sni: if SNI is used for TLS connections.
533  * @param dtenv: environment to send dnstap events with (if enabled).
534  * @param udp_connect: if the udp_connect option is enabled.
535  * @return: the new structure (with no pending answers) or NULL on error.
536  */
537 struct outside_network* outside_network_create(struct comm_base* base,
538 	size_t bufsize, size_t num_ports, char** ifs, int num_ifs,
539 	int do_ip4, int do_ip6, size_t num_tcp, int dscp, struct infra_cache* infra,
540 	struct ub_randstate* rnd, int use_caps_for_id, int* availports,
541 	int numavailports, size_t unwanted_threshold, int tcp_mss,
542 	void (*unwanted_action)(void*), void* unwanted_param, int do_udp,
543 	void* sslctx, int delayclose, int tls_use_sni, struct dt_env *dtenv,
544 	int udp_connect);
545 
546 /**
547  * Delete outside_network structure.
548  * @param outnet: object to delete.
549  */
550 void outside_network_delete(struct outside_network* outnet);
551 
552 /**
553  * Prepare for quit. Sends no more queries, even if queued up.
554  * @param outnet: object to prepare for removal
555  */
556 void outside_network_quit_prepare(struct outside_network* outnet);
557 
558 /**
559  * Send UDP query, create pending answer.
560  * Changes the ID for the query to be random and unique for that destination.
561  * @param sq: serviced query.
562  * @param packet: wireformat query to send to destination.
563  * @param timeout: in milliseconds from now.
564  * @param callback: function to call on error, timeout or reply.
565  * @param callback_arg: user argument for callback function.
566  * @return: NULL on error for malloc or socket. Else the pending query object.
567  */
568 struct pending* pending_udp_query(struct serviced_query* sq,
569 	struct sldns_buffer* packet, int timeout, comm_point_callback_type* callback,
570 	void* callback_arg);
571 
572 /**
573  * Send TCP query. May wait for TCP buffer. Selects ID to be random, and
574  * checks id.
575  * @param sq: serviced query.
576  * @param packet: wireformat query to send to destination. copied from.
577  * @param timeout: in milliseconds from now.
578  *    Timer starts running now. Timer may expire if all buffers are used,
579  *    without any query been sent to the server yet.
580  * @param callback: function to call on error, timeout or reply.
581  * @param callback_arg: user argument for callback function.
582  * @return: false on error for malloc or socket. Else the pending TCP object.
583  */
584 struct waiting_tcp* pending_tcp_query(struct serviced_query* sq,
585 	struct sldns_buffer* packet, int timeout, comm_point_callback_type* callback,
586 	void* callback_arg);
587 
588 /**
589  * Delete pending answer.
590  * @param outnet: outside network the pending query is part of.
591  *    Internal feature: if outnet is NULL, p is not unlinked from rbtree.
592  * @param p: deleted
593  */
594 void pending_delete(struct outside_network* outnet, struct pending* p);
595 
596 /**
597  * Perform a serviced query to the authoritative servers.
598  * Duplicate efforts are detected, and EDNS, TCP and UDP retry is performed.
599  * @param outnet: outside network, with rbtree of serviced queries.
600  * @param qinfo: query info.
601  * @param flags: flags u16 (host format), includes opcode, CD bit.
602  * @param dnssec: if set, DO bit is set in EDNS queries.
603  *	If the value includes BIT_CD, CD bit is set when in EDNS queries.
604  *	If the value includes BIT_DO, DO bit is set when in EDNS queries.
605  * @param want_dnssec: signatures are needed, without EDNS the answer is
606  * 	likely to be useless.
607  * @param nocaps: ignore use_caps_for_id and use unperturbed qname.
608  * @param tcp_upstream: use TCP for upstream queries.
609  * @param ssl_upstream: use SSL for upstream queries.
610  * @param tls_auth_name: when ssl_upstream is true, use this name to check
611  * 	the server's peer certificate.
612  * @param addr: to which server to send the query.
613  * @param addrlen: length of addr.
614  * @param zone: name of the zone of the delegation point. wireformat dname.
615 	This is the delegation point name for which the server is deemed
616 	authoritative.
617  * @param zonelen: length of zone.
618  * @param qstate: module qstate. Mainly for inspecting the available
619  *	edns_opts_lists.
620  * @param callback: callback function.
621  * @param callback_arg: user argument to callback function.
622  * @param buff: scratch buffer to create query contents in. Empty on exit.
623  * @param env: the module environment.
624  * @return 0 on error, or pointer to serviced query that is used to answer
625  *	this serviced query may be shared with other callbacks as well.
626  */
627 struct serviced_query* outnet_serviced_query(struct outside_network* outnet,
628 	struct query_info* qinfo, uint16_t flags, int dnssec, int want_dnssec,
629 	int nocaps, int tcp_upstream, int ssl_upstream, char* tls_auth_name,
630 	struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
631 	size_t zonelen, struct module_qstate* qstate,
632 	comm_point_callback_type* callback, void* callback_arg,
633 	struct sldns_buffer* buff, struct module_env* env);
634 
635 /**
636  * Remove service query callback.
637  * If that leads to zero callbacks, the query is completely cancelled.
638  * @param sq: serviced query to adjust.
639  * @param cb_arg: callback argument of callback that needs removal.
640  *	same as the callback_arg to outnet_serviced_query().
641  */
642 void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg);
643 
644 /**
645  * Get memory size in use by outside network.
646  * Counts buffers and outstanding query (serviced queries) malloced data.
647  * @param outnet: outside network structure.
648  * @return size in bytes.
649  */
650 size_t outnet_get_mem(struct outside_network* outnet);
651 
652 /**
653  * Get memory size in use by serviced query while it is servicing callbacks.
654  * This takes into account the pre-deleted status of it; it will be deleted
655  * when the callbacks are done.
656  * @param sq: serviced query.
657  * @return size in bytes.
658  */
659 size_t serviced_get_mem(struct serviced_query* sq);
660 
661 /** Pick random ID value for a tcp stream, avoids existing IDs. */
662 uint16_t reuse_tcp_select_id(struct reuse_tcp* reuse,
663 	struct outside_network* outnet);
664 
665 /** find element in tree by id */
666 struct waiting_tcp* reuse_tcp_by_id_find(struct reuse_tcp* reuse, uint16_t id);
667 
668 /** insert element in tree by id */
669 void reuse_tree_by_id_insert(struct reuse_tcp* reuse, struct waiting_tcp* w);
670 
671 /** delete readwait waiting_tcp elements, deletes the elements in the list */
672 void reuse_del_readwait(rbtree_type* tree_by_id);
673 
674 /** get TCP file descriptor for address, returns -1 on failure,
675  * tcp_mss is 0 or maxseg size to set for TCP packets. */
676 int outnet_get_tcp_fd(struct sockaddr_storage* addr, socklen_t addrlen, int tcp_mss, int dscp);
677 
678 /**
679  * Create udp commpoint suitable for sending packets to the destination.
680  * @param outnet: outside_network with the comm_base it is attached to,
681  * 	with the outgoing interfaces chosen from, and rnd gen for random.
682  * @param cb: callback function for the commpoint.
683  * @param cb_arg: callback argument for cb.
684  * @param to_addr: intended destination.
685  * @param to_addrlen: length of to_addr.
686  * @return commpoint that you can comm_point_send_udp_msg with, or NULL.
687  */
688 struct comm_point* outnet_comm_point_for_udp(struct outside_network* outnet,
689 	comm_point_callback_type* cb, void* cb_arg,
690 	struct sockaddr_storage* to_addr, socklen_t to_addrlen);
691 
692 /**
693  * Create tcp commpoint suitable for communication to the destination.
694  * It also performs connect() to the to_addr.
695  * @param outnet: outside_network with the comm_base it is attached to,
696  * 	and the tcp_mss.
697  * @param cb: callback function for the commpoint.
698  * @param cb_arg: callback argument for cb.
699  * @param to_addr: intended destination.
700  * @param to_addrlen: length of to_addr.
701  * @param query: initial packet to send writing, in buffer.  It is copied
702  * 	to the commpoint buffer that is created.
703  * @param timeout: timeout for the TCP connection.
704  * 	timeout in milliseconds, or -1 for no (change to the) timeout.
705  *	So seconds*1000.
706  * @param ssl: set to true for TLS.
707  * @param host: hostname for host name verification of TLS (or NULL if no TLS).
708  * @return tcp_out commpoint, or NULL.
709  */
710 struct comm_point* outnet_comm_point_for_tcp(struct outside_network* outnet,
711 	comm_point_callback_type* cb, void* cb_arg,
712 	struct sockaddr_storage* to_addr, socklen_t to_addrlen,
713 	struct sldns_buffer* query, int timeout, int ssl, char* host);
714 
715 /**
716  * Create http commpoint suitable for communication to the destination.
717  * Creates the http request buffer. It also performs connect() to the to_addr.
718  * @param outnet: outside_network with the comm_base it is attached to,
719  * 	and the tcp_mss.
720  * @param cb: callback function for the commpoint.
721  * @param cb_arg: callback argument for cb.
722  * @param to_addr: intended destination.
723  * @param to_addrlen: length of to_addr.
724  * @param timeout: timeout for the TCP connection.
725  * 	timeout in milliseconds, or -1 for no (change to the) timeout.
726  *	So seconds*1000.
727  * @param ssl: set to true for https.
728  * @param host: hostname to use for the destination. part of http request.
729  * @param path: pathname to lookup, eg. name of the file on the destination.
730  * @return http_out commpoint, or NULL.
731  */
732 struct comm_point* outnet_comm_point_for_http(struct outside_network* outnet,
733 	comm_point_callback_type* cb, void* cb_arg,
734 	struct sockaddr_storage* to_addr, socklen_t to_addrlen, int timeout,
735 	int ssl, char* host, char* path);
736 
737 /** connect tcp connection to addr, 0 on failure */
738 int outnet_tcp_connect(int s, struct sockaddr_storage* addr, socklen_t addrlen);
739 
740 /** callback for incoming udp answers from the network */
741 int outnet_udp_cb(struct comm_point* c, void* arg, int error,
742 	struct comm_reply *reply_info);
743 
744 /** callback for pending tcp connections */
745 int outnet_tcp_cb(struct comm_point* c, void* arg, int error,
746 	struct comm_reply *reply_info);
747 
748 /** callback for udp timeout */
749 void pending_udp_timer_cb(void *arg);
750 
751 /** callback for udp delay for timeout */
752 void pending_udp_timer_delay_cb(void *arg);
753 
754 /** callback for outgoing TCP timer event */
755 void outnet_tcptimer(void* arg);
756 
757 /** callback for serviced query UDP answers */
758 int serviced_udp_callback(struct comm_point* c, void* arg, int error,
759         struct comm_reply* rep);
760 
761 /** TCP reply or error callback for serviced queries */
762 int serviced_tcp_callback(struct comm_point* c, void* arg, int error,
763         struct comm_reply* rep);
764 
765 /** compare function of pending rbtree */
766 int pending_cmp(const void* key1, const void* key2);
767 
768 /** compare function of serviced query rbtree */
769 int serviced_cmp(const void* key1, const void* key2);
770 
771 /** compare function of reuse_tcp rbtree in outside_network struct */
772 int reuse_cmp(const void* key1, const void* key2);
773 
774 /** compare function of reuse_tcp tree_by_id rbtree */
775 int reuse_id_cmp(const void* key1, const void* key2);
776 
777 #endif /* OUTSIDE_NETWORK_H */
778