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