1 /*
2  * services/listen_dnsport.h - listen on port 53 for incoming DNS queries.
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 get queries from clients.
40  */
41 
42 #ifndef LISTEN_DNSPORT_H
43 #define LISTEN_DNSPORT_H
44 
45 #include "util/netevent.h"
46 #ifdef HAVE_NGHTTP2_NGHTTP2_H
47 #include <nghttp2/nghttp2.h>
48 #endif
49 struct listen_list;
50 struct config_file;
51 struct addrinfo;
52 struct sldns_buffer;
53 struct tcl_list;
54 
55 /**
56  * Listening for queries structure.
57  * Contains list of query-listen sockets.
58  */
59 struct listen_dnsport {
60 	/** Base for select calls */
61 	struct comm_base* base;
62 
63 	/** buffer shared by UDP connections, since there is only one
64 	    datagram at any time. */
65 	struct sldns_buffer* udp_buff;
66 #ifdef USE_DNSCRYPT
67 	struct sldns_buffer* dnscrypt_udp_buff;
68 #endif
69 	/** list of comm points used to get incoming events */
70 	struct listen_list* cps;
71 };
72 
73 /**
74  * Single linked list to store event points.
75  */
76 struct listen_list {
77 	/** next in list */
78 	struct listen_list* next;
79 	/** event info */
80 	struct comm_point* com;
81 };
82 
83 /**
84  * type of ports
85  */
86 enum listen_type {
87 	/** udp type */
88 	listen_type_udp,
89 	/** tcp type */
90 	listen_type_tcp,
91 	/** udp ipv6 (v4mapped) for use with ancillary data */
92 	listen_type_udpancil,
93 	/** ssl over tcp type */
94 	listen_type_ssl,
95 	/** udp type  + dnscrypt*/
96 	listen_type_udp_dnscrypt,
97 	/** tcp type + dnscrypt */
98 	listen_type_tcp_dnscrypt,
99 	/** udp ipv6 (v4mapped) for use with ancillary data + dnscrypt*/
100 	listen_type_udpancil_dnscrypt,
101 	/** HTTP(2) over TLS over TCP */
102 	listen_type_http
103 };
104 
105 /*
106  * socket properties (just like NSD nsd_socket structure definition)
107  */
108 struct unbound_socket {
109 	/** socket-address structure */
110         struct addrinfo *       addr;
111 	/** socket descriptor returned by socket() syscall */
112         int                     s;
113 	/** address family (AF_INET/IF_INET6) */
114         int                     fam;
115 };
116 
117 /**
118  * Single linked list to store shared ports that have been
119  * opened for use by all threads.
120  */
121 struct listen_port {
122 	/** next in list */
123 	struct listen_port* next;
124 	/** file descriptor, open and ready for use */
125 	int fd;
126 	/** type of file descriptor, udp or tcp */
127 	enum listen_type ftype;
128 	/** fill in unbpound_socket structure for every opened socket at Unbound startup */
129 	struct unbound_socket* socket;
130 };
131 
132 /**
133  * Create shared listening ports
134  * Getaddrinfo, create socket, bind and listen to zero or more
135  * interfaces for IP4 and/or IP6, for UDP and/or TCP.
136  * On the given port number. It creates the sockets.
137  * @param cfg: settings on what ports to open.
138  * @param ifs: interfaces to open, array of IP addresses, "ip[@port]".
139  * @param num_ifs: length of ifs.
140  * @param reuseport: set to true if you want reuseport, or NULL to not have it,
141  *   set to false on exit if reuseport failed to apply (because of no
142  *   kernel support).
143  * @return: linked list of ports or NULL on error.
144  */
145 struct listen_port* listening_ports_open(struct config_file* cfg,
146 	char** ifs, int num_ifs, int* reuseport);
147 
148 /**
149  * Close and delete the (list of) listening ports.
150  */
151 void listening_ports_free(struct listen_port* list);
152 
153 struct config_strlist;
154 /**
155  * Resolve interface names in config and store result IP addresses
156  * @param ifs: array of interfaces.  The list of interface names, if not NULL.
157  * @param num_ifs: length of ifs array.
158  * @param list: if not NULL, this is used as the list of interface names.
159  * @param resif: string array (malloced array of malloced strings) with
160  * 	result.  NULL if cfg has none.
161  * @param num_resif: length of resif.  Zero if cfg has zero num_ifs.
162  * @return 0 on failure.
163  */
164 int resolve_interface_names(char** ifs, int num_ifs,
165 	struct config_strlist* list, char*** resif, int* num_resif);
166 
167 /**
168  * Create commpoints with for this thread for the shared ports.
169  * @param base: the comm_base that provides event functionality.
170  *	for default all ifs.
171  * @param ports: the list of shared ports.
172  * @param bufsize: size of datagram buffer.
173  * @param tcp_accept_count: max number of simultaneous TCP connections
174  * 	from clients.
175  * @param tcp_idle_timeout: idle timeout for TCP connections in msec.
176  * @param harden_large_queries: whether query size should be limited.
177  * @param http_max_streams: maximum number of HTTP/2 streams per connection.
178  * @param http_endpoint: HTTP endpoint to service queries on
179  * @param http_notls: no TLS for http downstream
180  * @param tcp_conn_limit: TCP connection limit info.
181  * @param sslctx: nonNULL if ssl context.
182  * @param dtenv: nonNULL if dnstap enabled.
183  * @param cb: callback function when a request arrives. It is passed
184  *	  the packet and user argument. Return true to send a reply.
185  * @param cb_arg: user data argument for callback function.
186  * @return: the malloced listening structure, ready for use. NULL on error.
187  */
188 struct listen_dnsport*
189 listen_create(struct comm_base* base, struct listen_port* ports,
190 	size_t bufsize, int tcp_accept_count, int tcp_idle_timeout,
191 	int harden_large_queries, uint32_t http_max_streams,
192 	char* http_endpoint, int http_notls, struct tcl_list* tcp_conn_limit,
193 	void* sslctx, struct dt_env* dtenv, comm_point_callback_type* cb,
194 	void *cb_arg);
195 
196 /**
197  * delete the listening structure
198  * @param listen: listening structure.
199  */
200 void listen_delete(struct listen_dnsport* listen);
201 
202 /** setup the locks for the listen ports */
203 void listen_setup_locks(void);
204 /** desetup the locks for the listen ports */
205 void listen_desetup_locks(void);
206 
207 /**
208  * delete listen_list of commpoints. Calls commpointdelete() on items.
209  * This may close the fds or not depending on flags.
210  * @param list: to delete.
211  */
212 void listen_list_delete(struct listen_list* list);
213 
214 /**
215  * get memory size used by the listening structs
216  * @param listen: listening structure.
217  * @return: size in bytes.
218  */
219 size_t listen_get_mem(struct listen_dnsport* listen);
220 
221 /**
222  * stop accept handlers for TCP (until enabled again)
223  * @param listen: listening structure.
224  */
225 void listen_stop_accept(struct listen_dnsport* listen);
226 
227 /**
228  * start accept handlers for TCP (was stopped before)
229  * @param listen: listening structure.
230  */
231 void listen_start_accept(struct listen_dnsport* listen);
232 
233 /**
234  * Create and bind nonblocking UDP socket
235  * @param family: for socket call.
236  * @param socktype: for socket call.
237  * @param addr: for bind call.
238  * @param addrlen: for bind call.
239  * @param v6only: if enabled, IP6 sockets get IP6ONLY option set.
240  * 	if enabled with value 2 IP6ONLY option is disabled.
241  * @param inuse: on error, this is set true if the port was in use.
242  * @param noproto: on error, this is set true if cause is that the
243 	IPv6 proto (family) is not available.
244  * @param rcv: set size on rcvbuf with socket option, if 0 it is not set.
245  * @param snd: set size on sndbuf with socket option, if 0 it is not set.
246  * @param listen: if true, this is a listening UDP port, eg port 53, and
247  * 	set SO_REUSEADDR on it.
248  * @param reuseport: if nonNULL and true, try to set SO_REUSEPORT on
249  * 	listening UDP port.  Set to false on return if it failed to do so.
250  * @param transparent: set IP_TRANSPARENT socket option.
251  * @param freebind: set IP_FREEBIND socket option.
252  * @param use_systemd: if true, fetch sockets from systemd.
253  * @param dscp: DSCP to use.
254  * @return: the socket. -1 on error.
255  */
256 int create_udp_sock(int family, int socktype, struct sockaddr* addr,
257 	socklen_t addrlen, int v6only, int* inuse, int* noproto, int rcv,
258 	int snd, int listen, int* reuseport, int transparent, int freebind, int use_systemd, int dscp);
259 
260 /**
261  * Create and bind TCP listening socket
262  * @param addr: address info ready to make socket.
263  * @param v6only: enable ip6 only flag on ip6 sockets.
264  * @param noproto: if error caused by lack of protocol support.
265  * @param reuseport: if nonNULL and true, try to set SO_REUSEPORT on
266  * 	listening UDP port.  Set to false on return if it failed to do so.
267  * @param transparent: set IP_TRANSPARENT socket option.
268  * @param mss: maximum segment size of the socket. if zero, leaves the default.
269  * @param nodelay: if true set TCP_NODELAY and TCP_QUICKACK socket options.
270  * @param freebind: set IP_FREEBIND socket option.
271  * @param use_systemd: if true, fetch sockets from systemd.
272  * @param dscp: DSCP to use.
273  * @return: the socket. -1 on error.
274  */
275 int create_tcp_accept_sock(struct addrinfo *addr, int v6only, int* noproto,
276 	int* reuseport, int transparent, int mss, int nodelay, int freebind,
277 	int use_systemd, int dscp);
278 
279 /**
280  * Create and bind local listening socket
281  * @param path: path to the socket.
282  * @param noproto: on error, this is set true if cause is that local sockets
283  *	are not supported.
284  * @param use_systemd: if true, fetch sockets from systemd.
285  * @return: the socket. -1 on error.
286  */
287 int create_local_accept_sock(const char* path, int* noproto, int use_systemd);
288 
289 /**
290  * TCP request info.  List of requests outstanding on the channel, that
291  * are asked for but not yet answered back.
292  */
293 struct tcp_req_info {
294 	/** the TCP comm point for this.  Its buffer is used for read/write */
295 	struct comm_point* cp;
296 	/** the buffer to use to spool reply from mesh into,
297 	 * it can then be copied to the result list and written.
298 	 * it is a pointer to the shared udp buffer. */
299 	struct sldns_buffer* spool_buffer;
300 	/** are we in worker_handle function call (for recursion callback)*/
301 	int in_worker_handle;
302 	/** is the comm point dropped (by worker handle).
303 	 * That means we have to disconnect the channel. */
304 	int is_drop;
305 	/** is the comm point set to send_reply (by mesh new client in worker
306 	 * handle), if so answer is available in c.buffer */
307 	int is_reply;
308 	/** read channel has closed, just write pending results */
309 	int read_is_closed;
310 	/** read again */
311 	int read_again;
312 	/** number of outstanding requests */
313 	int num_open_req;
314 	/** list of outstanding requests */
315 	struct tcp_req_open_item* open_req_list;
316 	/** number of pending writeable results */
317 	int num_done_req;
318 	/** list of pending writable result packets, malloced one at a time */
319 	struct tcp_req_done_item* done_req_list;
320 };
321 
322 /**
323  * List of open items in TCP channel
324  */
325 struct tcp_req_open_item {
326 	/** next in list */
327 	struct tcp_req_open_item* next;
328 	/** the mesh area of the mesh_state */
329 	struct mesh_area* mesh;
330 	/** the mesh state */
331 	struct mesh_state* mesh_state;
332 };
333 
334 /**
335  * List of done items in TCP channel
336  */
337 struct tcp_req_done_item {
338 	/** next in list */
339 	struct tcp_req_done_item* next;
340 	/** the buffer with packet contents */
341 	uint8_t* buf;
342 	/** length of the buffer */
343 	size_t len;
344 };
345 
346 /**
347  * Create tcp request info structure that keeps track of open
348  * requests on the TCP channel that are resolved at the same time,
349  * and the pending results that have to get written back to that client.
350  * @param spoolbuf: shared buffer
351  * @return new structure or NULL on alloc failure.
352  */
353 struct tcp_req_info* tcp_req_info_create(struct sldns_buffer* spoolbuf);
354 
355 /**
356  * Delete tcp request structure.  Called by owning commpoint.
357  * Removes mesh entry references and stored results from the lists.
358  * @param req: the tcp request info
359  */
360 void tcp_req_info_delete(struct tcp_req_info* req);
361 
362 /**
363  * Clear tcp request structure.  Removes list entries, sets it up ready
364  * for the next connection.
365  * @param req: tcp request info structure.
366  */
367 void tcp_req_info_clear(struct tcp_req_info* req);
368 
369 /**
370  * Remove mesh state entry from list in tcp_req_info.
371  * caller has to manage the mesh state reply entry in the mesh state.
372  * @param req: the tcp req info that has the entry removed from the list.
373  * @param m: the state removed from the list.
374  */
375 void tcp_req_info_remove_mesh_state(struct tcp_req_info* req,
376 	struct mesh_state* m);
377 
378 /**
379  * Handle write done of the last result packet
380  * @param req: the tcp req info.
381  */
382 void tcp_req_info_handle_writedone(struct tcp_req_info* req);
383 
384 /**
385  * Handle read done of a new request from the client
386  * @param req: the tcp req info.
387  */
388 void tcp_req_info_handle_readdone(struct tcp_req_info* req);
389 
390 /**
391  * Add mesh state to the tcp req list of open requests.
392  * So the comm_reply can be removed off the mesh reply list when
393  * the tcp channel has to be closed (for other reasons then that that
394  * request was done, eg. channel closed by client or some format error).
395  * @param req: tcp req info structure.  It keeps track of the simultaneous
396  * 	requests and results on a tcp (or TLS) channel.
397  * @param mesh: mesh area for the state.
398  * @param m: mesh state to add.
399  * @return 0 on failure (malloc failure).
400  */
401 int tcp_req_info_add_meshstate(struct tcp_req_info* req,
402 	struct mesh_area* mesh, struct mesh_state* m);
403 
404 /**
405  * Send reply on tcp simultaneous answer channel.  May queue it up.
406  * @param req: request info structure.
407  */
408 void tcp_req_info_send_reply(struct tcp_req_info* req);
409 
410 /** the read channel has closed
411  * @param req: request. remaining queries are looked up and answered.
412  * @return zero if nothing to do, just close the tcp.
413  */
414 int tcp_req_info_handle_read_close(struct tcp_req_info* req);
415 
416 /** get the size of currently used tcp stream wait buffers (in bytes) */
417 size_t tcp_req_info_get_stream_buffer_size(void);
418 
419 /** get the size of currently used HTTP2 query buffers (in bytes) */
420 size_t http2_get_query_buffer_size(void);
421 /** get the size of currently used HTTP2 response buffers (in bytes) */
422 size_t http2_get_response_buffer_size(void);
423 
424 #ifdef HAVE_NGHTTP2
425 /**
426  * Create nghttp2 callbacks to handle HTTP2 requests.
427  * @return malloc'ed struct, NULL on failure
428  */
429 nghttp2_session_callbacks* http2_req_callbacks_create(void);
430 
431 /** Free http2 stream buffers and decrease buffer counters */
432 void http2_req_stream_clear(struct http2_stream* h2_stream);
433 
434 /**
435  * DNS response ready to be submitted to nghttp2, to be prepared for sending
436  * out. Response is stored in c->buffer. Copy to rbuffer because the c->buffer
437  * might be used before this will be send out.
438  * @param h2_session: http2 session, containing c->buffer which contains answer
439  * @param h2_stream: http2 stream, containing buffer to store answer in
440  * @return 0 on error, 1 otherwise
441  */
442 int http2_submit_dns_response(struct http2_session* h2_session);
443 #else
444 int http2_submit_dns_response(void* v);
445 #endif /* HAVE_NGHTTP2 */
446 
447 char* set_ip_dscp(int socket, int addrfamily, int ds);
448 
449 /** for debug and profiling purposes only
450  * @param ub_sock: the structure containing created socket info we want to print or log for
451  */
452 void verbose_print_unbound_socket(struct unbound_socket* ub_sock);
453 
454 #endif /* LISTEN_DNSPORT_H */
455