1 /*
2  * Proxy variables and functions.
3  *
4  * Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  *
11  */
12 
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <string.h>
16 #include <sys/types.h>
17 #include <sys/socket.h>
18 #include <sys/stat.h>
19 
20 #include <common/defaults.h>
21 #include <common/cfgparse.h>
22 #include <common/compat.h>
23 #include <common/config.h>
24 #include <common/errors.h>
25 #include <common/memory.h>
26 #include <common/time.h>
27 
28 #include <eb32tree.h>
29 #include <ebistree.h>
30 
31 #include <types/capture.h>
32 #include <types/cli.h>
33 #include <types/global.h>
34 #include <types/obj_type.h>
35 #include <types/peers.h>
36 #include <types/stats.h>
37 
38 #include <proto/applet.h>
39 #include <proto/cli.h>
40 #include <proto/backend.h>
41 #include <proto/fd.h>
42 #include <proto/filters.h>
43 #include <proto/hdr_idx.h>
44 #include <proto/listener.h>
45 #include <proto/log.h>
46 #include <proto/proto_tcp.h>
47 #include <proto/proto_http.h>
48 #include <proto/proxy.h>
49 #include <proto/signal.h>
50 #include <proto/stream.h>
51 #include <proto/stream_interface.h>
52 #include <proto/task.h>
53 
54 
55 int listeners;	/* # of proxy listeners, set by cfgparse */
56 struct proxy *proxy  = NULL;	/* list of all existing proxies */
57 struct eb_root used_proxy_id = EB_ROOT;	/* list of proxy IDs in use */
58 struct eb_root proxy_by_name = EB_ROOT; /* tree of proxies sorted by name */
59 unsigned int error_snapshot_id = 0;     /* global ID assigned to each error then incremented */
60 
61 /*
62  * This function returns a string containing a name describing capabilities to
63  * report comprehensible error messages. Specifically, it will return the words
64  * "frontend", "backend" when appropriate, or "proxy" for all other
65  * cases including the proxies declared in "listen" mode.
66  */
proxy_cap_str(int cap)67 const char *proxy_cap_str(int cap)
68 {
69 	if ((cap & PR_CAP_LISTEN) != PR_CAP_LISTEN) {
70 		if (cap & PR_CAP_FE)
71 			return "frontend";
72 		else if (cap & PR_CAP_BE)
73 			return "backend";
74 	}
75 	return "proxy";
76 }
77 
78 /*
79  * This function returns a string containing the mode of the proxy in a format
80  * suitable for error messages.
81  */
proxy_mode_str(int mode)82 const char *proxy_mode_str(int mode) {
83 
84 	if (mode == PR_MODE_TCP)
85 		return "tcp";
86 	else if (mode == PR_MODE_HTTP)
87 		return "http";
88 	else if (mode == PR_MODE_HEALTH)
89 		return "health";
90 	else
91 		return "unknown";
92 }
93 
94 /*
95  * This function scans the list of backends and servers to retrieve the first
96  * backend and the first server with the given names, and sets them in both
97  * parameters. It returns zero if either is not found, or non-zero and sets
98  * the ones it did not found to NULL. If a NULL pointer is passed for the
99  * backend, only the pointer to the server will be updated.
100  */
get_backend_server(const char * bk_name,const char * sv_name,struct proxy ** bk,struct server ** sv)101 int get_backend_server(const char *bk_name, const char *sv_name,
102 		       struct proxy **bk, struct server **sv)
103 {
104 	struct proxy *p;
105 	struct server *s;
106 	int sid;
107 
108 	*sv = NULL;
109 
110 	sid = -1;
111 	if (*sv_name == '#')
112 		sid = atoi(sv_name + 1);
113 
114 	p = proxy_be_by_name(bk_name);
115 	if (bk)
116 		*bk = p;
117 	if (!p)
118 		return 0;
119 
120 	for (s = p->srv; s; s = s->next)
121 		if ((sid >= 0 && s->puid == sid) ||
122 		    (sid < 0 && strcmp(s->id, sv_name) == 0))
123 			break;
124 	*sv = s;
125 	if (!s)
126 		return 0;
127 	return 1;
128 }
129 
130 /* This function parses a "timeout" statement in a proxy section. It returns
131  * -1 if there is any error, 1 for a warning, otherwise zero. If it does not
132  * return zero, it will write an error or warning message into a preallocated
133  * buffer returned at <err>. The trailing is not be written. The function must
134  * be called with <args> pointing to the first command line word, with <proxy>
135  * pointing to the proxy being parsed, and <defpx> to the default proxy or NULL.
136  * As a special case for compatibility with older configs, it also accepts
137  * "{cli|srv|con}timeout" in args[0].
138  */
proxy_parse_timeout(char ** args,int section,struct proxy * proxy,struct proxy * defpx,const char * file,int line,char ** err)139 static int proxy_parse_timeout(char **args, int section, struct proxy *proxy,
140                                struct proxy *defpx, const char *file, int line,
141                                char **err)
142 {
143 	unsigned timeout;
144 	int retval, cap;
145 	const char *res, *name;
146 	int *tv = NULL;
147 	int *td = NULL;
148 	int warn = 0;
149 
150 	retval = 0;
151 
152 	/* simply skip "timeout" but remain compatible with old form */
153 	if (strcmp(args[0], "timeout") == 0)
154 		args++;
155 
156 	name = args[0];
157 	if (!strcmp(args[0], "client") || (!strcmp(args[0], "clitimeout") && (warn = WARN_CLITO_DEPRECATED))) {
158 		name = "client";
159 		tv = &proxy->timeout.client;
160 		td = &defpx->timeout.client;
161 		cap = PR_CAP_FE;
162 	} else if (!strcmp(args[0], "tarpit")) {
163 		tv = &proxy->timeout.tarpit;
164 		td = &defpx->timeout.tarpit;
165 		cap = PR_CAP_FE | PR_CAP_BE;
166 	} else if (!strcmp(args[0], "http-keep-alive")) {
167 		tv = &proxy->timeout.httpka;
168 		td = &defpx->timeout.httpka;
169 		cap = PR_CAP_FE | PR_CAP_BE;
170 	} else if (!strcmp(args[0], "http-request")) {
171 		tv = &proxy->timeout.httpreq;
172 		td = &defpx->timeout.httpreq;
173 		cap = PR_CAP_FE | PR_CAP_BE;
174 	} else if (!strcmp(args[0], "server") || (!strcmp(args[0], "srvtimeout") && (warn = WARN_SRVTO_DEPRECATED))) {
175 		name = "server";
176 		tv = &proxy->timeout.server;
177 		td = &defpx->timeout.server;
178 		cap = PR_CAP_BE;
179 	} else if (!strcmp(args[0], "connect") || (!strcmp(args[0], "contimeout") && (warn = WARN_CONTO_DEPRECATED))) {
180 		name = "connect";
181 		tv = &proxy->timeout.connect;
182 		td = &defpx->timeout.connect;
183 		cap = PR_CAP_BE;
184 	} else if (!strcmp(args[0], "check")) {
185 		tv = &proxy->timeout.check;
186 		td = &defpx->timeout.check;
187 		cap = PR_CAP_BE;
188 	} else if (!strcmp(args[0], "queue")) {
189 		tv = &proxy->timeout.queue;
190 		td = &defpx->timeout.queue;
191 		cap = PR_CAP_BE;
192 	} else if (!strcmp(args[0], "tunnel")) {
193 		tv = &proxy->timeout.tunnel;
194 		td = &defpx->timeout.tunnel;
195 		cap = PR_CAP_BE;
196 	} else if (!strcmp(args[0], "client-fin")) {
197 		tv = &proxy->timeout.clientfin;
198 		td = &defpx->timeout.clientfin;
199 		cap = PR_CAP_FE;
200 	} else if (!strcmp(args[0], "server-fin")) {
201 		tv = &proxy->timeout.serverfin;
202 		td = &defpx->timeout.serverfin;
203 		cap = PR_CAP_BE;
204 	} else {
205 		memprintf(err,
206 		          "'timeout' supports 'client', 'server', 'connect', 'check', "
207 		          "'queue', 'http-keep-alive', 'http-request', 'tunnel', 'tarpit', "
208 			  "'client-fin' and 'server-fin' (got '%s')",
209 		          args[0]);
210 		return -1;
211 	}
212 
213 	if (*args[1] == 0) {
214 		memprintf(err, "'timeout %s' expects an integer value (in milliseconds)", name);
215 		return -1;
216 	}
217 
218 	res = parse_time_err(args[1], &timeout, TIME_UNIT_MS);
219 	if (res) {
220 		memprintf(err, "unexpected character '%c' in 'timeout %s'", *res, name);
221 		return -1;
222 	}
223 
224 	if (!(proxy->cap & cap)) {
225 		memprintf(err, "'timeout %s' will be ignored because %s '%s' has no %s capability",
226 		          name, proxy_type_str(proxy), proxy->id,
227 		          (cap & PR_CAP_BE) ? "backend" : "frontend");
228 		retval = 1;
229 	}
230 	else if (defpx && *tv != *td) {
231 		memprintf(err, "overwriting 'timeout %s' which was already specified", name);
232 		retval = 1;
233 	}
234 	else if (warn) {
235 		if (!already_warned(warn)) {
236 			memprintf(err, "the '%s' directive is now deprecated in favor of 'timeout %s', and will not be supported in future versions.",
237 				  args[0], name);
238 			retval = 1;
239 		}
240 	}
241 
242 	if (*args[2] != 0) {
243 		memprintf(err, "'timeout %s' : unexpected extra argument '%s' after value '%s'.", name, args[2], args[1]);
244 		retval = -1;
245 	}
246 
247 	*tv = MS_TO_TICKS(timeout);
248 	return retval;
249 }
250 
251 /* This function parses a "rate-limit" statement in a proxy section. It returns
252  * -1 if there is any error, 1 for a warning, otherwise zero. If it does not
253  * return zero, it will write an error or warning message into a preallocated
254  * buffer returned at <err>. The function must be called with <args> pointing
255  * to the first command line word, with <proxy> pointing to the proxy being
256  * parsed, and <defpx> to the default proxy or NULL.
257  */
proxy_parse_rate_limit(char ** args,int section,struct proxy * proxy,struct proxy * defpx,const char * file,int line,char ** err)258 static int proxy_parse_rate_limit(char **args, int section, struct proxy *proxy,
259                                   struct proxy *defpx, const char *file, int line,
260                                   char **err)
261 {
262 	int retval, cap;
263 	char *res;
264 	unsigned int *tv = NULL;
265 	unsigned int *td = NULL;
266 	unsigned int val;
267 
268 	retval = 0;
269 
270 	if (strcmp(args[1], "sessions") == 0) {
271 		tv = &proxy->fe_sps_lim;
272 		td = &defpx->fe_sps_lim;
273 		cap = PR_CAP_FE;
274 	}
275 	else {
276 		memprintf(err, "'%s' only supports 'sessions' (got '%s')", args[0], args[1]);
277 		return -1;
278 	}
279 
280 	if (*args[2] == 0) {
281 		memprintf(err, "'%s %s' expects expects an integer value (in sessions/second)", args[0], args[1]);
282 		return -1;
283 	}
284 
285 	val = strtoul(args[2], &res, 0);
286 	if (*res) {
287 		memprintf(err, "'%s %s' : unexpected character '%c' in integer value '%s'", args[0], args[1], *res, args[2]);
288 		return -1;
289 	}
290 
291 	if (!(proxy->cap & cap)) {
292 		memprintf(err, "%s %s will be ignored because %s '%s' has no %s capability",
293 			 args[0], args[1], proxy_type_str(proxy), proxy->id,
294 			 (cap & PR_CAP_BE) ? "backend" : "frontend");
295 		retval = 1;
296 	}
297 	else if (defpx && *tv != *td) {
298 		memprintf(err, "overwriting %s %s which was already specified", args[0], args[1]);
299 		retval = 1;
300 	}
301 
302 	*tv = val;
303 	return retval;
304 }
305 
306 /* This function parses a "max-keep-alive-queue" statement in a proxy section.
307  * It returns -1 if there is any error, 1 for a warning, otherwise zero. If it
308  * does not return zero, it will write an error or warning message into a
309  * preallocated buffer returned at <err>. The function must be called with
310  * <args> pointing to the first command line word, with <proxy> pointing to
311  * the proxy being parsed, and <defpx> to the default proxy or NULL.
312  */
proxy_parse_max_ka_queue(char ** args,int section,struct proxy * proxy,struct proxy * defpx,const char * file,int line,char ** err)313 static int proxy_parse_max_ka_queue(char **args, int section, struct proxy *proxy,
314                                     struct proxy *defpx, const char *file, int line,
315                                     char **err)
316 {
317 	int retval;
318 	char *res;
319 	unsigned int val;
320 
321 	retval = 0;
322 
323 	if (*args[1] == 0) {
324 		memprintf(err, "'%s' expects expects an integer value (or -1 to disable)", args[0]);
325 		return -1;
326 	}
327 
328 	val = strtol(args[1], &res, 0);
329 	if (*res) {
330 		memprintf(err, "'%s' : unexpected character '%c' in integer value '%s'", args[0], *res, args[1]);
331 		return -1;
332 	}
333 
334 	if (!(proxy->cap & PR_CAP_BE)) {
335 		memprintf(err, "%s will be ignored because %s '%s' has no backend capability",
336 		          args[0], proxy_type_str(proxy), proxy->id);
337 		retval = 1;
338 	}
339 
340 	/* we store <val+1> so that a user-facing value of -1 is stored as zero (default) */
341 	proxy->max_ka_queue = val + 1;
342 	return retval;
343 }
344 
345 /* This function parses a "declare" statement in a proxy section. It returns -1
346  * if there is any error, 1 for warning, otherwise 0. If it does not return zero,
347  * it will write an error or warning message into a preallocated buffer returned
348  * at <err>. The function must be called with <args> pointing to the first command
349  * line word, with <proxy> pointing to the proxy being parsed, and <defpx> to the
350  * default proxy or NULL.
351  */
proxy_parse_declare(char ** args,int section,struct proxy * curpx,struct proxy * defpx,const char * file,int line,char ** err)352 static int proxy_parse_declare(char **args, int section, struct proxy *curpx,
353                                struct proxy *defpx, const char *file, int line,
354                                char **err)
355 {
356 	/* Capture keyword wannot be declared in a default proxy. */
357 	if (curpx == defpx) {
358 		memprintf(err, "'%s' not avalaible in default section", args[0]);
359 		return -1;
360 	}
361 
362 	/* Capture keywork is only avalaible in frontend. */
363 	if (!(curpx->cap & PR_CAP_FE)) {
364 		memprintf(err, "'%s' only avalaible in frontend or listen section", args[0]);
365 		return -1;
366 	}
367 
368 	/* Check mandatory second keyword. */
369 	if (!args[1] || !*args[1]) {
370 		memprintf(err, "'%s' needs a second keyword that specify the type of declaration ('capture')", args[0]);
371 		return -1;
372 	}
373 
374 	/* Actually, declare is only avalaible for declaring capture
375 	 * slot, but in the future it can declare maps or variables.
376 	 * So, this section permits to check and switch acording with
377 	 * the second keyword.
378 	 */
379 	if (strcmp(args[1], "capture") == 0) {
380 		char *error = NULL;
381 		long len;
382 		struct cap_hdr *hdr;
383 
384 		/* Check the next keyword. */
385 		if (!args[2] || !*args[2] ||
386 		    (strcmp(args[2], "response") != 0 &&
387 		     strcmp(args[2], "request") != 0)) {
388 			memprintf(err, "'%s %s' requires a direction ('request' or 'response')", args[0], args[1]);
389 			return -1;
390 		}
391 
392 		/* Check the 'len' keyword. */
393 		if (!args[3] || !*args[3] || strcmp(args[3], "len") != 0) {
394 			memprintf(err, "'%s %s' requires a capture length ('len')", args[0], args[1]);
395 			return -1;
396 		}
397 
398 		/* Check the length value. */
399 		if (!args[4] || !*args[4]) {
400 			memprintf(err, "'%s %s': 'len' requires a numeric value that represents the "
401 			               "capture length",
402 			          args[0], args[1]);
403 			return -1;
404 		}
405 
406 		/* convert the length value. */
407 		len = strtol(args[4], &error, 10);
408 		if (*error != '\0') {
409 			memprintf(err, "'%s %s': cannot parse the length '%s'.",
410 			          args[0], args[1], args[3]);
411 			return -1;
412 		}
413 
414 		/* check length. */
415 		if (len <= 0) {
416 			memprintf(err, "length must be > 0");
417 			return -1;
418 		}
419 
420 		/* register the capture. */
421 		hdr = calloc(1, sizeof(*hdr));
422 		hdr->name = NULL; /* not a header capture */
423 		hdr->namelen = 0;
424 		hdr->len = len;
425 		hdr->pool = create_pool("caphdr", hdr->len + 1, MEM_F_SHARED);
426 
427 		if (strcmp(args[2], "request") == 0) {
428 			hdr->next = curpx->req_cap;
429 			hdr->index = curpx->nb_req_cap++;
430 			curpx->req_cap = hdr;
431 		}
432 		if (strcmp(args[2], "response") == 0) {
433 			hdr->next = curpx->rsp_cap;
434 			hdr->index = curpx->nb_rsp_cap++;
435 			curpx->rsp_cap = hdr;
436 		}
437 		return 0;
438 	}
439 	else {
440 		memprintf(err, "unknown declaration type '%s' (supports 'capture')", args[1]);
441 		return -1;
442 	}
443 }
444 
445 /* This function inserts proxy <px> into the tree of known proxies. The proxy's
446  * name is used as the storing key so it must already have been initialized.
447  */
proxy_store_name(struct proxy * px)448 void proxy_store_name(struct proxy *px)
449 {
450 	px->conf.by_name.key = px->id;
451 	ebis_insert(&proxy_by_name, &px->conf.by_name);
452 }
453 
454 /* Returns a pointer to the first proxy matching capabilities <cap> and id
455  * <id>. NULL is returned if no match is found. If <table> is non-zero, it
456  * only considers proxies having a table.
457  */
proxy_find_by_id(int id,int cap,int table)458 struct proxy *proxy_find_by_id(int id, int cap, int table)
459 {
460 	struct eb32_node *n;
461 
462 	for (n = eb32_lookup(&used_proxy_id, id); n; n = eb32_next(n)) {
463 		struct proxy *px = container_of(n, struct proxy, conf.id);
464 
465 		if (px->uuid != id)
466 			break;
467 
468 		if ((px->cap & cap) != cap)
469 			continue;
470 
471 		if (table && !px->table.size)
472 			continue;
473 
474 		return px;
475 	}
476 	return NULL;
477 }
478 
479 /* Returns a pointer to the first proxy matching either name <name>, or id
480  * <name> if <name> begins with a '#'. NULL is returned if no match is found.
481  * If <table> is non-zero, it only considers proxies having a table.
482  */
proxy_find_by_name(const char * name,int cap,int table)483 struct proxy *proxy_find_by_name(const char *name, int cap, int table)
484 {
485 	struct proxy *curproxy;
486 
487 	if (*name == '#') {
488 		curproxy = proxy_find_by_id(atoi(name + 1), cap, table);
489 		if (curproxy)
490 			return curproxy;
491 	}
492 	else {
493 		struct ebpt_node *node;
494 
495 		for (node = ebis_lookup(&proxy_by_name, name); node; node = ebpt_next(node)) {
496 			curproxy = container_of(node, struct proxy, conf.by_name);
497 
498 			if (strcmp(curproxy->id, name) != 0)
499 				break;
500 
501 			if ((curproxy->cap & cap) != cap)
502 				continue;
503 
504 			if (table && !curproxy->table.size)
505 				continue;
506 
507 			return curproxy;
508 		}
509 	}
510 	return NULL;
511 }
512 
513 /* Finds the best match for a proxy with capabilities <cap>, name <name> and id
514  * <id>. At most one of <id> or <name> may be different provided that <cap> is
515  * valid. Either <id> or <name> may be left unspecified (0). The purpose is to
516  * find a proxy based on some information from a previous configuration, across
517  * reloads or during information exchange between peers.
518  *
519  * Names are looked up first if present, then IDs are compared if present. In
520  * case of an inexact match whatever is forced in the configuration has
521  * precedence in the following order :
522  *   - 1) forced ID (proves a renaming / change of proxy type)
523  *   - 2) proxy name+type (may indicate a move if ID differs)
524  *   - 3) automatic ID+type (may indicate a renaming)
525  *
526  * Depending on what is found, we can end up in the following situations :
527  *
528  *   name id cap  | possible causes
529  *   -------------+-----------------
530  *    --  --  --  | nothing found
531  *    --  --  ok  | nothing found
532  *    --  ok  --  | proxy deleted, ID points to next one
533  *    --  ok  ok  | proxy renamed, or deleted with ID pointing to next one
534  *    ok  --  --  | proxy deleted, but other half with same name still here (before)
535  *    ok  --  ok  | proxy's ID changed (proxy moved in the config file)
536  *    ok  ok  --  | proxy deleted, but other half with same name still here (after)
537  *    ok  ok  ok  | perfect match
538  *
539  * Upon return if <diff> is not NULL, it is zeroed then filled with up to 3 bits :
540  *   - PR_FBM_MISMATCH_ID        : proxy was found but ID differs
541  *                                 (and ID was not zero)
542  *   - PR_FBM_MISMATCH_NAME      : proxy was found by ID but name differs
543  *                                 (and name was not NULL)
544  *   - PR_FBM_MISMATCH_PROXYTYPE : a proxy of different type was found with
545  *                                 the same name and/or id
546  *
547  * Only a valid proxy is returned. If capabilities do not match, NULL is
548  * returned. The caller can check <diff> to report detailed warnings / errors,
549  * and decide whether or not to use what was found.
550  */
proxy_find_best_match(int cap,const char * name,int id,int * diff)551 struct proxy *proxy_find_best_match(int cap, const char *name, int id, int *diff)
552 {
553 	struct proxy *byname;
554 	struct proxy *byid;
555 
556 	if (!name && !id)
557 		return NULL;
558 
559 	if (diff)
560 		*diff = 0;
561 
562 	byname = byid = NULL;
563 
564 	if (name) {
565 		byname = proxy_find_by_name(name, cap, 0);
566 		if (byname && (!id || byname->uuid == id))
567 			return byname;
568 	}
569 
570 	/* remaining possiblities :
571 	 *   - name not set
572 	 *   - name set but not found
573 	 *   - name found, but ID doesn't match.
574 	 */
575 	if (id) {
576 		byid = proxy_find_by_id(id, cap, 0);
577 		if (byid) {
578 			if (byname) {
579 				/* id+type found, name+type found, but not all 3.
580 				 * ID wins only if forced, otherwise name wins.
581 				 */
582 				if (byid->options & PR_O_FORCED_ID) {
583 					if (diff)
584 						*diff |= PR_FBM_MISMATCH_NAME;
585 					return byid;
586 				}
587 				else {
588 					if (diff)
589 						*diff |= PR_FBM_MISMATCH_ID;
590 					return byname;
591 				}
592 			}
593 
594 			/* remaining possiblities :
595 			 *   - name not set
596 			 *   - name set but not found
597 			 */
598 			if (name && diff)
599 				*diff |= PR_FBM_MISMATCH_NAME;
600 			return byid;
601 		}
602 
603 		/* ID not found */
604 		if (byname) {
605 			if (diff)
606 				*diff |= PR_FBM_MISMATCH_ID;
607 			return byname;
608 		}
609 	}
610 
611 	/* All remaining possiblities will lead to NULL. If we can report more
612 	 * detailed information to the caller about changed types and/or name,
613 	 * we'll do it. For example, we could detect that "listen foo" was
614 	 * split into "frontend foo_ft" and "backend foo_bk" if IDs are forced.
615 	 *   - name not set, ID not found
616 	 *   - name not found, ID not set
617 	 *   - name not found, ID not found
618 	 */
619 	if (!diff)
620 		return NULL;
621 
622 	if (name) {
623 		byname = proxy_find_by_name(name, 0, 0);
624 		if (byname && (!id || byname->uuid == id))
625 			*diff |= PR_FBM_MISMATCH_PROXYTYPE;
626 	}
627 
628 	if (id) {
629 		byid = proxy_find_by_id(id, 0, 0);
630 		if (byid) {
631 			if (!name)
632 				*diff |= PR_FBM_MISMATCH_PROXYTYPE; /* only type changed */
633 			else if (byid->options & PR_O_FORCED_ID)
634 				*diff |= PR_FBM_MISMATCH_NAME | PR_FBM_MISMATCH_PROXYTYPE; /* name and type changed */
635 			/* otherwise it's a different proxy that was returned */
636 		}
637 	}
638 	return NULL;
639 }
640 
641 /*
642  * This function finds a server with matching name within selected proxy.
643  * It also checks if there are more matching servers with
644  * requested name as this often leads into unexpected situations.
645  */
646 
findserver(const struct proxy * px,const char * name)647 struct server *findserver(const struct proxy *px, const char *name) {
648 
649 	struct server *cursrv, *target = NULL;
650 
651 	if (!px)
652 		return NULL;
653 
654 	for (cursrv = px->srv; cursrv; cursrv = cursrv->next) {
655 		if (strcmp(cursrv->id, name))
656 			continue;
657 
658 		if (!target) {
659 			target = cursrv;
660 			continue;
661 		}
662 
663 		Alert("Refusing to use duplicated server '%s' found in proxy: %s!\n",
664 			name, px->id);
665 
666 		return NULL;
667 	}
668 
669 	return target;
670 }
671 
672 /* This function checks that the designated proxy has no http directives
673  * enabled. It will output a warning if there are, and will fix some of them.
674  * It returns the number of fatal errors encountered. This should be called
675  * at the end of the configuration parsing if the proxy is not in http mode.
676  * The <file> argument is used to construct the error message.
677  */
proxy_cfg_ensure_no_http(struct proxy * curproxy)678 int proxy_cfg_ensure_no_http(struct proxy *curproxy)
679 {
680 	if (curproxy->cookie_name != NULL) {
681 		Warning("config : cookie will be ignored for %s '%s' (needs 'mode http').\n",
682 			proxy_type_str(curproxy), curproxy->id);
683 	}
684 	if (curproxy->rsp_exp != NULL) {
685 		Warning("config : server regular expressions will be ignored for %s '%s' (needs 'mode http').\n",
686 			proxy_type_str(curproxy), curproxy->id);
687 	}
688 	if (curproxy->req_exp != NULL) {
689 		Warning("config : client regular expressions will be ignored for %s '%s' (needs 'mode http').\n",
690 			proxy_type_str(curproxy), curproxy->id);
691 	}
692 	if (curproxy->monitor_uri != NULL) {
693 		Warning("config : monitor-uri will be ignored for %s '%s' (needs 'mode http').\n",
694 			proxy_type_str(curproxy), curproxy->id);
695 	}
696 	if (curproxy->lbprm.algo & BE_LB_NEED_HTTP) {
697 		curproxy->lbprm.algo &= ~BE_LB_ALGO;
698 		curproxy->lbprm.algo |= BE_LB_ALGO_RR;
699 		Warning("config : Layer 7 hash not possible for %s '%s' (needs 'mode http'). Falling back to round robin.\n",
700 			proxy_type_str(curproxy), curproxy->id);
701 	}
702 	if (curproxy->to_log & (LW_REQ | LW_RESP)) {
703 		curproxy->to_log &= ~(LW_REQ | LW_RESP);
704 		Warning("parsing [%s:%d] : HTTP log/header format not usable with %s '%s' (needs 'mode http').\n",
705 			curproxy->conf.lfs_file, curproxy->conf.lfs_line,
706 			proxy_type_str(curproxy), curproxy->id);
707 	}
708 	if (curproxy->conf.logformat_string == default_http_log_format ||
709 	    curproxy->conf.logformat_string == clf_http_log_format) {
710 		/* Note: we don't change the directive's file:line number */
711 		curproxy->conf.logformat_string = default_tcp_log_format;
712 		Warning("parsing [%s:%d] : 'option httplog' not usable with %s '%s' (needs 'mode http'). Falling back to 'option tcplog'.\n",
713 			curproxy->conf.lfs_file, curproxy->conf.lfs_line,
714 			proxy_type_str(curproxy), curproxy->id);
715 	}
716 
717 	return 0;
718 }
719 
720 /* Perform the most basic initialization of a proxy :
721  * memset(), list_init(*), reset_timeouts(*).
722  * Any new proxy or peer should be initialized via this function.
723  */
init_new_proxy(struct proxy * p)724 void init_new_proxy(struct proxy *p)
725 {
726 	memset(p, 0, sizeof(struct proxy));
727 	p->obj_type = OBJ_TYPE_PROXY;
728 	LIST_INIT(&p->pendconns);
729 	LIST_INIT(&p->acl);
730 	LIST_INIT(&p->http_req_rules);
731 	LIST_INIT(&p->http_res_rules);
732 	LIST_INIT(&p->block_rules);
733 	LIST_INIT(&p->redirect_rules);
734 	LIST_INIT(&p->mon_fail_cond);
735 	LIST_INIT(&p->switching_rules);
736 	LIST_INIT(&p->server_rules);
737 	LIST_INIT(&p->persist_rules);
738 	LIST_INIT(&p->sticking_rules);
739 	LIST_INIT(&p->storersp_rules);
740 	LIST_INIT(&p->tcp_req.inspect_rules);
741 	LIST_INIT(&p->tcp_rep.inspect_rules);
742 	LIST_INIT(&p->tcp_req.l4_rules);
743 	LIST_INIT(&p->tcp_req.l5_rules);
744 	LIST_INIT(&p->req_add);
745 	LIST_INIT(&p->rsp_add);
746 	LIST_INIT(&p->listener_queue);
747 	LIST_INIT(&p->logsrvs);
748 	LIST_INIT(&p->logformat);
749 	LIST_INIT(&p->logformat_sd);
750 	LIST_INIT(&p->format_unique_id);
751 	LIST_INIT(&p->conf.bind);
752 	LIST_INIT(&p->conf.listeners);
753 	LIST_INIT(&p->conf.args.list);
754 	LIST_INIT(&p->tcpcheck_rules);
755 	LIST_INIT(&p->filter_configs);
756 
757 	/* Timeouts are defined as -1 */
758 	proxy_reset_timeouts(p);
759 	p->tcp_rep.inspect_delay = TICK_ETERNITY;
760 
761 	/* initial uuid is unassigned (-1) */
762 	p->uuid = -1;
763 }
764 
765 /*
766  * This function creates all proxy sockets. It should be done very early,
767  * typically before privileges are dropped. The sockets will be registered
768  * but not added to any fd_set, in order not to loose them across the fork().
769  * The proxies also start in READY state because they all have their listeners
770  * bound.
771  *
772  * Its return value is composed from ERR_NONE, ERR_RETRYABLE and ERR_FATAL.
773  * Retryable errors will only be printed if <verbose> is not zero.
774  */
start_proxies(int verbose)775 int start_proxies(int verbose)
776 {
777 	struct proxy *curproxy;
778 	struct listener *listener;
779 	int lerr, err = ERR_NONE;
780 	int pxerr;
781 	char msg[100];
782 
783 	for (curproxy = proxy; curproxy != NULL; curproxy = curproxy->next) {
784 		if (curproxy->state != PR_STNEW)
785 			continue; /* already initialized */
786 
787 		pxerr = 0;
788 		list_for_each_entry(listener, &curproxy->conf.listeners, by_fe) {
789 			if (listener->state != LI_ASSIGNED)
790 				continue; /* already started */
791 
792 			lerr = listener->proto->bind(listener, msg, sizeof(msg));
793 
794 			/* errors are reported if <verbose> is set or if they are fatal */
795 			if (verbose || (lerr & (ERR_FATAL | ERR_ABORT))) {
796 				if (lerr & ERR_ALERT)
797 					Alert("Starting %s %s: %s\n",
798 					      proxy_type_str(curproxy), curproxy->id, msg);
799 				else if (lerr & ERR_WARN)
800 					Warning("Starting %s %s: %s\n",
801 						proxy_type_str(curproxy), curproxy->id, msg);
802 			}
803 
804 			err |= lerr;
805 			if (lerr & (ERR_ABORT | ERR_FATAL)) {
806 				pxerr |= 1;
807 				break;
808 			}
809 			else if (lerr & ERR_CODE) {
810 				pxerr |= 1;
811 				continue;
812 			}
813 		}
814 
815 		if (!pxerr) {
816 			curproxy->state = PR_STREADY;
817 			send_log(curproxy, LOG_NOTICE, "Proxy %s started.\n", curproxy->id);
818 		}
819 
820 		if (err & ERR_ABORT)
821 			break;
822 	}
823 
824 	return err;
825 }
826 
827 
828 /*
829  * This is the proxy management task. It enables proxies when there are enough
830  * free streams, or stops them when the table is full. It is designed to be
831  * called as a task which is woken up upon stopping or when rate limiting must
832  * be enforced.
833  */
manage_proxy(struct task * t)834 struct task *manage_proxy(struct task *t)
835 {
836 	struct proxy *p = t->context;
837 	int next = TICK_ETERNITY;
838 	unsigned int wait;
839 
840 	/* We should periodically try to enable listeners waiting for a
841 	 * global resource here.
842 	 */
843 
844 	/* first, let's check if we need to stop the proxy */
845 	if (unlikely(stopping && p->state != PR_STSTOPPED)) {
846 		int t;
847 		t = tick_remain(now_ms, p->stop_time);
848 		if (t == 0) {
849 			Warning("Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
850 				p->id, p->fe_counters.cum_conn, p->be_counters.cum_conn);
851 			send_log(p, LOG_WARNING, "Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
852 				 p->id, p->fe_counters.cum_conn, p->be_counters.cum_conn);
853 			stop_proxy(p);
854 			/* try to free more memory */
855 			pool_gc2();
856 		}
857 		else {
858 			next = tick_first(next, p->stop_time);
859 		}
860 	}
861 
862 	/* If the proxy holds a stick table, we need to purge all unused
863 	 * entries. These are all the ones in the table with ref_cnt == 0
864 	 * and all the ones in the pool used to allocate new entries. Any
865 	 * entry attached to an existing stream waiting for a store will
866 	 * be in neither list. Any entry being dumped will have ref_cnt > 0.
867 	 * However we protect tables that are being synced to peers.
868 	 */
869 	if (unlikely(stopping && p->state == PR_STSTOPPED && p->table.current)) {
870 		if (!p->table.syncing) {
871 			stktable_trash_oldest(&p->table, p->table.current);
872 			pool_gc2();
873 		}
874 		if (p->table.current) {
875 			/* some entries still remain, let's recheck in one second */
876 			next = tick_first(next, tick_add(now_ms, 1000));
877 		}
878 	}
879 
880 	/* the rest below is just for frontends */
881 	if (!(p->cap & PR_CAP_FE))
882 		goto out;
883 
884 	/* check the various reasons we may find to block the frontend */
885 	if (unlikely(p->feconn >= p->maxconn)) {
886 		if (p->state == PR_STREADY)
887 			p->state = PR_STFULL;
888 		goto out;
889 	}
890 
891 	/* OK we have no reason to block, so let's unblock if we were blocking */
892 	if (p->state == PR_STFULL)
893 		p->state = PR_STREADY;
894 
895 	if (p->fe_sps_lim &&
896 	    (wait = next_event_delay(&p->fe_sess_per_sec, p->fe_sps_lim, 0))) {
897 		/* we're blocking because a limit was reached on the number of
898 		 * requests/s on the frontend. We want to re-check ASAP, which
899 		 * means in 1 ms before estimated expiration date, because the
900 		 * timer will have settled down.
901 		 */
902 		next = tick_first(next, tick_add(now_ms, wait));
903 		goto out;
904 	}
905 
906 	/* The proxy is not limited so we can re-enable any waiting listener */
907 	if (!LIST_ISEMPTY(&p->listener_queue))
908 		dequeue_all_listeners(&p->listener_queue);
909  out:
910 	t->expire = next;
911 	task_queue(t);
912 	return t;
913 }
914 
915 
proxy_parse_hard_stop_after(char ** args,int section_type,struct proxy * curpx,struct proxy * defpx,const char * file,int line,char ** err)916 static int proxy_parse_hard_stop_after(char **args, int section_type, struct proxy *curpx,
917                                 struct proxy *defpx, const char *file, int line,
918                                 char **err)
919 {
920 	const char *res;
921 
922 	if (!*args[1]) {
923 		memprintf(err, "'%s' expects <time> as argument.\n", args[0]);
924 		return -1;
925 	}
926 	res = parse_time_err(args[1], &global.hard_stop_after, TIME_UNIT_MS);
927 	if (res) {
928 		memprintf(err, "unexpected character '%c' in argument to <%s>.\n", *res, args[0]);
929 		return -1;
930 	}
931 	return 0;
932 }
933 
hard_stop(struct task * t)934 struct task *hard_stop(struct task *t)
935 {
936 	struct proxy *p;
937 	struct stream *s;
938 
939 	if (killed) {
940 		Warning("Some tasks resisted to hard-stop, exiting now.\n");
941 		send_log(NULL, LOG_WARNING, "Some tasks resisted to hard-stop, exiting now.\n");
942 		/* Do some cleanup and explicitely quit */
943 		deinit();
944 		exit(0);
945 	}
946 
947 	Warning("soft-stop running for too long, performing a hard-stop.\n");
948 	send_log(NULL, LOG_WARNING, "soft-stop running for too long, performing a hard-stop.\n");
949 	p = proxy;
950 	while (p) {
951 		if ((p->cap & PR_CAP_FE) && (p->feconn > 0)) {
952 			Warning("Proxy %s hard-stopped (%d remaining conns will be closed).\n",
953 				p->id, p->feconn);
954 			send_log(p, LOG_WARNING, "Proxy %s hard-stopped (%d remaining conns will be closed).\n",
955 				p->id, p->feconn);
956 		}
957 		p = p->next;
958 	}
959 	list_for_each_entry(s, &streams, list) {
960 		stream_shutdown(s, SF_ERR_KILLED);
961 	}
962 
963 	killed = 1;
964 	t->expire = tick_add(now_ms, MS_TO_TICKS(1000));
965 	return t;
966 }
967 
968 /*
969  * this function disables health-check servers so that the process will quickly be ignored
970  * by load balancers. Note that if a proxy was already in the PAUSED state, then its grace
971  * time will not be used since it would already not listen anymore to the socket.
972  */
soft_stop(void)973 void soft_stop(void)
974 {
975 	struct proxy *p;
976 	struct peers *prs;
977 	struct task *task;
978 
979 	stopping = 1;
980 	if (tick_isset(global.hard_stop_after)) {
981 		task = task_new();
982 		if (task) {
983 			task->process = hard_stop;
984 			task_schedule(task, tick_add(now_ms, global.hard_stop_after));
985 		}
986 		else {
987 			Alert("out of memory trying to allocate the hard-stop task.\n");
988 		}
989 	}
990 	p = proxy;
991 	tv_update_date(0,1); /* else, the old time before select will be used */
992 	while (p) {
993 		if (p->state != PR_STSTOPPED) {
994 			Warning("Stopping %s %s in %d ms.\n", proxy_cap_str(p->cap), p->id, p->grace);
995 			send_log(p, LOG_WARNING, "Stopping %s %s in %d ms.\n", proxy_cap_str(p->cap), p->id, p->grace);
996 			p->stop_time = tick_add(now_ms, p->grace);
997 
998 			/* Note: do not wake up stopped proxies' task nor their tables'
999 			 * tasks as these ones might point to already released entries.
1000 			 */
1001 			if (p->table.size && p->table.sync_task)
1002 				task_wakeup(p->table.sync_task, TASK_WOKEN_MSG);
1003 
1004 			if (p->task)
1005 				task_wakeup(p->task, TASK_WOKEN_MSG);
1006 		}
1007 		p = p->next;
1008 	}
1009 
1010 	prs = cfg_peers;
1011 	while (prs) {
1012 		if (prs->peers_fe)
1013 			stop_proxy(prs->peers_fe);
1014 		prs = prs->next;
1015 	}
1016 	/* signal zero is used to broadcast the "stopping" event */
1017 	signal_handler(0);
1018 }
1019 
1020 
1021 /* Temporarily disables listening on all of the proxy's listeners. Upon
1022  * success, the proxy enters the PR_PAUSED state. If disabling at least one
1023  * listener returns an error, then the proxy state is set to PR_STERROR
1024  * because we don't know how to resume from this. The function returns 0
1025  * if it fails, or non-zero on success.
1026  */
pause_proxy(struct proxy * p)1027 int pause_proxy(struct proxy *p)
1028 {
1029 	struct listener *l;
1030 
1031 	if (!(p->cap & PR_CAP_FE) || p->state == PR_STERROR ||
1032 	    p->state == PR_STSTOPPED || p->state == PR_STPAUSED)
1033 		return 1;
1034 
1035 	Warning("Pausing %s %s.\n", proxy_cap_str(p->cap), p->id);
1036 	send_log(p, LOG_WARNING, "Pausing %s %s.\n", proxy_cap_str(p->cap), p->id);
1037 
1038 	list_for_each_entry(l, &p->conf.listeners, by_fe) {
1039 		if (!pause_listener(l))
1040 			p->state = PR_STERROR;
1041 	}
1042 
1043 	if (p->state == PR_STERROR) {
1044 		Warning("%s %s failed to enter pause mode.\n", proxy_cap_str(p->cap), p->id);
1045 		send_log(p, LOG_WARNING, "%s %s failed to enter pause mode.\n", proxy_cap_str(p->cap), p->id);
1046 		return 0;
1047 	}
1048 
1049 	p->state = PR_STPAUSED;
1050 	return 1;
1051 }
1052 
1053 
1054 /*
1055  * This function completely stops a proxy and releases its listeners. It has
1056  * to be called when going down in order to release the ports so that another
1057  * process may bind to them. It must also be called on disabled proxies at the
1058  * end of start-up. When all listeners are closed, the proxy is set to the
1059  * PR_STSTOPPED state.
1060  */
stop_proxy(struct proxy * p)1061 void stop_proxy(struct proxy *p)
1062 {
1063 	struct listener *l;
1064 
1065 	list_for_each_entry(l, &p->conf.listeners, by_fe) {
1066 		unbind_listener(l);
1067 		if (l->state >= LI_ASSIGNED) {
1068 			delete_listener(l);
1069 			listeners--;
1070 			jobs--;
1071 		}
1072 	}
1073 	p->state = PR_STSTOPPED;
1074 }
1075 
1076 /* This function resumes listening on the specified proxy. It scans all of its
1077  * listeners and tries to enable them all. If any of them fails, the proxy is
1078  * put back to the paused state. It returns 1 upon success, or zero if an error
1079  * is encountered.
1080  */
resume_proxy(struct proxy * p)1081 int resume_proxy(struct proxy *p)
1082 {
1083 	struct listener *l;
1084 	int fail;
1085 
1086 	if (p->state != PR_STPAUSED)
1087 		return 1;
1088 
1089 	Warning("Enabling %s %s.\n", proxy_cap_str(p->cap), p->id);
1090 	send_log(p, LOG_WARNING, "Enabling %s %s.\n", proxy_cap_str(p->cap), p->id);
1091 
1092 	fail = 0;
1093 	list_for_each_entry(l, &p->conf.listeners, by_fe) {
1094 		if (!resume_listener(l)) {
1095 			int port;
1096 
1097 			port = get_host_port(&l->addr);
1098 			if (port) {
1099 				Warning("Port %d busy while trying to enable %s %s.\n",
1100 					port, proxy_cap_str(p->cap), p->id);
1101 				send_log(p, LOG_WARNING, "Port %d busy while trying to enable %s %s.\n",
1102 					 port, proxy_cap_str(p->cap), p->id);
1103 			}
1104 			else {
1105 				Warning("Bind on socket %d busy while trying to enable %s %s.\n",
1106 					l->luid, proxy_cap_str(p->cap), p->id);
1107 				send_log(p, LOG_WARNING, "Bind on socket %d busy while trying to enable %s %s.\n",
1108 					 l->luid, proxy_cap_str(p->cap), p->id);
1109 			}
1110 
1111 			/* Another port might have been enabled. Let's stop everything. */
1112 			fail = 1;
1113 			break;
1114 		}
1115 	}
1116 
1117 	p->state = PR_STREADY;
1118 	if (fail) {
1119 		pause_proxy(p);
1120 		return 0;
1121 	}
1122 	return 1;
1123 }
1124 
1125 /*
1126  * This function temporarily disables listening so that another new instance
1127  * can start listening. It is designed to be called upon reception of a
1128  * SIGTTOU, after which either a SIGUSR1 can be sent to completely stop
1129  * the proxy, or a SIGTTIN can be sent to listen again.
1130  */
pause_proxies(void)1131 void pause_proxies(void)
1132 {
1133 	int err;
1134 	struct proxy *p;
1135 	struct peers *prs;
1136 
1137 	err = 0;
1138 	p = proxy;
1139 	tv_update_date(0,1); /* else, the old time before select will be used */
1140 	while (p) {
1141 		err |= !pause_proxy(p);
1142 		p = p->next;
1143 	}
1144 
1145 	prs = cfg_peers;
1146 	while (prs) {
1147 		if (prs->peers_fe)
1148 			err |= !pause_proxy(prs->peers_fe);
1149 		prs = prs->next;
1150         }
1151 
1152 	if (err) {
1153 		Warning("Some proxies refused to pause, performing soft stop now.\n");
1154 		send_log(p, LOG_WARNING, "Some proxies refused to pause, performing soft stop now.\n");
1155 		soft_stop();
1156 	}
1157 }
1158 
1159 
1160 /*
1161  * This function reactivates listening. This can be used after a call to
1162  * sig_pause(), for example when a new instance has failed starting up.
1163  * It is designed to be called upon reception of a SIGTTIN.
1164  */
resume_proxies(void)1165 void resume_proxies(void)
1166 {
1167 	int err;
1168 	struct proxy *p;
1169 	struct peers *prs;
1170 
1171 	err = 0;
1172 	p = proxy;
1173 	tv_update_date(0,1); /* else, the old time before select will be used */
1174 	while (p) {
1175 		err |= !resume_proxy(p);
1176 		p = p->next;
1177 	}
1178 
1179 	prs = cfg_peers;
1180 	while (prs) {
1181 		if (prs->peers_fe)
1182 			err |= !resume_proxy(prs->peers_fe);
1183 		prs = prs->next;
1184         }
1185 
1186 	if (err) {
1187 		Warning("Some proxies refused to resume, a restart is probably needed to resume safe operations.\n");
1188 		send_log(p, LOG_WARNING, "Some proxies refused to resume, a restart is probably needed to resume safe operations.\n");
1189 	}
1190 }
1191 
1192 /* Set current stream's backend to <be>. Nothing is done if the
1193  * stream already had a backend assigned, which is indicated by
1194  * s->flags & SF_BE_ASSIGNED.
1195  * All flags, stats and counters which need be updated are updated.
1196  * Returns 1 if done, 0 in case of internal error, eg: lack of resource.
1197  */
stream_set_backend(struct stream * s,struct proxy * be)1198 int stream_set_backend(struct stream *s, struct proxy *be)
1199 {
1200 	if (s->flags & SF_BE_ASSIGNED)
1201 		return 1;
1202 
1203 	if (flt_set_stream_backend(s, be) < 0)
1204 		return 0;
1205 
1206 	s->be = be;
1207 	be->beconn++;
1208 	if (be->beconn > be->be_counters.conn_max)
1209 		be->be_counters.conn_max = be->beconn;
1210 	proxy_inc_be_ctr(be);
1211 
1212 	/* assign new parameters to the stream from the new backend */
1213 	s->si[1].flags &= ~SI_FL_INDEP_STR;
1214 	if (be->options2 & PR_O2_INDEPSTR)
1215 		s->si[1].flags |= SI_FL_INDEP_STR;
1216 
1217 	if (tick_isset(be->timeout.serverfin))
1218 		s->si[1].hcto = be->timeout.serverfin;
1219 
1220 	/* We want to enable the backend-specific analysers except those which
1221 	 * were already run as part of the frontend/listener. Note that it would
1222 	 * be more reliable to store the list of analysers that have been run,
1223 	 * but what we do here is OK for now.
1224 	 */
1225 	s->req.analysers |= be->be_req_ana & ~(strm_li(s) ? strm_li(s)->analysers : 0);
1226 
1227 	/* If the target backend requires HTTP processing, we have to allocate
1228 	 * the HTTP transaction and hdr_idx if we did not have one.
1229 	 */
1230 	if (unlikely(!s->txn && be->http_needed)) {
1231 		if (unlikely(!http_alloc_txn(s)))
1232 			return 0; /* not enough memory */
1233 
1234 		/* and now initialize the HTTP transaction state */
1235 		http_init_txn(s);
1236 	}
1237 
1238 	/* Be sure to filter request headers if the backend is an HTTP proxy and
1239 	 * if there are filters attached to the stream. */
1240 	if (s->be->mode == PR_MODE_HTTP && HAS_FILTERS(s))
1241 		s->req.analysers |= AN_REQ_FLT_HTTP_HDRS;
1242 
1243 	if (s->txn) {
1244 		if (be->options2 & PR_O2_RSPBUG_OK)
1245 			s->txn->rsp.err_pos = -1; /* let buggy responses pass */
1246 
1247 		/* If we chain to an HTTP backend running a different HTTP mode, we
1248 		 * have to re-adjust the desired keep-alive/close mode to accommodate
1249 		 * both the frontend's and the backend's modes.
1250 		 */
1251 		if (strm_fe(s)->mode == PR_MODE_HTTP && be->mode == PR_MODE_HTTP &&
1252 		    ((strm_fe(s)->options & PR_O_HTTP_MODE) != (be->options & PR_O_HTTP_MODE)))
1253 			http_adjust_conn_mode(s, s->txn, &s->txn->req);
1254 
1255 		/* If an LB algorithm needs to access some pre-parsed body contents,
1256 		 * we must not start to forward anything until the connection is
1257 		 * confirmed otherwise we'll lose the pointer to these data and
1258 		 * prevent the hash from being doable again after a redispatch.
1259 		 */
1260 		if (be->mode == PR_MODE_HTTP &&
1261 		    (be->lbprm.algo & (BE_LB_KIND | BE_LB_PARM)) == (BE_LB_KIND_HI | BE_LB_HASH_PRM))
1262 			s->txn->req.flags |= HTTP_MSGF_WAIT_CONN;
1263 
1264 		/* we may request to parse a request body */
1265 		if ((be->options & PR_O_WREQ_BODY) &&
1266 		    (s->txn->req.body_len || (s->txn->req.flags & HTTP_MSGF_TE_CHNK)))
1267 			s->req.analysers |= AN_REQ_HTTP_BODY;
1268 	}
1269 
1270 	s->flags |= SF_BE_ASSIGNED;
1271 	if (be->options2 & PR_O2_NODELAY) {
1272 		s->req.flags |= CF_NEVER_WAIT;
1273 		s->res.flags |= CF_NEVER_WAIT;
1274 	}
1275 
1276 	return 1;
1277 }
1278 
1279 static struct cfg_kw_list cfg_kws = {ILH, {
1280 	{ CFG_GLOBAL, "hard-stop-after", proxy_parse_hard_stop_after },
1281 	{ CFG_LISTEN, "timeout", proxy_parse_timeout },
1282 	{ CFG_LISTEN, "clitimeout", proxy_parse_timeout },
1283 	{ CFG_LISTEN, "contimeout", proxy_parse_timeout },
1284 	{ CFG_LISTEN, "srvtimeout", proxy_parse_timeout },
1285 	{ CFG_LISTEN, "rate-limit", proxy_parse_rate_limit },
1286 	{ CFG_LISTEN, "max-keep-alive-queue", proxy_parse_max_ka_queue },
1287 	{ CFG_LISTEN, "declare", proxy_parse_declare },
1288 	{ 0, NULL, NULL },
1289 }};
1290 
1291 /* Expects to find a frontend named <arg> and returns it, otherwise displays various
1292  * adequate error messages and returns NULL. This function is designed to be used by
1293  * functions requiring a frontend on the CLI.
1294  */
cli_find_frontend(struct appctx * appctx,const char * arg)1295 struct proxy *cli_find_frontend(struct appctx *appctx, const char *arg)
1296 {
1297 	struct proxy *px;
1298 
1299 	if (!*arg) {
1300 		appctx->ctx.cli.msg = "A frontend name is expected.\n";
1301 		appctx->st0 = CLI_ST_PRINT;
1302 		return NULL;
1303 	}
1304 
1305 	px = proxy_fe_by_name(arg);
1306 	if (!px) {
1307 		appctx->ctx.cli.msg = "No such frontend.\n";
1308 		appctx->st0 = CLI_ST_PRINT;
1309 		return NULL;
1310 	}
1311 	return px;
1312 }
1313 
1314 /* parse a "show servers" CLI line, returns 0 if it wants to start the dump or
1315  * 1 if it stops immediately.
1316  */
cli_parse_show_servers(char ** args,struct appctx * appctx,void * private)1317 static int cli_parse_show_servers(char **args, struct appctx *appctx, void *private)
1318 {
1319 	appctx->ctx.server_state.iid = 0;
1320 	appctx->ctx.server_state.px = NULL;
1321 	appctx->ctx.server_state.sv = NULL;
1322 
1323 	/* check if a backend name has been provided */
1324 	if (*args[3]) {
1325 		/* read server state from local file */
1326 		appctx->ctx.server_state.px = proxy_be_by_name(args[3]);
1327 
1328 		if (!appctx->ctx.server_state.px) {
1329 			appctx->ctx.cli.msg = "Can't find backend.\n";
1330 			appctx->st0 = CLI_ST_PRINT;
1331 			return 1;
1332 		}
1333 		appctx->ctx.server_state.iid = appctx->ctx.server_state.px->uuid;
1334 	}
1335 	return 0;
1336 }
1337 
1338 /* dumps server state information into <buf> for all the servers found in <backend>
1339  * These information are all the parameters which may change during HAProxy runtime.
1340  * By default, we only export to the last known server state file format.
1341  * These information can be used at next startup to recover same level of server state.
1342  */
dump_servers_state(struct stream_interface * si,struct chunk * buf)1343 static int dump_servers_state(struct stream_interface *si, struct chunk *buf)
1344 {
1345 	struct appctx *appctx = __objt_appctx(si->end);
1346 	struct server *srv;
1347 	char srv_addr[INET6_ADDRSTRLEN + 1];
1348 	time_t srv_time_since_last_change;
1349 	int bk_f_forced_id, srv_f_forced_id;
1350 
1351 
1352 	/* we don't want to report any state if the backend is not enabled on this process */
1353 	if (appctx->ctx.server_state.px->bind_proc && !(appctx->ctx.server_state.px->bind_proc & (1UL << (relative_pid - 1))))
1354 		return 1;
1355 
1356 	if (!appctx->ctx.server_state.sv)
1357 		appctx->ctx.server_state.sv = appctx->ctx.server_state.px->srv;
1358 
1359 	for (; appctx->ctx.server_state.sv != NULL; appctx->ctx.server_state.sv = srv->next) {
1360 		srv = appctx->ctx.server_state.sv;
1361 		srv_addr[0] = '\0';
1362 
1363 		switch (srv->addr.ss_family) {
1364 			case AF_INET:
1365 				inet_ntop(srv->addr.ss_family, &((struct sockaddr_in *)&srv->addr)->sin_addr,
1366 					  srv_addr, INET_ADDRSTRLEN + 1);
1367 				break;
1368 			case AF_INET6:
1369 				inet_ntop(srv->addr.ss_family, &((struct sockaddr_in6 *)&srv->addr)->sin6_addr,
1370 					  srv_addr, INET6_ADDRSTRLEN + 1);
1371 				break;
1372 		}
1373 		srv_time_since_last_change = now.tv_sec - srv->last_change;
1374 		bk_f_forced_id = appctx->ctx.server_state.px->options & PR_O_FORCED_ID ? 1 : 0;
1375 		srv_f_forced_id = srv->flags & SRV_F_FORCED_ID ? 1 : 0;
1376 
1377 		chunk_appendf(buf,
1378 				"%d %s "
1379 				"%d %s %s "
1380 				"%d %d %d %d %ld "
1381 				"%d %d %d %d %d "
1382 				"%d %d"
1383 				"\n",
1384 				appctx->ctx.server_state.px->uuid, appctx->ctx.server_state.px->id,
1385 				srv->puid, srv->id, srv_addr,
1386 				srv->state, srv->admin, srv->uweight, srv->iweight, (long int)srv_time_since_last_change,
1387 				srv->check.status, srv->check.result, srv->check.health, srv->check.state, srv->agent.state,
1388 				bk_f_forced_id, srv_f_forced_id);
1389 		if (bi_putchk(si_ic(si), &trash) == -1) {
1390 			si_applet_cant_put(si);
1391 			return 0;
1392 		}
1393 	}
1394 	return 1;
1395 }
1396 
1397 /* Parses backend list or simply use backend name provided by the user to return
1398  * states of servers to stdout.
1399  */
cli_io_handler_servers_state(struct appctx * appctx)1400 static int cli_io_handler_servers_state(struct appctx *appctx)
1401 {
1402 	struct stream_interface *si = appctx->owner;
1403 	extern struct proxy *proxy;
1404 	struct proxy *curproxy;
1405 
1406 	chunk_reset(&trash);
1407 
1408 	if (appctx->st2 == STAT_ST_INIT) {
1409 		if (!appctx->ctx.server_state.px)
1410 			appctx->ctx.server_state.px = proxy;
1411 		appctx->st2 = STAT_ST_HEAD;
1412 	}
1413 
1414 	if (appctx->st2 == STAT_ST_HEAD) {
1415 		chunk_printf(&trash, "%d\n# %s\n", SRV_STATE_FILE_VERSION, SRV_STATE_FILE_FIELD_NAMES);
1416 		if (bi_putchk(si_ic(si), &trash) == -1) {
1417 			si_applet_cant_put(si);
1418 			return 0;
1419 		}
1420 		appctx->st2 = STAT_ST_INFO;
1421 	}
1422 
1423 	/* STAT_ST_INFO */
1424 	for (; appctx->ctx.server_state.px != NULL; appctx->ctx.server_state.px = curproxy->next) {
1425 		curproxy = appctx->ctx.server_state.px;
1426 		/* servers are only in backends */
1427 		if (curproxy->cap & PR_CAP_BE) {
1428 			if (!dump_servers_state(si, &trash))
1429 				return 0;
1430 
1431 			if (bi_putchk(si_ic(si), &trash) == -1) {
1432 				si_applet_cant_put(si);
1433 				return 0;
1434 			}
1435 		}
1436 		/* only the selected proxy is dumped */
1437 		if (appctx->ctx.server_state.iid)
1438 			break;
1439 	}
1440 
1441 	return 1;
1442 }
1443 
cli_parse_show_backend(char ** args,struct appctx * appctx,void * private)1444 static int cli_parse_show_backend(char **args, struct appctx *appctx, void *private)
1445 {
1446 	appctx->ctx.be.px = NULL;
1447 	return 0;
1448 }
1449 
1450 /* Parses backend list and simply report backend names */
cli_io_handler_show_backend(struct appctx * appctx)1451 static int cli_io_handler_show_backend(struct appctx *appctx)
1452 {
1453 	extern struct proxy *proxy;
1454 	struct stream_interface *si = appctx->owner;
1455 	struct proxy *curproxy;
1456 
1457 	chunk_reset(&trash);
1458 
1459 	if (!appctx->ctx.be.px) {
1460 		chunk_printf(&trash, "# name\n");
1461 		if (bi_putchk(si_ic(si), &trash) == -1) {
1462 			si_applet_cant_put(si);
1463 			return 0;
1464 		}
1465 		appctx->ctx.be.px = proxy;
1466 	}
1467 
1468 	for (; appctx->ctx.be.px != NULL; appctx->ctx.be.px = curproxy->next) {
1469 		curproxy = appctx->ctx.be.px;
1470 
1471 		/* looking for backends only */
1472 		if (!(curproxy->cap & PR_CAP_BE))
1473 			continue;
1474 
1475 		/* we don't want to list a backend which is bound to this process */
1476 		if (curproxy->bind_proc && !(curproxy->bind_proc & (1UL << (relative_pid - 1))))
1477 			continue;
1478 
1479 		chunk_appendf(&trash, "%s\n", curproxy->id);
1480 		if (bi_putchk(si_ic(si), &trash) == -1) {
1481 			si_applet_cant_put(si);
1482 			return 0;
1483 		}
1484 	}
1485 
1486 	return 1;
1487 }
1488 
1489 /* Parses the "set maxconn frontend" directive, it always returns 1 */
cli_parse_set_maxconn_frontend(char ** args,struct appctx * appctx,void * private)1490 static int cli_parse_set_maxconn_frontend(char **args, struct appctx *appctx, void *private)
1491 {
1492 	struct proxy *px;
1493 	struct listener *l;
1494 	int v;
1495 
1496 	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1497 		return 1;
1498 
1499 	px = cli_find_frontend(appctx, args[3]);
1500 	if (!px)
1501 		return 1;
1502 
1503 	if (!*args[4]) {
1504 		appctx->ctx.cli.msg = "Integer value expected.\n";
1505 		appctx->st0 = CLI_ST_PRINT;
1506 		return 1;
1507 	}
1508 
1509 	v = atoi(args[4]);
1510 	if (v < 0) {
1511 		appctx->ctx.cli.msg = "Value out of range.\n";
1512 		appctx->st0 = CLI_ST_PRINT;
1513 		return 1;
1514 	}
1515 
1516 	/* OK, the value is fine, so we assign it to the proxy and to all of
1517 	 * its listeners. The blocked ones will be dequeued.
1518 	 */
1519 	px->maxconn = v;
1520 	list_for_each_entry(l, &px->conf.listeners, by_fe) {
1521 		l->maxconn = v;
1522 		if (l->state == LI_FULL)
1523 			resume_listener(l);
1524 	}
1525 
1526 	if (px->maxconn > px->feconn && !LIST_ISEMPTY(&px->listener_queue))
1527 		dequeue_all_listeners(&px->listener_queue);
1528 
1529 	return 1;
1530 }
1531 
1532 /* Parses the "shutdown frontend" directive, it always returns 1 */
cli_parse_shutdown_frontend(char ** args,struct appctx * appctx,void * private)1533 static int cli_parse_shutdown_frontend(char **args, struct appctx *appctx, void *private)
1534 {
1535 	struct proxy *px;
1536 
1537 	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1538 		return 1;
1539 
1540 	px = cli_find_frontend(appctx, args[2]);
1541 	if (!px)
1542 		return 1;
1543 
1544 	if (px->state == PR_STSTOPPED) {
1545 		appctx->ctx.cli.msg = "Frontend was already shut down.\n";
1546 		appctx->st0 = CLI_ST_PRINT;
1547 		return 1;
1548 	}
1549 
1550 	Warning("Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
1551 	        px->id, px->fe_counters.cum_conn, px->be_counters.cum_conn);
1552 	send_log(px, LOG_WARNING, "Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
1553 	         px->id, px->fe_counters.cum_conn, px->be_counters.cum_conn);
1554 	stop_proxy(px);
1555 	return 1;
1556 }
1557 
1558 /* Parses the "disable frontend" directive, it always returns 1 */
cli_parse_disable_frontend(char ** args,struct appctx * appctx,void * private)1559 static int cli_parse_disable_frontend(char **args, struct appctx *appctx, void *private)
1560 {
1561 	struct proxy *px;
1562 
1563 	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1564 		return 1;
1565 
1566 	px = cli_find_frontend(appctx, args[2]);
1567 	if (!px)
1568 		return 1;
1569 
1570 	if (px->state == PR_STSTOPPED) {
1571 		appctx->ctx.cli.msg = "Frontend was previously shut down, cannot disable.\n";
1572 		appctx->st0 = CLI_ST_PRINT;
1573 		return 1;
1574 	}
1575 
1576 	if (px->state == PR_STPAUSED) {
1577 		appctx->ctx.cli.msg = "Frontend is already disabled.\n";
1578 		appctx->st0 = CLI_ST_PRINT;
1579 		return 1;
1580 	}
1581 
1582 	if (!pause_proxy(px)) {
1583 		appctx->ctx.cli.msg = "Failed to pause frontend, check logs for precise cause.\n";
1584 		appctx->st0 = CLI_ST_PRINT;
1585 		return 1;
1586 	}
1587 	return 1;
1588 }
1589 
1590 /* Parses the "enable frontend" directive, it always returns 1 */
cli_parse_enable_frontend(char ** args,struct appctx * appctx,void * private)1591 static int cli_parse_enable_frontend(char **args, struct appctx *appctx, void *private)
1592 {
1593 	struct proxy *px;
1594 
1595 	if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1596 		return 1;
1597 
1598 	px = cli_find_frontend(appctx, args[2]);
1599 	if (!px)
1600 		return 1;
1601 
1602 	if (px->state == PR_STSTOPPED) {
1603 		appctx->ctx.cli.msg = "Frontend was previously shut down, cannot enable.\n";
1604 		appctx->st0 = CLI_ST_PRINT;
1605 		return 1;
1606 	}
1607 
1608 	if (px->state != PR_STPAUSED) {
1609 		appctx->ctx.cli.msg = "Frontend is already enabled.\n";
1610 		appctx->st0 = CLI_ST_PRINT;
1611 		return 1;
1612 	}
1613 
1614 	if (!resume_proxy(px)) {
1615 		appctx->ctx.cli.msg = "Failed to resume frontend, check logs for precise cause (port conflict?).\n";
1616 		appctx->st0 = CLI_ST_PRINT;
1617 		return 1;
1618 	}
1619 	return 1;
1620 }
1621 
1622 /* register cli keywords */
1623 static struct cli_kw_list cli_kws = {{ },{
1624 	{ { "disable", "frontend",  NULL }, "disable frontend : temporarily disable specific frontend", cli_parse_disable_frontend, NULL, NULL },
1625 	{ { "enable", "frontend",  NULL }, "enable frontend : re-enable specific frontend", cli_parse_enable_frontend, NULL, NULL },
1626 	{ { "set", "maxconn", "frontend",  NULL }, "set maxconn frontend : change a frontend's maxconn setting", cli_parse_set_maxconn_frontend, NULL },
1627 	{ { "show","servers", "state",  NULL }, "show servers state [id]: dump volatile server information (for backend <id>)", cli_parse_show_servers, cli_io_handler_servers_state },
1628 	{ { "show", "backend", NULL }, "show backend   : list backends in the current running config", cli_parse_show_backend, cli_io_handler_show_backend },
1629 	{ { "shutdown", "frontend",  NULL }, "shutdown frontend : stop a specific frontend", cli_parse_shutdown_frontend, NULL, NULL },
1630 	{{},}
1631 }};
1632 
1633 __attribute__((constructor))
__proxy_module_init(void)1634 static void __proxy_module_init(void)
1635 {
1636 	cfg_register_keywords(&cfg_kws);
1637 	cli_register_kw(&cli_kws);
1638 }
1639 
1640 /*
1641  * Local variables:
1642  *  c-indent-level: 8
1643  *  c-basic-offset: 8
1644  * End:
1645  */
1646