1 /*
2  * include/types/listener.h
3  * This file defines the structures needed to manage listeners.
4  *
5  * Copyright (C) 2000-2012 Willy Tarreau - w@1wt.eu
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation, version 2.1
10  * exclusively.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21 
22 #ifndef _TYPES_LISTENER_H
23 #define _TYPES_LISTENER_H
24 
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 
28 #ifdef USE_OPENSSL
29 #include <common/openssl-compat.h>
30 #include <types/ssl_sock.h>
31 #endif
32 
33 #include <common/config.h>
34 #include <common/mini-clist.h>
35 #include <common/hathreads.h>
36 #include <common/standard.h>
37 
38 #include <types/obj_type.h>
39 #include <eb32tree.h>
40 
41 /* Some pointer types reference below */
42 struct task;
43 struct protocol;
44 struct xprt_ops;
45 struct proxy;
46 struct fe_counters;
47 
48 /* listener state */
49 enum li_state {
50 	LI_NEW	= 0,    /* not initialized yet */
51 	LI_INIT,        /* all parameters filled in, but not assigned yet */
52 	LI_ASSIGNED,    /* assigned to the protocol, but not listening yet */
53 	LI_PAUSED,      /* listener was paused, it's bound but not listening  */
54 	LI_ZOMBIE,	/* The listener doesn't belong to the process, but is kept opened */
55 	LI_LISTEN,      /* started, listening but not enabled */
56 	LI_READY,       /* started, listening and enabled */
57 	LI_FULL,        /* reached its connection limit */
58 	LI_LIMITED,     /* transient state: limits have been reached, listener is queued */
59 } __attribute__((packed));
60 
61 /* Listener transitions
62  * calloc()     set()      add_listener()       bind()
63  * -------> NEW ----> INIT ----------> ASSIGNED -----> LISTEN
64  * <-------     <----      <----------          <-----
65  *    free()   bzero()     del_listener()       unbind()
66  *
67  * The file descriptor is valid only during these three states :
68  *
69  *             disable()
70  * LISTEN <------------ READY
71  *   A|   ------------>  |A
72  *   ||  !max & enable() ||
73  *   ||                  ||
74  *   ||              max ||
75  *   || max & enable()   V| !max
76  *   |+---------------> FULL
77  *   +-----------------
78  *            disable()
79  *
80  * The LIMITED state my be used when a limit has been detected just before
81  * using a listener. In this case, the listener MUST be queued into the
82  * appropriate wait queue (either the proxy's or the global one). It may be
83  * set back to the READY state at any instant and for any reason, so one must
84  * not rely on this state.
85  */
86 
87 /* listener socket options */
88 #define LI_O_NONE               0x0000
89 #define LI_O_NOLINGER           0x0001  /* disable linger on this socket */
90 #define LI_O_FOREIGN            0x0002  /* permit listening on foreign addresses ("transparent") */
91 #define LI_O_NOQUICKACK         0x0004  /* disable quick ack of immediate data (linux) */
92 #define LI_O_DEF_ACCEPT         0x0008  /* wait up to 1 second for data before accepting */
93 #define LI_O_TCP_L4_RULES       0x0010  /* run TCP L4 rules checks on the incoming connection */
94 #define LI_O_TCP_L5_RULES       0x0020  /* run TCP L5 rules checks on the incoming session */
95 #define LI_O_CHK_MONNET         0x0040  /* check the source against a monitor-net rule */
96 #define LI_O_ACC_PROXY          0x0080  /* find the proxied address in the first request line */
97 #define LI_O_UNLIMITED          0x0100  /* listener not subject to global limits (peers & stats socket) */
98 #define LI_O_TCP_FO             0x0200  /* enable TCP Fast Open (linux >= 3.7) */
99 #define LI_O_V6ONLY             0x0400  /* bind to IPv6 only on Linux >= 2.4.21 */
100 #define LI_O_V4V6               0x0800  /* bind to IPv4/IPv6 on Linux >= 2.4.21 */
101 #define LI_O_ACC_CIP            0x1000  /* find the proxied address in the NetScaler Client IP header */
102 #define LI_O_INHERITED          0x2000  /* inherited FD from the parent process (fd@) */
103 #define LI_O_MWORKER            0x4000  /* keep the FD open in the master but close it in the children */
104 #define LI_O_NOSTOP             0x8000  /* keep the listener active even after a soft stop */
105 
106 /* Note: if a listener uses LI_O_UNLIMITED, it is highly recommended that it adds its own
107  * maxconn setting to the global.maxsock value so that its resources are reserved.
108  */
109 
110 #ifdef USE_OPENSSL
111 #define BC_SSL_O_NONE           0x0000
112 #define BC_SSL_O_NO_TLS_TICKETS 0x0100	/* disable session resumption tickets */
113 #define BC_SSL_O_PREF_CLIE_CIPH 0x0200  /* prefer client ciphers */
114 #endif
115 
116 /* ssl "bind" settings */
117 struct ssl_bind_conf {
118 #ifdef USE_OPENSSL
119 #ifdef OPENSSL_NPN_NEGOTIATED
120 	char *npn_str;             /* NPN protocol string */
121 	int npn_len;               /* NPN protocol string length */
122 #endif
123 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
124 	char *alpn_str;            /* ALPN protocol string */
125 	int alpn_len;              /* ALPN protocol string length */
126 #endif
127 	int verify:3;              /* verify method (set of SSL_VERIFY_* flags) */
128 	int no_ca_names:1;         /* do not send ca names to clients (ca_file related) */
129 	int early_data:1;          /* early data allowed */
130 	char *ca_file;             /* CAfile to use on verify */
131 	char *crl_file;            /* CRLfile to use on verify */
132 	char *ciphers;             /* cipher suite to use if non-null */
133 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined OPENSSL_IS_BORINGSSL && !defined LIBRESSL_VERSION_NUMBER)
134 	char *ciphersuites;        /* TLS 1.3 cipher suite to use if non-null */
135 #endif
136 	char *curves;	           /* curves suite to use for ECDHE */
137 	char *ecdhe;               /* named curve to use for ECDHE */
138 	struct tls_version_filter ssl_methods; /* ssl methods */
139 #endif
140 };
141 
142 /* "bind" line settings */
143 struct bind_conf {
144 #ifdef USE_OPENSSL
145 	struct ssl_bind_conf ssl_conf; /* ssl conf for ctx setting */
146 	unsigned long long ca_ignerr;  /* ignored verify errors in handshake if depth > 0 */
147 	unsigned long long crt_ignerr; /* ignored verify errors in handshake if depth == 0 */
148 	SSL_CTX *initial_ctx;      /* SSL context for initial negotiation */
149 	SSL_CTX *default_ctx;      /* SSL context of first/default certificate */
150 	struct ssl_bind_conf *default_ssl_conf; /* custom SSL conf of default_ctx */
151 	int strict_sni;            /* refuse negotiation if sni doesn't match a certificate */
152 	int ssl_options;           /* ssl options */
153 	struct eb_root sni_ctx;    /* sni_ctx tree of all known certs full-names sorted by name */
154 	struct eb_root sni_w_ctx;  /* sni_ctx tree of all known certs wildcards sorted by name */
155 	struct tls_keys_ref *keys_ref; /* TLS ticket keys reference */
156 
157 	char *ca_sign_file;        /* CAFile used to generate and sign server certificates */
158 	char *ca_sign_pass;        /* CAKey passphrase */
159 
160 	X509     *ca_sign_cert;    /* CA certificate referenced by ca_file */
161 	EVP_PKEY *ca_sign_pkey;    /* CA private key referenced by ca_key */
162 #endif
163 	struct proxy *frontend;    /* the frontend all these listeners belong to, or NULL */
164 	const struct mux_proto_list *mux_proto; /* the mux to use for all incoming connections (specified by the "proto" keyword) */
165 	struct xprt_ops *xprt;     /* transport-layer operations for all listeners */
166 	int is_ssl;                /* SSL is required for these listeners */
167 	int generate_certs;        /* 1 if generate-certificates option is set, else 0 */
168 	int level;                 /* stats access level (ACCESS_LVL_*) */
169 	int severity_output;       /* default severity output format in cli feedback messages */
170 	struct list listeners;     /* list of listeners using this bind config */
171 	unsigned long bind_proc;   /* bitmask of processes allowed to use these listeners */
172 	unsigned long bind_thread; /* bitmask of threads allowed to use these listeners */
173 	uint32_t ns_cip_magic;     /* Excepted NetScaler Client IP magic number */
174 	struct list by_fe;         /* next binding for the same frontend, or NULL */
175 	char *arg;                 /* argument passed to "bind" for better error reporting */
176 	char *file;                /* file where the section appears */
177 	int line;                  /* line where the section appears */
178 	struct {                   /* UNIX socket permissions */
179 		uid_t uid;         /* -1 to leave unchanged */
180 		gid_t gid;         /* -1 to leave unchanged */
181 		mode_t mode;       /* 0 to leave unchanged */
182 	} ux;
183 };
184 
185 /* The listener will be directly referenced by the fdtab[] which holds its
186  * socket. The listener provides the protocol-specific accept() function to
187  * the fdtab.
188  */
189 struct listener {
190 	enum obj_type obj_type;         /* object type = OBJ_TYPE_LISTENER */
191 	enum li_state state;            /* state: NEW, INIT, ASSIGNED, LISTEN, READY, FULL */
192 	short int nice;                 /* nice value to assign to the instanciated tasks */
193 	int fd;				/* the listen socket */
194 	int luid;			/* listener universally unique ID, used for SNMP */
195 	int options;			/* socket options : LI_O_* */
196 	struct fe_counters *counters;	/* statistics counters */
197 	struct protocol *proto;		/* protocol this listener belongs to */
198 	int nbconn;			/* current number of connections on this listener */
199 	int maxconn;			/* maximum connections allowed on this listener */
200 	unsigned int backlog;		/* if set, listen backlog */
201 	int maxaccept;         /* if set, max number of connections accepted at once (-1 when disabled) */
202 	int (*accept)(struct listener *l, int fd, struct sockaddr_storage *addr); /* upper layer's accept() */
203 	enum obj_type *default_target;  /* default target to use for accepted sessions or NULL */
204 	/* cache line boundary */
205 	struct list wait_queue;		/* link element to make the listener wait for something (LI_LIMITED)  */
206 	unsigned int thr_idx;           /* thread indexes for queue distribution : (t2<<16)+t1 */
207 	unsigned int analysers;		/* bitmap of required protocol analysers */
208 	int maxseg;			/* for TCP, advertised MSS */
209 	int tcp_ut;                     /* for TCP, user timeout */
210 	char *interface;		/* interface name or NULL */
211 	char *name;			/* listener's name */
212 
213 	__decl_hathreads(HA_SPINLOCK_T lock);
214 
215 	const struct netns_entry *netns; /* network namespace of the listener*/
216 
217 	/* cache line boundary */
218 	unsigned int thr_conn[MAX_THREADS]; /* number of connections per thread */
219 
220 	/* cache line boundary */
221 
222 	struct list by_fe;              /* chaining in frontend's list of listeners */
223 	struct list by_bind;            /* chaining in bind_conf's list of listeners */
224 	struct bind_conf *bind_conf;	/* "bind" line settings, include SSL settings among other things */
225 	struct list proto_list;         /* list in the protocol header */
226 
227 	/* warning: this struct is huge, keep it at the bottom */
228 	struct sockaddr_storage addr;	/* the address we listen to */
229 	struct {
230 		struct eb32_node id;	/* place in the tree of used IDs */
231 	} conf;				/* config information */
232 };
233 
234 /* Descriptor for a "bind" keyword. The ->parse() function returns 0 in case of
235  * success, or a combination of ERR_* flags if an error is encountered. The
236  * function pointer can be NULL if not implemented. The function also has an
237  * access to the current "bind" config line. The ->skip value tells the parser
238  * how many words have to be skipped after the keyword.
239  */
240 struct bind_kw {
241 	const char *kw;
242 	int (*parse)(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err);
243 	int skip; /* nb of args to skip */
244 };
245 struct ssl_bind_kw {
246 	const char *kw;
247 	int (*parse)(char **args, int cur_arg, struct proxy *px, struct ssl_bind_conf *conf, char **err);
248 	int skip; /* nb of args to skip */
249 };
250 
251 /*
252  * A keyword list. It is a NULL-terminated array of keywords. It embeds a
253  * struct list in order to be linked to other lists, allowing it to easily
254  * be declared where it is needed, and linked without duplicating data nor
255  * allocating memory. It is also possible to indicate a scope for the keywords.
256  */
257 struct bind_kw_list {
258 	const char *scope;
259 	struct list list;
260 	struct bind_kw kw[VAR_ARRAY];
261 };
262 
263 
264 struct xfer_sock_list {
265 	int fd;
266 	char *iface;
267 	char *namespace;
268 	int options; /* socket options LI_O_* */
269 	struct xfer_sock_list *prev;
270 	struct xfer_sock_list *next;
271 	struct sockaddr_storage addr;
272 };
273 
274 /* This is used to create the accept queue, optimized to be 64 bytes long. */
275 struct accept_queue_entry {
276 	struct listener *listener;          // 8 bytes
277 	int fd __attribute__((aligned(8))); // 4 bytes
278 	int addr_len;                       // 4 bytes
279 
280 	union {
281 		sa_family_t family;         // 2 bytes
282 		struct sockaddr_in in;      // 16 bytes
283 		struct sockaddr_in6 in6;    // 28 bytes
284 	} addr; // this is normally 28 bytes
285 	/* 20-bytes hole here */
286 	char pad0[0] __attribute((aligned(64)));
287 };
288 
289 /* The per-thread accept queue ring, must be a power of two minus 1 */
290 #define ACCEPT_QUEUE_SIZE ((1<<8) - 1)
291 
292 struct accept_queue_ring {
293 	unsigned int head;
294 	unsigned int tail;
295 	struct task *task;  /* task of the thread owning this ring */
296 	struct accept_queue_entry entry[ACCEPT_QUEUE_SIZE] __attribute((aligned(64)));
297 };
298 
299 
300 #endif /* _TYPES_LISTENER_H */
301 
302 /*
303  * Local variables:
304  *  c-indent-level: 8
305  *  c-basic-offset: 8
306  * End:
307  */
308