1 /*
2  * include/types/server.h
3  * This file defines everything related to servers.
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_SERVER_H
23 #define _TYPES_SERVER_H
24 
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
27 
28 #include <common/config.h>
29 #include <common/mini-clist.h>
30 #include <common/hathreads.h>
31 #include <common/openssl-compat.h>
32 
33 #include <eb32tree.h>
34 
35 #include <types/connection.h>
36 #include <types/counters.h>
37 #include <types/dns.h>
38 #include <types/freq_ctr.h>
39 #include <types/obj_type.h>
40 #include <types/proxy.h>
41 #include <types/queue.h>
42 #include <types/ssl_sock.h>
43 #include <types/task.h>
44 #include <types/checks.h>
45 
46 
47 /* server states. Only SRV_ST_STOPPED indicates a down server. */
48 enum srv_state {
49 	SRV_ST_STOPPED = 0,              /* the server is down. Please keep set to zero. */
50 	SRV_ST_STARTING,                 /* the server is warming up (up but throttled) */
51 	SRV_ST_RUNNING,                  /* the server is fully up */
52 	SRV_ST_STOPPING,                 /* the server is up but soft-stopping (eg: 404) */
53 } __attribute__((packed));
54 
55 /* Administrative status : a server runs in one of these 3 stats :
56  *   - READY : normal mode
57  *   - DRAIN : takes no new visitor, equivalent to weight == 0
58  *   - MAINT : maintenance mode, no more traffic nor health checks.
59  *
60  * Each server may be in maintenance by itself or may inherit this status from
61  * another server it tracks. It can also be in drain mode by itself or inherit
62  * it from another server. Let's store these origins here as flags. These flags
63  * are combined this way :
64  *
65  *      FMAINT  IMAINT  FDRAIN  IDRAIN  Resulting state
66  *         0       0       0       0    READY
67  *         0       0       0       1    DRAIN
68  *         0       0       1       x    DRAIN
69  *         0       1       x       x    MAINT
70  *         1       x       x       x    MAINT
71  *
72  * This can be simplified this way :
73  *
74  *   state_str = (state & MAINT) ? "MAINT" : (state & DRAIN) : "DRAIN" : "READY"
75  */
76 enum srv_admin {
77 	SRV_ADMF_FMAINT    = 0x01,        /* the server was explicitly forced into maintenance */
78 	SRV_ADMF_IMAINT    = 0x02,        /* the server has inherited the maintenance status from a tracked server */
79 	SRV_ADMF_MAINT     = 0x23,        /* mask to check if any maintenance flag is present */
80 	SRV_ADMF_CMAINT    = 0x04,        /* the server is in maintenance because of the configuration */
81 	SRV_ADMF_FDRAIN    = 0x08,        /* the server was explicitly forced into drain state */
82 	SRV_ADMF_IDRAIN    = 0x10,        /* the server has inherited the drain status from a tracked server */
83 	SRV_ADMF_DRAIN     = 0x18,        /* mask to check if any drain flag is present */
84 	SRV_ADMF_RMAINT    = 0x20,        /* the server is down because of an IP address resolution failure */
85 	SRV_ADMF_HMAINT    = 0x40,        /* the server FQDN has been set from socket stats */
86 } __attribute__((packed));
87 
88 /* options for servers' "init-addr" parameter
89  * this parameter may be used to drive HAProxy's behavior when parsing a server
90  * address at start up time.
91  * These values are stored as a list into an integer ordered from first to last
92  * starting with the lowest to highest bits. SRV_IADDR_END (0) is used to
93  * indicate the end of the list. 3 bits are enough to store each value.
94  */
95 enum srv_initaddr {
96 	SRV_IADDR_END      = 0,           /* end of the list */
97 	SRV_IADDR_NONE     = 1,           /* the server won't have any address at start up */
98 	SRV_IADDR_LIBC     = 2,           /* address set using the libc DNS resolver */
99 	SRV_IADDR_LAST     = 3,           /* we set the IP address found in state-file for this server */
100 	SRV_IADDR_IP       = 4,           /* we set an arbitrary IP address to the server */
101 } __attribute__((packed));
102 
103 /* server-state-file version */
104 #define SRV_STATE_FILE_VERSION 1
105 #define SRV_STATE_FILE_VERSION_MIN 1
106 #define SRV_STATE_FILE_VERSION_MAX 1
107 #define SRV_STATE_FILE_FIELD_NAMES \
108     "be_id "                      \
109     "be_name "                    \
110     "srv_id "                     \
111     "srv_name "                   \
112     "srv_addr "                   \
113     "srv_op_state "               \
114     "srv_admin_state "            \
115     "srv_uweight "                \
116     "srv_iweight "                \
117     "srv_time_since_last_change " \
118     "srv_check_status "           \
119     "srv_check_result "           \
120     "srv_check_health "           \
121     "srv_check_state "            \
122     "srv_agent_state "            \
123     "bk_f_forced_id "             \
124     "srv_f_forced_id "            \
125     "srv_fqdn "                   \
126     "srv_port "                   \
127     "srvrecord"
128 
129 #define SRV_STATE_FILE_MAX_FIELDS 20
130 #define SRV_STATE_FILE_NB_FIELDS_VERSION_1 20
131 #define SRV_STATE_LINE_MAXLEN 512
132 
133 /* server flags -- 32 bits */
134 #define SRV_F_BACKUP       0x0001        /* this server is a backup server */
135 #define SRV_F_MAPPORTS     0x0002        /* this server uses mapped ports */
136 #define SRV_F_NON_STICK    0x0004        /* never add connections allocated to this server to a stick table */
137 #define SRV_F_USE_NS_FROM_PP 0x0008      /* use namespace associated with connection if present */
138 #define SRV_F_FORCED_ID    0x0010        /* server's ID was forced in the configuration */
139 #define SRV_F_CHECKADDR    0x0020        /* this server has a check addr configured */
140 #define SRV_F_CHECKPORT    0x0040        /* this server has a check port configured */
141 #define SRV_F_AGENTADDR    0x0080        /* this server has a agent addr configured */
142 #define SRV_F_COOKIESET    0x0100        /* this server has a cookie configured, so don't generate dynamic cookies */
143 #define SRV_F_FASTOPEN     0x0200        /* Use TCP Fast Open to connect to server */
144 #define SRV_F_SOCKS4_PROXY 0x0400        /* this server uses SOCKS4 proxy */
145 
146 /* configured server options for send-proxy (server->pp_opts) */
147 #define SRV_PP_V1               0x0001   /* proxy protocol version 1 */
148 #define SRV_PP_V2               0x0002   /* proxy protocol version 2 */
149 #define SRV_PP_V2_SSL           0x0004   /* proxy protocol version 2 with SSL */
150 #define SRV_PP_V2_SSL_CN        0x0008   /* proxy protocol version 2 with CN */
151 #define SRV_PP_V2_SSL_KEY_ALG   0x0010   /* proxy protocol version 2 with cert key algorithm */
152 #define SRV_PP_V2_SSL_SIG_ALG   0x0020   /* proxy protocol version 2 with cert signature algorithm */
153 #define SRV_PP_V2_SSL_CIPHER    0x0040   /* proxy protocol version 2 with cipher used */
154 #define SRV_PP_V2_AUTHORITY     0x0080   /* proxy protocol version 2 with authority */
155 #define SRV_PP_V2_CRC32C        0x0100   /* proxy protocol version 2 with crc32c */
156 
157 /* function which act on servers need to return various errors */
158 #define SRV_STATUS_OK       0   /* everything is OK. */
159 #define SRV_STATUS_INTERNAL 1   /* other unrecoverable errors. */
160 #define SRV_STATUS_NOSRV    2   /* no server is available */
161 #define SRV_STATUS_FULL     3   /* the/all server(s) are saturated */
162 #define SRV_STATUS_QUEUED   4   /* the/all server(s) are saturated but the connection was queued */
163 
164 /* various constants */
165 #define SRV_UWGHT_RANGE 256
166 #define SRV_UWGHT_MAX   (SRV_UWGHT_RANGE)
167 #define SRV_EWGHT_RANGE (SRV_UWGHT_RANGE * BE_WEIGHT_SCALE)
168 #define SRV_EWGHT_MAX   (SRV_UWGHT_MAX   * BE_WEIGHT_SCALE)
169 
170 #ifdef USE_OPENSSL
171 /* server ssl options */
172 #define SRV_SSL_O_NONE         0x0000
173 #define SRV_SSL_O_NO_TLS_TICKETS 0x0100 /* disable session resumption tickets */
174 #define SRV_SSL_O_NO_REUSE     0x200  /* disable session reuse */
175 #define SRV_SSL_O_EARLY_DATA   0x400  /* Allow using early data */
176 #endif
177 
178 /* The server names dictionary */
179 extern struct dict server_name_dict;
180 
181 struct pid_list {
182 	struct list list;
183 	pid_t pid;
184 	struct task *t;
185 	int status;
186 	int exited;
187 };
188 
189 /* A tree occurrence is a descriptor of a place in a tree, with a pointer back
190  * to the server itself.
191  */
192 struct server;
193 struct tree_occ {
194 	struct server *server;
195 	struct eb32_node node;
196 };
197 
198 struct server {
199 	enum obj_type obj_type;                 /* object type == OBJ_TYPE_SERVER */
200 	enum srv_state next_state, cur_state;   /* server state among SRV_ST_* */
201 	enum srv_admin next_admin, cur_admin;   /* server maintenance status : SRV_ADMF_* */
202 	signed char use_ssl;		        /* ssl enabled (1: on, 0: disabled, -1 forced off)  */
203 	unsigned int pp_opts;                   /* proxy protocol options (SRV_PP_*) */
204 	struct server *next;
205 	int cklen;				/* the len of the cookie, to speed up checks */
206 	int rdr_len;				/* the length of the redirection prefix */
207 	char *cookie;				/* the id set in the cookie */
208 	char *rdr_pfx;				/* the redirection prefix */
209 
210 	struct proxy *proxy;			/* the proxy this server belongs to */
211 	const struct mux_proto_list *mux_proto;       /* the mux to use for all outgoing connections (specified by the "proto" keyword) */
212 	int served;				/* # of active sessions currently being served (ie not pending) */
213 	int cur_sess;				/* number of currently active sessions (including syn_sent) */
214 	unsigned maxconn, minconn;		/* max # of active sessions (0 = unlimited), min# for dynamic limit. */
215 	int nbpend;				/* number of pending connections */
216 	unsigned int queue_idx;			/* count of pending connections which have been de-queued */
217 	int maxqueue;				/* maximum number of pending connections allowed */
218 	struct freq_ctr sess_per_sec;		/* sessions per second on this server */
219 	struct be_counters counters;		/* statistics counters */
220 
221 	struct eb_root pendconns;		/* pending connections */
222 	struct list actconns;			/* active connections */
223 	struct list *priv_conns;		/* private idle connections attached to stream interfaces */
224 	struct list *idle_conns;		/* sharable idle connections attached or not to a stream interface */
225 	struct list *safe_conns;		/* safe idle connections attached to stream interfaces, shared */
226 	struct mt_list *idle_orphan_conns;         /* Orphan connections idling */
227 	unsigned int pool_purge_delay;          /* Delay before starting to purge the idle conns pool */
228 	unsigned int max_idle_conns;            /* Max number of connection allowed in the orphan connections list */
229 	unsigned int curr_idle_conns;           /* Current number of orphan idling connections */
230 	unsigned int *curr_idle_thr;            /* Current number of orphan idling connections per thread */
231 	int max_reuse;                          /* Max number of requests on a same connection */
232 	struct eb32_node idle_node;             /* When to next do cleanup in the idle connections */
233 	struct task *warmup;                    /* the task dedicated to the warmup when slowstart is set */
234 
235 	struct conn_src conn_src;               /* connection source settings */
236 
237 	struct server *track;                   /* the server we're currently tracking, if any */
238 	struct server *trackers;                /* the list of servers tracking us, if any */
239 	struct server *tracknext;               /* next server tracking <track> in <track>'s trackers list */
240 	char *trackit;				/* temporary variable to make assignment deferrable */
241 	int consecutive_errors;			/* current number of consecutive errors */
242 	int consecutive_errors_limit;		/* number of consecutive errors that triggers an event */
243 	short observe, onerror;			/* observing mode: one of HANA_OBS_*; what to do on error: on of ANA_ONERR_* */
244 	short onmarkeddown;			/* what to do when marked down: one of HANA_ONMARKEDDOWN_* */
245 	short onmarkedup;			/* what to do when marked up: one of HANA_ONMARKEDUP_* */
246 	unsigned int flags;                     /* server flags (SRV_F_*) */
247 	int slowstart;				/* slowstart time in seconds (ms in the conf) */
248 
249 	char *id;				/* just for identification */
250 	unsigned iweight,uweight, cur_eweight;	/* initial weight, user-specified weight, and effective weight */
251 	unsigned wscore;			/* weight score, used during srv map computation */
252 	unsigned next_eweight;			/* next pending eweight to commit */
253 	unsigned rweight;			/* remainer of weight in the current LB tree */
254 	unsigned cumulative_weight;		/* weight of servers prior to this one in the same group, for chash balancing */
255 	unsigned npos, lpos;			/* next and last positions in the LB tree */
256 	struct eb32_node lb_node;               /* node used for tree-based load balancing */
257 	struct eb_root *lb_tree;                /* we want to know in what tree the server is */
258 	struct server *next_full;               /* next server in the temporary full list */
259 	unsigned lb_nodes_tot;                  /* number of allocated lb_nodes (C-HASH) */
260 	unsigned lb_nodes_now;                  /* number of lb_nodes placed in the tree (C-HASH) */
261 	struct tree_occ *lb_nodes;              /* lb_nodes_tot * struct tree_occ */
262 
263 	const struct netns_entry *netns;        /* contains network namespace name or NULL. Network namespace comes from configuration */
264 	/* warning, these structs are huge, keep them at the bottom */
265 	struct sockaddr_storage addr;           /* the address to connect to, doesn't include the port */
266 	struct xprt_ops *xprt;                  /* transport-layer operations */
267 	unsigned int svc_port;                  /* the port to connect to (for relevant families) */
268 	unsigned down_time;			/* total time the server was down */
269 	time_t last_change;			/* last time, when the state was changed */
270 
271 	int puid;				/* proxy-unique server ID, used for SNMP, and "first" LB algo */
272 	int tcp_ut;                             /* for TCP, user timeout */
273 
274 	int do_check;                           /* temporary variable used during parsing to denote if health checks must be enabled */
275 	int do_agent;                           /* temporary variable used during parsing to denote if an auxiliary agent check must be enabled */
276 	struct check check;                     /* health-check specific configuration */
277 	struct check agent;                     /* agent specific configuration */
278 
279 	struct dns_requester *dns_requester;	/* used to link a server to its DNS resolution */
280 	char *resolvers_id;			/* resolvers section used by this server */
281 	struct dns_resolvers *resolvers;	/* pointer to the resolvers structure used by this server */
282 	char *lastaddr;				/* the address string provided by the server-state file */
283 	struct dns_options dns_opts;
284 	int hostname_dn_len;			/* sting length of the server hostname in Domain Name format */
285 	char *hostname_dn;			/* server hostname in Domain Name format */
286 	char *hostname;				/* server hostname */
287 	struct sockaddr_storage init_addr;	/* plain IP address specified on the init-addr line */
288 	unsigned int init_addr_methods;		/* initial address setting, 3-bit per method, ends at 0, enough to store 10 entries */
289 
290 #ifdef USE_OPENSSL
291 	char *sni_expr;             /* Temporary variable to store a sample expression for SNI */
292 	struct {
293 		SSL_CTX *ctx;
294 		struct {
295 			unsigned char *ptr;
296 			int size;
297 			int allocated_size;
298 		} * reused_sess;
299 		char *ciphers;			/* cipher suite to use if non-null */
300 #if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined OPENSSL_IS_BORINGSSL && !defined LIBRESSL_VERSION_NUMBER)
301 		char *ciphersuites;			/* TLS 1.3 cipher suite to use if non-null */
302 #endif
303 		int options;			/* ssl options */
304 		int verify;			/* verify method (set of SSL_VERIFY_* flags) */
305 		struct tls_version_filter methods;	/* ssl methods */
306 		char *verify_host;              /* hostname of certificate must match this host */
307 		char *ca_file;			/* CAfile to use on verify */
308 		char *crl_file;			/* CRLfile to use on verify */
309 		char *client_crt;		/* client certificate to send */
310 		struct sample_expr *sni;        /* sample expression for SNI */
311 #ifdef OPENSSL_NPN_NEGOTIATED
312 		char *npn_str;                  /* NPN protocol string */
313 		int npn_len;                    /* NPN protocol string length */
314 #endif
315 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
316 		char *alpn_str;                 /* ALPN protocol string */
317 		int alpn_len;                   /* ALPN protocol string length */
318 #endif
319 	} ssl_ctx;
320 #endif
321 	struct dns_srvrq *srvrq;		/* Pointer representing the DNS SRV requeest, if any */
322 	__decl_hathreads(HA_SPINLOCK_T lock);   /* may enclose the proxy's lock, must not be taken under */
323 	struct {
324 		const char *file;		/* file where the section appears */
325 		struct eb32_node id;		/* place in the tree of used IDs */
326 		struct ebpt_node name;		/* place in the tree of used names */
327 		int line;			/* line where the section appears */
328 	} conf;					/* config information */
329 	/* Template information used only for server objects which
330 	 * serve as template filled at parsing time and used during
331 	 * server allocations from server templates.
332 	 */
333 	struct {
334 		char *prefix;
335 		int nb_low;
336 		int nb_high;
337 	} tmpl_info;
338 	struct {
339 		long duration;
340 		short status, code;
341 		char reason[128];
342 	} op_st_chg;				/* operational status change's reason */
343 	char adm_st_chg_cause[48];		/* administrative status change's cause */
344 
345 	struct sockaddr_storage socks4_addr;	/* the address of the SOCKS4 Proxy, including the port */
346 };
347 
348 
349 /* Storage structure to load server-state lines from a flat file into
350  * an ebtree, for faster processing
351  */
352 struct state_line {
353 	char *line;
354 	struct ebmb_node name_name;
355 	/* WARNING don't put anything after name_name, it's used by the key */
356 };
357 
358 
359 /* Descriptor for a "server" keyword. The ->parse() function returns 0 in case of
360  * success, or a combination of ERR_* flags if an error is encountered. The
361  * function pointer can be NULL if not implemented. The function also has an
362  * access to the current "server" config line. The ->skip value tells the parser
363  * how many words have to be skipped after the keyword. If the function needs to
364  * parse more keywords, it needs to update cur_arg.
365  */
366 struct srv_kw {
367 	const char *kw;
368 	int (*parse)(char **args, int *cur_arg, struct proxy *px, struct server *srv, char **err);
369 	int skip; /* nb min of args to skip, for use when kw is not handled */
370 	int default_ok; /* non-zero if kw is supported in default-server section */
371 };
372 
373 /*
374  * A keyword list. It is a NULL-terminated array of keywords. It embeds a
375  * struct list in order to be linked to other lists, allowing it to easily
376  * be declared where it is needed, and linked without duplicating data nor
377  * allocating memory. It is also possible to indicate a scope for the keywords.
378  */
379 struct srv_kw_list {
380 	const char *scope;
381 	struct list list;
382 	struct srv_kw kw[VAR_ARRAY];
383 };
384 
385 #endif /* _TYPES_SERVER_H */
386 
387 /*
388  * Local variables:
389  *  c-indent-level: 8
390  *  c-basic-offset: 8
391  * End:
392  */
393