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/initcall.h>
26 #include <common/memory.h>
27 #include <common/time.h>
28
29 #include <eb32tree.h>
30 #include <ebistree.h>
31
32 #include <types/capture.h>
33 #include <types/cli.h>
34 #include <types/global.h>
35 #include <types/obj_type.h>
36 #include <types/peers.h>
37 #include <types/stats.h>
38
39 #include <proto/applet.h>
40 #include <proto/cli.h>
41 #include <proto/backend.h>
42 #include <proto/fd.h>
43 #include <proto/filters.h>
44 #include <proto/hdr_idx.h>
45 #include <proto/listener.h>
46 #include <proto/log.h>
47 #include <proto/proto_tcp.h>
48 #include <proto/proto_http.h>
49 #include <proto/proxy.h>
50 #include <proto/server.h>
51 #include <proto/signal.h>
52 #include <proto/stream.h>
53 #include <proto/stream_interface.h>
54 #include <proto/task.h>
55
56
57 int listeners; /* # of proxy listeners, set by cfgparse */
58 struct proxy *proxies_list = NULL; /* list of all existing proxies */
59 struct eb_root used_proxy_id = EB_ROOT; /* list of proxy IDs in use */
60 struct eb_root proxy_by_name = EB_ROOT; /* tree of proxies sorted by name */
61 unsigned int error_snapshot_id = 0; /* global ID assigned to each error then incremented */
62
63 /* proxy->options */
64 const struct cfg_opt cfg_opts[] =
65 {
66 { "abortonclose", PR_O_ABRT_CLOSE, PR_CAP_BE, 0, 0 },
67 { "allbackups", PR_O_USE_ALL_BK, PR_CAP_BE, 0, 0 },
68 { "checkcache", PR_O_CHK_CACHE, PR_CAP_BE, 0, PR_MODE_HTTP },
69 { "clitcpka", PR_O_TCP_CLI_KA, PR_CAP_FE, 0, 0 },
70 { "contstats", PR_O_CONTSTATS, PR_CAP_FE, 0, 0 },
71 { "dontlognull", PR_O_NULLNOLOG, PR_CAP_FE, 0, 0 },
72 { "http_proxy", PR_O_HTTP_PROXY, PR_CAP_FE | PR_CAP_BE, 0, PR_MODE_HTTP },
73 { "http-buffer-request", PR_O_WREQ_BODY, PR_CAP_FE | PR_CAP_BE, 0, PR_MODE_HTTP },
74 { "http-ignore-probes", PR_O_IGNORE_PRB, PR_CAP_FE, 0, PR_MODE_HTTP },
75 { "prefer-last-server", PR_O_PREF_LAST, PR_CAP_BE, 0, PR_MODE_HTTP },
76 { "logasap", PR_O_LOGASAP, PR_CAP_FE, 0, 0 },
77 { "nolinger", PR_O_TCP_NOLING, PR_CAP_FE | PR_CAP_BE, 0, 0 },
78 { "persist", PR_O_PERSIST, PR_CAP_BE, 0, 0 },
79 { "srvtcpka", PR_O_TCP_SRV_KA, PR_CAP_BE, 0, 0 },
80 #ifdef TPROXY
81 { "transparent", PR_O_TRANSP, PR_CAP_BE, 0, 0 },
82 #else
83 { "transparent", 0, 0, 0, 0 },
84 #endif
85
86 { NULL, 0, 0, 0, 0 }
87 };
88
89 /* proxy->options2 */
90 const struct cfg_opt cfg_opts2[] =
91 {
92 #ifdef CONFIG_HAP_LINUX_SPLICE
93 { "splice-request", PR_O2_SPLIC_REQ, PR_CAP_FE|PR_CAP_BE, 0, 0 },
94 { "splice-response", PR_O2_SPLIC_RTR, PR_CAP_FE|PR_CAP_BE, 0, 0 },
95 { "splice-auto", PR_O2_SPLIC_AUT, PR_CAP_FE|PR_CAP_BE, 0, 0 },
96 #else
97 { "splice-request", 0, 0, 0, 0 },
98 { "splice-response", 0, 0, 0, 0 },
99 { "splice-auto", 0, 0, 0, 0 },
100 #endif
101 { "accept-invalid-http-request", PR_O2_REQBUG_OK, PR_CAP_FE, 0, PR_MODE_HTTP },
102 { "accept-invalid-http-response", PR_O2_RSPBUG_OK, PR_CAP_BE, 0, PR_MODE_HTTP },
103 { "dontlog-normal", PR_O2_NOLOGNORM, PR_CAP_FE, 0, 0 },
104 { "log-separate-errors", PR_O2_LOGERRORS, PR_CAP_FE, 0, 0 },
105 { "log-health-checks", PR_O2_LOGHCHKS, PR_CAP_BE, 0, 0 },
106 { "socket-stats", PR_O2_SOCKSTAT, PR_CAP_FE, 0, 0 },
107 { "tcp-smart-accept", PR_O2_SMARTACC, PR_CAP_FE, 0, 0 },
108 { "tcp-smart-connect", PR_O2_SMARTCON, PR_CAP_BE, 0, 0 },
109 { "independant-streams", PR_O2_INDEPSTR, PR_CAP_FE|PR_CAP_BE, 0, 0 },
110 { "independent-streams", PR_O2_INDEPSTR, PR_CAP_FE|PR_CAP_BE, 0, 0 },
111 { "http-use-proxy-header", PR_O2_USE_PXHDR, PR_CAP_FE, 0, PR_MODE_HTTP },
112 { "http-pretend-keepalive", PR_O2_FAKE_KA, PR_CAP_BE, 0, PR_MODE_HTTP },
113 { "http-no-delay", PR_O2_NODELAY, PR_CAP_FE|PR_CAP_BE, 0, PR_MODE_HTTP },
114 { "http-use-htx", PR_O2_USE_HTX, PR_CAP_FE|PR_CAP_BE, 0, PR_MODE_HTTP },
115 { NULL, 0, 0, 0 }
116 };
117
118 /*
119 * This function returns a string containing a name describing capabilities to
120 * report comprehensible error messages. Specifically, it will return the words
121 * "frontend", "backend" when appropriate, or "proxy" for all other
122 * cases including the proxies declared in "listen" mode.
123 */
proxy_cap_str(int cap)124 const char *proxy_cap_str(int cap)
125 {
126 if ((cap & PR_CAP_LISTEN) != PR_CAP_LISTEN) {
127 if (cap & PR_CAP_FE)
128 return "frontend";
129 else if (cap & PR_CAP_BE)
130 return "backend";
131 }
132 return "proxy";
133 }
134
135 /*
136 * This function returns a string containing the mode of the proxy in a format
137 * suitable for error messages.
138 */
proxy_mode_str(int mode)139 const char *proxy_mode_str(int mode) {
140
141 if (mode == PR_MODE_TCP)
142 return "tcp";
143 else if (mode == PR_MODE_HTTP)
144 return "http";
145 else if (mode == PR_MODE_HEALTH)
146 return "health";
147 else if (mode == PR_MODE_CLI)
148 return "cli";
149 else
150 return "unknown";
151 }
152
153 /*
154 * This function scans the list of backends and servers to retrieve the first
155 * backend and the first server with the given names, and sets them in both
156 * parameters. It returns zero if either is not found, or non-zero and sets
157 * the ones it did not found to NULL. If a NULL pointer is passed for the
158 * backend, only the pointer to the server will be updated.
159 */
get_backend_server(const char * bk_name,const char * sv_name,struct proxy ** bk,struct server ** sv)160 int get_backend_server(const char *bk_name, const char *sv_name,
161 struct proxy **bk, struct server **sv)
162 {
163 struct proxy *p;
164 struct server *s;
165 int sid;
166
167 *sv = NULL;
168
169 sid = -1;
170 if (*sv_name == '#')
171 sid = atoi(sv_name + 1);
172
173 p = proxy_be_by_name(bk_name);
174 if (bk)
175 *bk = p;
176 if (!p)
177 return 0;
178
179 for (s = p->srv; s; s = s->next)
180 if ((sid >= 0 && s->puid == sid) ||
181 (sid < 0 && strcmp(s->id, sv_name) == 0))
182 break;
183 *sv = s;
184 if (!s)
185 return 0;
186 return 1;
187 }
188
189 /* This function parses a "timeout" statement in a proxy section. It returns
190 * -1 if there is any error, 1 for a warning, otherwise zero. If it does not
191 * return zero, it will write an error or warning message into a preallocated
192 * buffer returned at <err>. The trailing is not be written. The function must
193 * be called with <args> pointing to the first command line word, with <proxy>
194 * pointing to the proxy being parsed, and <defpx> to the default proxy or NULL.
195 * As a special case for compatibility with older configs, it also accepts
196 * "{cli|srv|con}timeout" in args[0].
197 */
proxy_parse_timeout(char ** args,int section,struct proxy * proxy,struct proxy * defpx,const char * file,int line,char ** err)198 static int proxy_parse_timeout(char **args, int section, struct proxy *proxy,
199 struct proxy *defpx, const char *file, int line,
200 char **err)
201 {
202 unsigned timeout;
203 int retval, cap;
204 const char *res, *name;
205 int *tv = NULL;
206 int *td = NULL;
207 int warn = 0;
208
209 retval = 0;
210
211 /* simply skip "timeout" but remain compatible with old form */
212 if (strcmp(args[0], "timeout") == 0)
213 args++;
214
215 name = args[0];
216 if (!strcmp(args[0], "client") || (!strcmp(args[0], "clitimeout") && (warn = WARN_CLITO_DEPRECATED))) {
217 name = "client";
218 tv = &proxy->timeout.client;
219 td = &defpx->timeout.client;
220 cap = PR_CAP_FE;
221 } else if (!strcmp(args[0], "tarpit")) {
222 tv = &proxy->timeout.tarpit;
223 td = &defpx->timeout.tarpit;
224 cap = PR_CAP_FE | PR_CAP_BE;
225 } else if (!strcmp(args[0], "http-keep-alive")) {
226 tv = &proxy->timeout.httpka;
227 td = &defpx->timeout.httpka;
228 cap = PR_CAP_FE | PR_CAP_BE;
229 } else if (!strcmp(args[0], "http-request")) {
230 tv = &proxy->timeout.httpreq;
231 td = &defpx->timeout.httpreq;
232 cap = PR_CAP_FE | PR_CAP_BE;
233 } else if (!strcmp(args[0], "server") || (!strcmp(args[0], "srvtimeout") && (warn = WARN_SRVTO_DEPRECATED))) {
234 name = "server";
235 tv = &proxy->timeout.server;
236 td = &defpx->timeout.server;
237 cap = PR_CAP_BE;
238 } else if (!strcmp(args[0], "connect") || (!strcmp(args[0], "contimeout") && (warn = WARN_CONTO_DEPRECATED))) {
239 name = "connect";
240 tv = &proxy->timeout.connect;
241 td = &defpx->timeout.connect;
242 cap = PR_CAP_BE;
243 } else if (!strcmp(args[0], "check")) {
244 tv = &proxy->timeout.check;
245 td = &defpx->timeout.check;
246 cap = PR_CAP_BE;
247 } else if (!strcmp(args[0], "queue")) {
248 tv = &proxy->timeout.queue;
249 td = &defpx->timeout.queue;
250 cap = PR_CAP_BE;
251 } else if (!strcmp(args[0], "tunnel")) {
252 tv = &proxy->timeout.tunnel;
253 td = &defpx->timeout.tunnel;
254 cap = PR_CAP_BE;
255 } else if (!strcmp(args[0], "client-fin")) {
256 tv = &proxy->timeout.clientfin;
257 td = &defpx->timeout.clientfin;
258 cap = PR_CAP_FE;
259 } else if (!strcmp(args[0], "server-fin")) {
260 tv = &proxy->timeout.serverfin;
261 td = &defpx->timeout.serverfin;
262 cap = PR_CAP_BE;
263 } else {
264 memprintf(err,
265 "'timeout' supports 'client', 'server', 'connect', 'check', "
266 "'queue', 'http-keep-alive', 'http-request', 'tunnel', 'tarpit', "
267 "'client-fin' and 'server-fin' (got '%s')",
268 args[0]);
269 return -1;
270 }
271
272 if (*args[1] == 0) {
273 memprintf(err, "'timeout %s' expects an integer value (in milliseconds)", name);
274 return -1;
275 }
276
277 res = parse_time_err(args[1], &timeout, TIME_UNIT_MS);
278 if (res) {
279 memprintf(err, "unexpected character '%c' in 'timeout %s'", *res, name);
280 return -1;
281 }
282
283 if (!(proxy->cap & cap)) {
284 memprintf(err, "'timeout %s' will be ignored because %s '%s' has no %s capability",
285 name, proxy_type_str(proxy), proxy->id,
286 (cap & PR_CAP_BE) ? "backend" : "frontend");
287 retval = 1;
288 }
289 else if (defpx && *tv != *td) {
290 memprintf(err, "overwriting 'timeout %s' which was already specified", name);
291 retval = 1;
292 }
293 else if (warn) {
294 if (!already_warned(warn)) {
295 memprintf(err, "the '%s' directive is now deprecated in favor of 'timeout %s', and will not be supported in future versions.",
296 args[0], name);
297 retval = 1;
298 }
299 }
300
301 if (*args[2] != 0) {
302 memprintf(err, "'timeout %s' : unexpected extra argument '%s' after value '%s'.", name, args[2], args[1]);
303 retval = -1;
304 }
305
306 *tv = MS_TO_TICKS(timeout);
307 return retval;
308 }
309
310 /* This function parses a "rate-limit" statement in a proxy section. It returns
311 * -1 if there is any error, 1 for a warning, otherwise zero. If it does not
312 * return zero, it will write an error or warning message into a preallocated
313 * buffer returned at <err>. The function must be called with <args> pointing
314 * to the first command line word, with <proxy> pointing to the proxy being
315 * parsed, and <defpx> to the default proxy or NULL.
316 */
proxy_parse_rate_limit(char ** args,int section,struct proxy * proxy,struct proxy * defpx,const char * file,int line,char ** err)317 static int proxy_parse_rate_limit(char **args, int section, struct proxy *proxy,
318 struct proxy *defpx, const char *file, int line,
319 char **err)
320 {
321 int retval, cap;
322 char *res;
323 unsigned int *tv = NULL;
324 unsigned int *td = NULL;
325 unsigned int val;
326
327 retval = 0;
328
329 if (strcmp(args[1], "sessions") == 0) {
330 tv = &proxy->fe_sps_lim;
331 td = &defpx->fe_sps_lim;
332 cap = PR_CAP_FE;
333 }
334 else {
335 memprintf(err, "'%s' only supports 'sessions' (got '%s')", args[0], args[1]);
336 return -1;
337 }
338
339 if (*args[2] == 0) {
340 memprintf(err, "'%s %s' expects expects an integer value (in sessions/second)", args[0], args[1]);
341 return -1;
342 }
343
344 val = strtoul(args[2], &res, 0);
345 if (*res) {
346 memprintf(err, "'%s %s' : unexpected character '%c' in integer value '%s'", args[0], args[1], *res, args[2]);
347 return -1;
348 }
349
350 if (!(proxy->cap & cap)) {
351 memprintf(err, "%s %s will be ignored because %s '%s' has no %s capability",
352 args[0], args[1], proxy_type_str(proxy), proxy->id,
353 (cap & PR_CAP_BE) ? "backend" : "frontend");
354 retval = 1;
355 }
356 else if (defpx && *tv != *td) {
357 memprintf(err, "overwriting %s %s which was already specified", args[0], args[1]);
358 retval = 1;
359 }
360
361 *tv = val;
362 return retval;
363 }
364
365 /* This function parses a "max-keep-alive-queue" statement in a proxy section.
366 * It returns -1 if there is any error, 1 for a warning, otherwise zero. If it
367 * does not return zero, it will write an error or warning message into a
368 * preallocated buffer returned at <err>. The function must be called with
369 * <args> pointing to the first command line word, with <proxy> pointing to
370 * the proxy being parsed, and <defpx> to the default proxy or NULL.
371 */
proxy_parse_max_ka_queue(char ** args,int section,struct proxy * proxy,struct proxy * defpx,const char * file,int line,char ** err)372 static int proxy_parse_max_ka_queue(char **args, int section, struct proxy *proxy,
373 struct proxy *defpx, const char *file, int line,
374 char **err)
375 {
376 int retval;
377 char *res;
378 unsigned int val;
379
380 retval = 0;
381
382 if (*args[1] == 0) {
383 memprintf(err, "'%s' expects expects an integer value (or -1 to disable)", args[0]);
384 return -1;
385 }
386
387 val = strtol(args[1], &res, 0);
388 if (*res) {
389 memprintf(err, "'%s' : unexpected character '%c' in integer value '%s'", args[0], *res, args[1]);
390 return -1;
391 }
392
393 if (!(proxy->cap & PR_CAP_BE)) {
394 memprintf(err, "%s will be ignored because %s '%s' has no backend capability",
395 args[0], proxy_type_str(proxy), proxy->id);
396 retval = 1;
397 }
398
399 /* we store <val+1> so that a user-facing value of -1 is stored as zero (default) */
400 proxy->max_ka_queue = val + 1;
401 return retval;
402 }
403
404 /* This function parses a "declare" statement in a proxy section. It returns -1
405 * if there is any error, 1 for warning, otherwise 0. If it does not return zero,
406 * it will write an error or warning message into a preallocated buffer returned
407 * at <err>. The function must be called with <args> pointing to the first command
408 * line word, with <proxy> pointing to the proxy being parsed, and <defpx> to the
409 * default proxy or NULL.
410 */
proxy_parse_declare(char ** args,int section,struct proxy * curpx,struct proxy * defpx,const char * file,int line,char ** err)411 static int proxy_parse_declare(char **args, int section, struct proxy *curpx,
412 struct proxy *defpx, const char *file, int line,
413 char **err)
414 {
415 /* Capture keyword wannot be declared in a default proxy. */
416 if (curpx == defpx) {
417 memprintf(err, "'%s' not available in default section", args[0]);
418 return -1;
419 }
420
421 /* Capture keywork is only available in frontend. */
422 if (!(curpx->cap & PR_CAP_FE)) {
423 memprintf(err, "'%s' only available in frontend or listen section", args[0]);
424 return -1;
425 }
426
427 /* Check mandatory second keyword. */
428 if (!args[1] || !*args[1]) {
429 memprintf(err, "'%s' needs a second keyword that specify the type of declaration ('capture')", args[0]);
430 return -1;
431 }
432
433 /* Actually, declare is only available for declaring capture
434 * slot, but in the future it can declare maps or variables.
435 * So, this section permits to check and switch according with
436 * the second keyword.
437 */
438 if (strcmp(args[1], "capture") == 0) {
439 char *error = NULL;
440 long len;
441 struct cap_hdr *hdr;
442
443 /* Check the next keyword. */
444 if (!args[2] || !*args[2] ||
445 (strcmp(args[2], "response") != 0 &&
446 strcmp(args[2], "request") != 0)) {
447 memprintf(err, "'%s %s' requires a direction ('request' or 'response')", args[0], args[1]);
448 return -1;
449 }
450
451 /* Check the 'len' keyword. */
452 if (!args[3] || !*args[3] || strcmp(args[3], "len") != 0) {
453 memprintf(err, "'%s %s' requires a capture length ('len')", args[0], args[1]);
454 return -1;
455 }
456
457 /* Check the length value. */
458 if (!args[4] || !*args[4]) {
459 memprintf(err, "'%s %s': 'len' requires a numeric value that represents the "
460 "capture length",
461 args[0], args[1]);
462 return -1;
463 }
464
465 /* convert the length value. */
466 len = strtol(args[4], &error, 10);
467 if (*error != '\0') {
468 memprintf(err, "'%s %s': cannot parse the length '%s'.",
469 args[0], args[1], args[3]);
470 return -1;
471 }
472
473 /* check length. */
474 if (len <= 0) {
475 memprintf(err, "length must be > 0");
476 return -1;
477 }
478
479 /* register the capture. */
480 hdr = calloc(1, sizeof(*hdr));
481 hdr->name = NULL; /* not a header capture */
482 hdr->namelen = 0;
483 hdr->len = len;
484 hdr->pool = create_pool("caphdr", hdr->len + 1, MEM_F_SHARED);
485
486 if (strcmp(args[2], "request") == 0) {
487 hdr->next = curpx->req_cap;
488 hdr->index = curpx->nb_req_cap++;
489 curpx->req_cap = hdr;
490 }
491 if (strcmp(args[2], "response") == 0) {
492 hdr->next = curpx->rsp_cap;
493 hdr->index = curpx->nb_rsp_cap++;
494 curpx->rsp_cap = hdr;
495 }
496 return 0;
497 }
498 else {
499 memprintf(err, "unknown declaration type '%s' (supports 'capture')", args[1]);
500 return -1;
501 }
502 }
503
504 /* This function inserts proxy <px> into the tree of known proxies. The proxy's
505 * name is used as the storing key so it must already have been initialized.
506 */
proxy_store_name(struct proxy * px)507 void proxy_store_name(struct proxy *px)
508 {
509 px->conf.by_name.key = px->id;
510 ebis_insert(&proxy_by_name, &px->conf.by_name);
511 }
512
513 /* Returns a pointer to the first proxy matching capabilities <cap> and id
514 * <id>. NULL is returned if no match is found. If <table> is non-zero, it
515 * only considers proxies having a table.
516 */
proxy_find_by_id(int id,int cap,int table)517 struct proxy *proxy_find_by_id(int id, int cap, int table)
518 {
519 struct eb32_node *n;
520
521 for (n = eb32_lookup(&used_proxy_id, id); n; n = eb32_next(n)) {
522 struct proxy *px = container_of(n, struct proxy, conf.id);
523
524 if (px->uuid != id)
525 break;
526
527 if ((px->cap & cap) != cap)
528 continue;
529
530 if (table && !px->table.size)
531 continue;
532
533 return px;
534 }
535 return NULL;
536 }
537
538 /* Returns a pointer to the first proxy matching either name <name>, or id
539 * <name> if <name> begins with a '#'. NULL is returned if no match is found.
540 * If <table> is non-zero, it only considers proxies having a table.
541 */
proxy_find_by_name(const char * name,int cap,int table)542 struct proxy *proxy_find_by_name(const char *name, int cap, int table)
543 {
544 struct proxy *curproxy;
545
546 if (*name == '#') {
547 curproxy = proxy_find_by_id(atoi(name + 1), cap, table);
548 if (curproxy)
549 return curproxy;
550 }
551 else {
552 struct ebpt_node *node;
553
554 for (node = ebis_lookup(&proxy_by_name, name); node; node = ebpt_next(node)) {
555 curproxy = container_of(node, struct proxy, conf.by_name);
556
557 if (strcmp(curproxy->id, name) != 0)
558 break;
559
560 if ((curproxy->cap & cap) != cap)
561 continue;
562
563 if (table && !curproxy->table.size)
564 continue;
565
566 return curproxy;
567 }
568 }
569 return NULL;
570 }
571
572 /* Finds the best match for a proxy with capabilities <cap>, name <name> and id
573 * <id>. At most one of <id> or <name> may be different provided that <cap> is
574 * valid. Either <id> or <name> may be left unspecified (0). The purpose is to
575 * find a proxy based on some information from a previous configuration, across
576 * reloads or during information exchange between peers.
577 *
578 * Names are looked up first if present, then IDs are compared if present. In
579 * case of an inexact match whatever is forced in the configuration has
580 * precedence in the following order :
581 * - 1) forced ID (proves a renaming / change of proxy type)
582 * - 2) proxy name+type (may indicate a move if ID differs)
583 * - 3) automatic ID+type (may indicate a renaming)
584 *
585 * Depending on what is found, we can end up in the following situations :
586 *
587 * name id cap | possible causes
588 * -------------+-----------------
589 * -- -- -- | nothing found
590 * -- -- ok | nothing found
591 * -- ok -- | proxy deleted, ID points to next one
592 * -- ok ok | proxy renamed, or deleted with ID pointing to next one
593 * ok -- -- | proxy deleted, but other half with same name still here (before)
594 * ok -- ok | proxy's ID changed (proxy moved in the config file)
595 * ok ok -- | proxy deleted, but other half with same name still here (after)
596 * ok ok ok | perfect match
597 *
598 * Upon return if <diff> is not NULL, it is zeroed then filled with up to 3 bits :
599 * - PR_FBM_MISMATCH_ID : proxy was found but ID differs
600 * (and ID was not zero)
601 * - PR_FBM_MISMATCH_NAME : proxy was found by ID but name differs
602 * (and name was not NULL)
603 * - PR_FBM_MISMATCH_PROXYTYPE : a proxy of different type was found with
604 * the same name and/or id
605 *
606 * Only a valid proxy is returned. If capabilities do not match, NULL is
607 * returned. The caller can check <diff> to report detailed warnings / errors,
608 * and decide whether or not to use what was found.
609 */
proxy_find_best_match(int cap,const char * name,int id,int * diff)610 struct proxy *proxy_find_best_match(int cap, const char *name, int id, int *diff)
611 {
612 struct proxy *byname;
613 struct proxy *byid;
614
615 if (!name && !id)
616 return NULL;
617
618 if (diff)
619 *diff = 0;
620
621 byname = byid = NULL;
622
623 if (name) {
624 byname = proxy_find_by_name(name, cap, 0);
625 if (byname && (!id || byname->uuid == id))
626 return byname;
627 }
628
629 /* remaining possibilities :
630 * - name not set
631 * - name set but not found
632 * - name found, but ID doesn't match.
633 */
634 if (id) {
635 byid = proxy_find_by_id(id, cap, 0);
636 if (byid) {
637 if (byname) {
638 /* id+type found, name+type found, but not all 3.
639 * ID wins only if forced, otherwise name wins.
640 */
641 if (byid->options & PR_O_FORCED_ID) {
642 if (diff)
643 *diff |= PR_FBM_MISMATCH_NAME;
644 return byid;
645 }
646 else {
647 if (diff)
648 *diff |= PR_FBM_MISMATCH_ID;
649 return byname;
650 }
651 }
652
653 /* remaining possibilities :
654 * - name not set
655 * - name set but not found
656 */
657 if (name && diff)
658 *diff |= PR_FBM_MISMATCH_NAME;
659 return byid;
660 }
661
662 /* ID not found */
663 if (byname) {
664 if (diff)
665 *diff |= PR_FBM_MISMATCH_ID;
666 return byname;
667 }
668 }
669
670 /* All remaining possibilities will lead to NULL. If we can report more
671 * detailed information to the caller about changed types and/or name,
672 * we'll do it. For example, we could detect that "listen foo" was
673 * split into "frontend foo_ft" and "backend foo_bk" if IDs are forced.
674 * - name not set, ID not found
675 * - name not found, ID not set
676 * - name not found, ID not found
677 */
678 if (!diff)
679 return NULL;
680
681 if (name) {
682 byname = proxy_find_by_name(name, 0, 0);
683 if (byname && (!id || byname->uuid == id))
684 *diff |= PR_FBM_MISMATCH_PROXYTYPE;
685 }
686
687 if (id) {
688 byid = proxy_find_by_id(id, 0, 0);
689 if (byid) {
690 if (!name)
691 *diff |= PR_FBM_MISMATCH_PROXYTYPE; /* only type changed */
692 else if (byid->options & PR_O_FORCED_ID)
693 *diff |= PR_FBM_MISMATCH_NAME | PR_FBM_MISMATCH_PROXYTYPE; /* name and type changed */
694 /* otherwise it's a different proxy that was returned */
695 }
696 }
697 return NULL;
698 }
699
700 /*
701 * This function finds a server with matching name within selected proxy.
702 * It also checks if there are more matching servers with
703 * requested name as this often leads into unexpected situations.
704 */
705
findserver(const struct proxy * px,const char * name)706 struct server *findserver(const struct proxy *px, const char *name) {
707
708 struct server *cursrv, *target = NULL;
709
710 if (!px)
711 return NULL;
712
713 for (cursrv = px->srv; cursrv; cursrv = cursrv->next) {
714 if (strcmp(cursrv->id, name))
715 continue;
716
717 if (!target) {
718 target = cursrv;
719 continue;
720 }
721
722 ha_alert("Refusing to use duplicated server '%s' found in proxy: %s!\n",
723 name, px->id);
724
725 return NULL;
726 }
727
728 return target;
729 }
730
731 /* This function checks that the designated proxy has no http directives
732 * enabled. It will output a warning if there are, and will fix some of them.
733 * It returns the number of fatal errors encountered. This should be called
734 * at the end of the configuration parsing if the proxy is not in http mode.
735 * The <file> argument is used to construct the error message.
736 */
proxy_cfg_ensure_no_http(struct proxy * curproxy)737 int proxy_cfg_ensure_no_http(struct proxy *curproxy)
738 {
739 if (curproxy->cookie_name != NULL) {
740 ha_warning("config : cookie will be ignored for %s '%s' (needs 'mode http').\n",
741 proxy_type_str(curproxy), curproxy->id);
742 }
743 if (curproxy->rsp_exp != NULL) {
744 ha_warning("config : server regular expressions will be ignored for %s '%s' (needs 'mode http').\n",
745 proxy_type_str(curproxy), curproxy->id);
746 }
747 if (curproxy->req_exp != NULL) {
748 ha_warning("config : client regular expressions will be ignored for %s '%s' (needs 'mode http').\n",
749 proxy_type_str(curproxy), curproxy->id);
750 }
751 if (curproxy->monitor_uri != NULL) {
752 ha_warning("config : monitor-uri will be ignored for %s '%s' (needs 'mode http').\n",
753 proxy_type_str(curproxy), curproxy->id);
754 }
755 if (curproxy->lbprm.algo & BE_LB_NEED_HTTP) {
756 curproxy->lbprm.algo &= ~BE_LB_ALGO;
757 curproxy->lbprm.algo |= BE_LB_ALGO_RR;
758 ha_warning("config : Layer 7 hash not possible for %s '%s' (needs 'mode http'). Falling back to round robin.\n",
759 proxy_type_str(curproxy), curproxy->id);
760 }
761 if (curproxy->to_log & (LW_REQ | LW_RESP)) {
762 curproxy->to_log &= ~(LW_REQ | LW_RESP);
763 ha_warning("parsing [%s:%d] : HTTP log/header format not usable with %s '%s' (needs 'mode http').\n",
764 curproxy->conf.lfs_file, curproxy->conf.lfs_line,
765 proxy_type_str(curproxy), curproxy->id);
766 }
767 if (curproxy->conf.logformat_string == default_http_log_format ||
768 curproxy->conf.logformat_string == clf_http_log_format) {
769 /* Note: we don't change the directive's file:line number */
770 curproxy->conf.logformat_string = default_tcp_log_format;
771 ha_warning("parsing [%s:%d] : 'option httplog' not usable with %s '%s' (needs 'mode http'). Falling back to 'option tcplog'.\n",
772 curproxy->conf.lfs_file, curproxy->conf.lfs_line,
773 proxy_type_str(curproxy), curproxy->id);
774 }
775
776 return 0;
777 }
778
779 /* Perform the most basic initialization of a proxy :
780 * memset(), list_init(*), reset_timeouts(*).
781 * Any new proxy or peer should be initialized via this function.
782 */
init_new_proxy(struct proxy * p)783 void init_new_proxy(struct proxy *p)
784 {
785 memset(p, 0, sizeof(struct proxy));
786 p->obj_type = OBJ_TYPE_PROXY;
787 p->pendconns = EB_ROOT;
788 LIST_INIT(&p->acl);
789 LIST_INIT(&p->http_req_rules);
790 LIST_INIT(&p->http_res_rules);
791 LIST_INIT(&p->block_rules);
792 LIST_INIT(&p->redirect_rules);
793 LIST_INIT(&p->mon_fail_cond);
794 LIST_INIT(&p->switching_rules);
795 LIST_INIT(&p->server_rules);
796 LIST_INIT(&p->persist_rules);
797 LIST_INIT(&p->sticking_rules);
798 LIST_INIT(&p->storersp_rules);
799 LIST_INIT(&p->tcp_req.inspect_rules);
800 LIST_INIT(&p->tcp_rep.inspect_rules);
801 LIST_INIT(&p->tcp_req.l4_rules);
802 LIST_INIT(&p->tcp_req.l5_rules);
803 LIST_INIT(&p->req_add);
804 LIST_INIT(&p->rsp_add);
805 LIST_INIT(&p->listener_queue);
806 LIST_INIT(&p->logsrvs);
807 LIST_INIT(&p->logformat);
808 LIST_INIT(&p->logformat_sd);
809 LIST_INIT(&p->format_unique_id);
810 LIST_INIT(&p->conf.bind);
811 LIST_INIT(&p->conf.listeners);
812 LIST_INIT(&p->conf.args.list);
813 LIST_INIT(&p->tcpcheck_rules);
814 LIST_INIT(&p->filter_configs);
815
816 /* Timeouts are defined as -1 */
817 proxy_reset_timeouts(p);
818 p->tcp_rep.inspect_delay = TICK_ETERNITY;
819
820 /* initial uuid is unassigned (-1) */
821 p->uuid = -1;
822
823 HA_SPIN_INIT(&p->lock);
824 }
825
826 /*
827 * This function creates all proxy sockets. It should be done very early,
828 * typically before privileges are dropped. The sockets will be registered
829 * but not added to any fd_set, in order not to loose them across the fork().
830 * The proxies also start in READY state because they all have their listeners
831 * bound.
832 *
833 * Its return value is composed from ERR_NONE, ERR_RETRYABLE and ERR_FATAL.
834 * Retryable errors will only be printed if <verbose> is not zero.
835 */
start_proxies(int verbose)836 int start_proxies(int verbose)
837 {
838 struct proxy *curproxy;
839 struct listener *listener;
840 int lerr, err = ERR_NONE;
841 int pxerr;
842 char msg[100];
843
844 for (curproxy = proxies_list; curproxy != NULL; curproxy = curproxy->next) {
845 if (curproxy->state != PR_STNEW)
846 continue; /* already initialized */
847
848 pxerr = 0;
849 list_for_each_entry(listener, &curproxy->conf.listeners, by_fe) {
850 if (listener->state != LI_ASSIGNED)
851 continue; /* already started */
852
853 lerr = listener->proto->bind(listener, msg, sizeof(msg));
854
855 /* errors are reported if <verbose> is set or if they are fatal */
856 if (verbose || (lerr & (ERR_FATAL | ERR_ABORT))) {
857 if (lerr & ERR_ALERT)
858 ha_alert("Starting %s %s: %s\n",
859 proxy_type_str(curproxy), curproxy->id, msg);
860 else if (lerr & ERR_WARN)
861 ha_warning("Starting %s %s: %s\n",
862 proxy_type_str(curproxy), curproxy->id, msg);
863 }
864
865 err |= lerr;
866 if (lerr & (ERR_ABORT | ERR_FATAL)) {
867 pxerr |= 1;
868 break;
869 }
870 else if (lerr & ERR_CODE) {
871 pxerr |= 1;
872 continue;
873 }
874 }
875
876 if (!pxerr) {
877 curproxy->state = PR_STREADY;
878 send_log(curproxy, LOG_NOTICE, "Proxy %s started.\n", curproxy->id);
879 }
880
881 if (err & ERR_ABORT)
882 break;
883 }
884
885 return err;
886 }
887
888
889 /*
890 * This is the proxy management task. It enables proxies when there are enough
891 * free streams, or stops them when the table is full. It is designed to be
892 * called as a task which is woken up upon stopping or when rate limiting must
893 * be enforced.
894 */
manage_proxy(struct task * t,void * context,unsigned short state)895 struct task *manage_proxy(struct task *t, void *context, unsigned short state)
896 {
897 struct proxy *p = context;
898 int next = TICK_ETERNITY;
899 unsigned int wait;
900
901 /* We should periodically try to enable listeners waiting for a
902 * global resource here.
903 */
904
905 /* first, let's check if we need to stop the proxy */
906 if (unlikely(stopping && p->state != PR_STSTOPPED)) {
907 int t;
908 t = tick_remain(now_ms, p->stop_time);
909 if (t == 0) {
910 ha_warning("Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
911 p->id, p->fe_counters.cum_conn, p->be_counters.cum_conn);
912 send_log(p, LOG_WARNING, "Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
913 p->id, p->fe_counters.cum_conn, p->be_counters.cum_conn);
914 stop_proxy(p);
915 /* try to free more memory */
916 pool_gc(NULL);
917 }
918 else {
919 next = tick_first(next, p->stop_time);
920 }
921 }
922
923 /* If the proxy holds a stick table, we need to purge all unused
924 * entries. These are all the ones in the table with ref_cnt == 0
925 * and all the ones in the pool used to allocate new entries. Any
926 * entry attached to an existing stream waiting for a store will
927 * be in neither list. Any entry being dumped will have ref_cnt > 0.
928 * However we protect tables that are being synced to peers.
929 */
930 if (unlikely(stopping && p->state == PR_STSTOPPED && p->table.current)) {
931 if (!p->table.syncing) {
932 stktable_trash_oldest(&p->table, p->table.current);
933 pool_gc(NULL);
934 }
935 if (p->table.current) {
936 /* some entries still remain, let's recheck in one second */
937 next = tick_first(next, tick_add(now_ms, 1000));
938 }
939 }
940
941 /* the rest below is just for frontends */
942 if (!(p->cap & PR_CAP_FE))
943 goto out;
944
945 /* check the various reasons we may find to block the frontend */
946 if (unlikely(p->feconn >= p->maxconn)) {
947 if (p->state == PR_STREADY)
948 p->state = PR_STFULL;
949 goto out;
950 }
951
952 /* OK we have no reason to block, so let's unblock if we were blocking */
953 if (p->state == PR_STFULL)
954 p->state = PR_STREADY;
955
956 if (p->fe_sps_lim &&
957 (wait = next_event_delay(&p->fe_sess_per_sec, p->fe_sps_lim, 0))) {
958 /* we're blocking because a limit was reached on the number of
959 * requests/s on the frontend. We want to re-check ASAP, which
960 * means in 1 ms before estimated expiration date, because the
961 * timer will have settled down.
962 */
963 next = tick_first(next, tick_add(now_ms, wait));
964 goto out;
965 }
966
967 /* The proxy is not limited so we can re-enable any waiting listener */
968 if (!LIST_ISEMPTY(&p->listener_queue))
969 dequeue_all_listeners(&p->listener_queue);
970 out:
971 t->expire = next;
972 task_queue(t);
973 return t;
974 }
975
976
proxy_parse_hard_stop_after(char ** args,int section_type,struct proxy * curpx,struct proxy * defpx,const char * file,int line,char ** err)977 static int proxy_parse_hard_stop_after(char **args, int section_type, struct proxy *curpx,
978 struct proxy *defpx, const char *file, int line,
979 char **err)
980 {
981 const char *res;
982
983 if (!*args[1]) {
984 memprintf(err, "'%s' expects <time> as argument.\n", args[0]);
985 return -1;
986 }
987 res = parse_time_err(args[1], &global.hard_stop_after, TIME_UNIT_MS);
988 if (res) {
989 memprintf(err, "unexpected character '%c' in argument to <%s>.\n", *res, args[0]);
990 return -1;
991 }
992 return 0;
993 }
994
hard_stop(struct task * t,void * context,unsigned short state)995 struct task *hard_stop(struct task *t, void *context, unsigned short state)
996 {
997 struct proxy *p;
998 struct stream *s;
999
1000 if (killed) {
1001 ha_warning("Some tasks resisted to hard-stop, exiting now.\n");
1002 send_log(NULL, LOG_WARNING, "Some tasks resisted to hard-stop, exiting now.\n");
1003 killed = 2;
1004 t->expire = TICK_ETERNITY;
1005 return t;
1006 }
1007
1008 ha_warning("soft-stop running for too long, performing a hard-stop.\n");
1009 send_log(NULL, LOG_WARNING, "soft-stop running for too long, performing a hard-stop.\n");
1010 p = proxies_list;
1011 while (p) {
1012 if ((p->cap & PR_CAP_FE) && (p->feconn > 0)) {
1013 ha_warning("Proxy %s hard-stopped (%d remaining conns will be closed).\n",
1014 p->id, p->feconn);
1015 send_log(p, LOG_WARNING, "Proxy %s hard-stopped (%d remaining conns will be closed).\n",
1016 p->id, p->feconn);
1017 }
1018 p = p->next;
1019 }
1020 list_for_each_entry(s, &streams, list) {
1021 stream_shutdown(s, SF_ERR_KILLED);
1022 }
1023
1024 killed = 1;
1025 t->expire = tick_add(now_ms, MS_TO_TICKS(1000));
1026 return t;
1027 }
1028
1029 /*
1030 * this function disables health-check servers so that the process will quickly be ignored
1031 * by load balancers. Note that if a proxy was already in the PAUSED state, then its grace
1032 * time will not be used since it would already not listen anymore to the socket.
1033 */
soft_stop(void)1034 void soft_stop(void)
1035 {
1036 struct proxy *p;
1037 struct peers *prs;
1038 struct task *task;
1039
1040 stopping = 1;
1041 if (tick_isset(global.hard_stop_after)) {
1042 task = task_new(MAX_THREADS_MASK);
1043 if (task) {
1044 task->process = hard_stop;
1045 task_schedule(task, tick_add(now_ms, global.hard_stop_after));
1046 }
1047 else {
1048 ha_alert("out of memory trying to allocate the hard-stop task.\n");
1049 }
1050 }
1051 p = proxies_list;
1052 tv_update_date(0,1); /* else, the old time before select will be used */
1053 while (p) {
1054 /* Zombie proxy, let's close the file descriptors */
1055 if (p->state == PR_STSTOPPED &&
1056 !LIST_ISEMPTY(&p->conf.listeners) &&
1057 LIST_ELEM(p->conf.listeners.n,
1058 struct listener *, by_fe)->state > LI_ASSIGNED) {
1059 struct listener *l;
1060 list_for_each_entry(l, &p->conf.listeners, by_fe) {
1061 if (l->state > LI_ASSIGNED)
1062 close(l->fd);
1063 l->state = LI_INIT;
1064 }
1065 }
1066
1067 if (p->state != PR_STSTOPPED) {
1068 ha_warning("Stopping %s %s in %d ms.\n", proxy_cap_str(p->cap), p->id, p->grace);
1069 send_log(p, LOG_WARNING, "Stopping %s %s in %d ms.\n", proxy_cap_str(p->cap), p->id, p->grace);
1070 p->stop_time = tick_add(now_ms, p->grace);
1071
1072 /* Note: do not wake up stopped proxies' task nor their tables'
1073 * tasks as these ones might point to already released entries.
1074 */
1075 if (p->table.size && p->table.sync_task)
1076 task_wakeup(p->table.sync_task, TASK_WOKEN_MSG);
1077
1078 if (p->task)
1079 task_wakeup(p->task, TASK_WOKEN_MSG);
1080 }
1081 p = p->next;
1082 }
1083
1084 prs = cfg_peers;
1085 while (prs) {
1086 if (prs->peers_fe)
1087 stop_proxy(prs->peers_fe);
1088 prs = prs->next;
1089 }
1090 /* signal zero is used to broadcast the "stopping" event */
1091 signal_handler(0);
1092 }
1093
1094
1095 /* Temporarily disables listening on all of the proxy's listeners. Upon
1096 * success, the proxy enters the PR_PAUSED state. If disabling at least one
1097 * listener returns an error, then the proxy state is set to PR_STERROR
1098 * because we don't know how to resume from this. The function returns 0
1099 * if it fails, or non-zero on success.
1100 */
pause_proxy(struct proxy * p)1101 int pause_proxy(struct proxy *p)
1102 {
1103 struct listener *l;
1104
1105 if (!(p->cap & PR_CAP_FE) || p->state == PR_STERROR ||
1106 p->state == PR_STSTOPPED || p->state == PR_STPAUSED)
1107 return 1;
1108
1109 ha_warning("Pausing %s %s.\n", proxy_cap_str(p->cap), p->id);
1110 send_log(p, LOG_WARNING, "Pausing %s %s.\n", proxy_cap_str(p->cap), p->id);
1111
1112 list_for_each_entry(l, &p->conf.listeners, by_fe) {
1113 if (!pause_listener(l))
1114 p->state = PR_STERROR;
1115 }
1116
1117 if (p->state == PR_STERROR) {
1118 ha_warning("%s %s failed to enter pause mode.\n", proxy_cap_str(p->cap), p->id);
1119 send_log(p, LOG_WARNING, "%s %s failed to enter pause mode.\n", proxy_cap_str(p->cap), p->id);
1120 return 0;
1121 }
1122
1123 p->state = PR_STPAUSED;
1124 return 1;
1125 }
1126
1127 /* This function makes the proxy unusable, but keeps the listening sockets
1128 * opened, so that if any process requests them, we are able to serve them.
1129 * This should only be called early, before we started accepting requests.
1130 */
zombify_proxy(struct proxy * p)1131 void zombify_proxy(struct proxy *p)
1132 {
1133 struct listener *l;
1134 struct listener *first_to_listen = NULL;
1135
1136 list_for_each_entry(l, &p->conf.listeners, by_fe) {
1137 enum li_state oldstate = l->state;
1138
1139 unbind_listener_no_close(l);
1140 if (l->state >= LI_ASSIGNED) {
1141 delete_listener(l);
1142 }
1143 /*
1144 * Pretend we're still up and running so that the fd
1145 * will be sent if asked.
1146 */
1147 l->state = LI_ZOMBIE;
1148 if (!first_to_listen && oldstate >= LI_LISTEN)
1149 first_to_listen = l;
1150 }
1151 /* Quick hack : at stop time, to know we have to close the sockets
1152 * despite the proxy being marked as stopped, make the first listener
1153 * of the listener list an active one, so that we don't have to
1154 * parse the whole list to be sure.
1155 */
1156 if (first_to_listen && LIST_ELEM(p->conf.listeners.n,
1157 struct listener *, by_fe) != first_to_listen) {
1158 LIST_DEL(&l->by_fe);
1159 LIST_ADD(&p->conf.listeners, &l->by_fe);
1160 }
1161
1162 p->state = PR_STSTOPPED;
1163 }
1164
1165 /*
1166 * This function completely stops a proxy and releases its listeners. It has
1167 * to be called when going down in order to release the ports so that another
1168 * process may bind to them. It must also be called on disabled proxies at the
1169 * end of start-up. If all listeners are closed, the proxy is set to the
1170 * PR_STSTOPPED state. The function takes the proxy's lock so it's safe to
1171 * call from multiple places.
1172 */
stop_proxy(struct proxy * p)1173 void stop_proxy(struct proxy *p)
1174 {
1175 struct listener *l;
1176 int nostop = 0;
1177
1178 HA_SPIN_LOCK(PROXY_LOCK, &p->lock);
1179
1180 list_for_each_entry(l, &p->conf.listeners, by_fe) {
1181 if (l->options & LI_O_NOSTOP) {
1182 HA_ATOMIC_ADD(&unstoppable_jobs, 1);
1183 nostop = 1;
1184 continue;
1185 }
1186 /* The master should not close an inherited FD */
1187 if (master && (l->options & LI_O_INHERITED))
1188 unbind_listener_no_close(l);
1189 else
1190 unbind_listener(l);
1191 if (l->state >= LI_ASSIGNED) {
1192 delete_listener(l);
1193 }
1194 }
1195 if (!nostop)
1196 p->state = PR_STSTOPPED;
1197
1198 HA_SPIN_UNLOCK(PROXY_LOCK, &p->lock);
1199 }
1200
1201 /* This function resumes listening on the specified proxy. It scans all of its
1202 * listeners and tries to enable them all. If any of them fails, the proxy is
1203 * put back to the paused state. It returns 1 upon success, or zero if an error
1204 * is encountered.
1205 */
resume_proxy(struct proxy * p)1206 int resume_proxy(struct proxy *p)
1207 {
1208 struct listener *l;
1209 int fail;
1210
1211 if (p->state != PR_STPAUSED)
1212 return 1;
1213
1214 ha_warning("Enabling %s %s.\n", proxy_cap_str(p->cap), p->id);
1215 send_log(p, LOG_WARNING, "Enabling %s %s.\n", proxy_cap_str(p->cap), p->id);
1216
1217 fail = 0;
1218 list_for_each_entry(l, &p->conf.listeners, by_fe) {
1219 if (!resume_listener(l)) {
1220 int port;
1221
1222 port = get_host_port(&l->addr);
1223 if (port) {
1224 ha_warning("Port %d busy while trying to enable %s %s.\n",
1225 port, proxy_cap_str(p->cap), p->id);
1226 send_log(p, LOG_WARNING, "Port %d busy while trying to enable %s %s.\n",
1227 port, proxy_cap_str(p->cap), p->id);
1228 }
1229 else {
1230 ha_warning("Bind on socket %d busy while trying to enable %s %s.\n",
1231 l->luid, proxy_cap_str(p->cap), p->id);
1232 send_log(p, LOG_WARNING, "Bind on socket %d busy while trying to enable %s %s.\n",
1233 l->luid, proxy_cap_str(p->cap), p->id);
1234 }
1235
1236 /* Another port might have been enabled. Let's stop everything. */
1237 fail = 1;
1238 break;
1239 }
1240 }
1241
1242 p->state = PR_STREADY;
1243 if (fail) {
1244 pause_proxy(p);
1245 return 0;
1246 }
1247 return 1;
1248 }
1249
1250 /*
1251 * This function temporarily disables listening so that another new instance
1252 * can start listening. It is designed to be called upon reception of a
1253 * SIGTTOU, after which either a SIGUSR1 can be sent to completely stop
1254 * the proxy, or a SIGTTIN can be sent to listen again.
1255 */
pause_proxies(void)1256 void pause_proxies(void)
1257 {
1258 int err;
1259 struct proxy *p;
1260 struct peers *prs;
1261
1262 err = 0;
1263 p = proxies_list;
1264 tv_update_date(0,1); /* else, the old time before select will be used */
1265 while (p) {
1266 err |= !pause_proxy(p);
1267 p = p->next;
1268 }
1269
1270 prs = cfg_peers;
1271 while (prs) {
1272 if (prs->peers_fe)
1273 err |= !pause_proxy(prs->peers_fe);
1274 prs = prs->next;
1275 }
1276
1277 if (err) {
1278 ha_warning("Some proxies refused to pause, performing soft stop now.\n");
1279 send_log(p, LOG_WARNING, "Some proxies refused to pause, performing soft stop now.\n");
1280 soft_stop();
1281 }
1282 }
1283
1284
1285 /*
1286 * This function reactivates listening. This can be used after a call to
1287 * sig_pause(), for example when a new instance has failed starting up.
1288 * It is designed to be called upon reception of a SIGTTIN.
1289 */
resume_proxies(void)1290 void resume_proxies(void)
1291 {
1292 int err;
1293 struct proxy *p;
1294 struct peers *prs;
1295
1296 err = 0;
1297 p = proxies_list;
1298 tv_update_date(0,1); /* else, the old time before select will be used */
1299 while (p) {
1300 err |= !resume_proxy(p);
1301 p = p->next;
1302 }
1303
1304 prs = cfg_peers;
1305 while (prs) {
1306 if (prs->peers_fe)
1307 err |= !resume_proxy(prs->peers_fe);
1308 prs = prs->next;
1309 }
1310
1311 if (err) {
1312 ha_warning("Some proxies refused to resume, a restart is probably needed to resume safe operations.\n");
1313 send_log(p, LOG_WARNING, "Some proxies refused to resume, a restart is probably needed to resume safe operations.\n");
1314 }
1315 }
1316
1317 /* Set current stream's backend to <be>. Nothing is done if the
1318 * stream already had a backend assigned, which is indicated by
1319 * s->flags & SF_BE_ASSIGNED.
1320 * All flags, stats and counters which need be updated are updated.
1321 * Returns 1 if done, 0 in case of internal error, eg: lack of resource.
1322 */
stream_set_backend(struct stream * s,struct proxy * be)1323 int stream_set_backend(struct stream *s, struct proxy *be)
1324 {
1325 if (s->flags & SF_BE_ASSIGNED)
1326 return 1;
1327
1328 if (flt_set_stream_backend(s, be) < 0)
1329 return 0;
1330
1331 s->be = be;
1332 HA_ATOMIC_UPDATE_MAX(&be->be_counters.conn_max,
1333 HA_ATOMIC_ADD(&be->beconn, 1));
1334 proxy_inc_be_ctr(be);
1335
1336 /* HTX/legacy must match */
1337 if ((s->sess->fe->options2 ^ be->options2) & PR_O2_USE_HTX)
1338 return 0;
1339
1340 /* assign new parameters to the stream from the new backend */
1341 s->si[1].flags &= ~SI_FL_INDEP_STR;
1342 if (be->options2 & PR_O2_INDEPSTR)
1343 s->si[1].flags |= SI_FL_INDEP_STR;
1344
1345 if (tick_isset(be->timeout.serverfin))
1346 s->si[1].hcto = be->timeout.serverfin;
1347
1348 /* We want to enable the backend-specific analysers except those which
1349 * were already run as part of the frontend/listener. Note that it would
1350 * be more reliable to store the list of analysers that have been run,
1351 * but what we do here is OK for now.
1352 */
1353 s->req.analysers |= be->be_req_ana & ~(strm_li(s) ? strm_li(s)->analysers : 0);
1354
1355 /* If the target backend requires HTTP processing, we have to allocate
1356 * the HTTP transaction and hdr_idx if we did not have one.
1357 */
1358 if (unlikely(!s->txn && be->http_needed)) {
1359 if (unlikely(!http_alloc_txn(s)))
1360 return 0; /* not enough memory */
1361
1362 /* and now initialize the HTTP transaction state */
1363 http_init_txn(s);
1364 }
1365
1366 /* Be sure to filter request headers if the backend is an HTTP proxy and
1367 * if there are filters attached to the stream. */
1368 if (s->be->mode == PR_MODE_HTTP && HAS_FILTERS(s))
1369 s->req.analysers |= AN_REQ_FLT_HTTP_HDRS;
1370
1371 if (s->txn) {
1372 if (be->options2 & PR_O2_RSPBUG_OK)
1373 s->txn->rsp.err_pos = -1; /* let buggy responses pass */
1374
1375 /* If we chain to an HTTP backend running a different HTTP mode, we
1376 * have to re-adjust the desired keep-alive/close mode to accommodate
1377 * both the frontend's and the backend's modes.
1378 */
1379 if (strm_fe(s)->mode == PR_MODE_HTTP && be->mode == PR_MODE_HTTP &&
1380 ((strm_fe(s)->options & PR_O_HTTP_MODE) != (be->options & PR_O_HTTP_MODE)))
1381 http_adjust_conn_mode(s, s->txn, &s->txn->req);
1382
1383 /* If an LB algorithm needs to access some pre-parsed body contents,
1384 * we must not start to forward anything until the connection is
1385 * confirmed otherwise we'll lose the pointer to these data and
1386 * prevent the hash from being doable again after a redispatch.
1387 */
1388 if (be->mode == PR_MODE_HTTP &&
1389 (be->lbprm.algo & (BE_LB_KIND | BE_LB_PARM)) == (BE_LB_KIND_HI | BE_LB_HASH_PRM))
1390 s->txn->req.flags |= HTTP_MSGF_WAIT_CONN;
1391
1392 /* we may request to parse a request body */
1393 if ((be->options & PR_O_WREQ_BODY) &&
1394 (s->txn->req.body_len || (s->txn->req.flags & HTTP_MSGF_TE_CHNK)))
1395 s->req.analysers |= AN_REQ_HTTP_BODY;
1396 }
1397
1398 s->flags |= SF_BE_ASSIGNED;
1399 if (be->options2 & PR_O2_NODELAY) {
1400 s->req.flags |= CF_NEVER_WAIT;
1401 s->res.flags |= CF_NEVER_WAIT;
1402 }
1403
1404 return 1;
1405 }
1406
1407 /* Capture a bad request or response and archive it in the proxy's structure.
1408 * It is relatively protocol-agnostic so it requires that a number of elements
1409 * are passed :
1410 * - <proxy> is the proxy where the error was detected and where the snapshot
1411 * needs to be stored
1412 * - <is_back> indicates that the error happened when receiving the response
1413 * - <other_end> is a pointer to the proxy on the other side when known
1414 * - <target> is the target of the connection, usually a server or a proxy
1415 * - <sess> is the session which experienced the error
1416 * - <ctx> may be NULL or should contain any info relevant to the protocol
1417 * - <buf> is the buffer containing the offending data
1418 * - <buf_ofs> is the position of this buffer's input data in the input
1419 * stream, starting at zero. It may be passed as zero if unknown.
1420 * - <buf_out> is the portion of <buf->data> which was already forwarded and
1421 * which precedes the buffer's input. The buffer's input starts at
1422 * buf->head + buf_out.
1423 * - <err_pos> is the pointer to the faulty byte in the buffer's input.
1424 * - <show> is the callback to use to display <ctx>. It may be NULL.
1425 */
proxy_capture_error(struct proxy * proxy,int is_back,struct proxy * other_end,enum obj_type * target,const struct session * sess,const struct buffer * buf,long buf_ofs,unsigned int buf_out,unsigned int err_pos,const union error_snapshot_ctx * ctx,void (* show)(struct buffer *,const struct error_snapshot *))1426 void proxy_capture_error(struct proxy *proxy, int is_back,
1427 struct proxy *other_end, enum obj_type *target,
1428 const struct session *sess,
1429 const struct buffer *buf, long buf_ofs,
1430 unsigned int buf_out, unsigned int err_pos,
1431 const union error_snapshot_ctx *ctx,
1432 void (*show)(struct buffer *, const struct error_snapshot *))
1433 {
1434 struct error_snapshot *es;
1435 unsigned int buf_len;
1436 int len1, len2;
1437 unsigned int ev_id;
1438
1439 ev_id = HA_ATOMIC_XADD(&error_snapshot_id, 1);
1440
1441 buf_len = b_data(buf) - buf_out;
1442
1443 es = malloc(sizeof(*es) + buf_len);
1444 if (!es)
1445 return;
1446
1447 es->buf_len = buf_len;
1448 es->ev_id = ev_id;
1449
1450 len1 = b_size(buf) - b_peek_ofs(buf, buf_out);
1451 if (len1 > buf_len)
1452 len1 = buf_len;
1453
1454 if (len1) {
1455 memcpy(es->buf, b_peek(buf, buf_out), len1);
1456 len2 = buf_len - len1;
1457 if (len2)
1458 memcpy(es->buf + len1, b_orig(buf), len2);
1459 }
1460
1461 es->buf_err = err_pos;
1462 es->when = date; // user-visible date
1463 es->srv = objt_server(target);
1464 es->oe = other_end;
1465 if (objt_conn(sess->origin))
1466 es->src = __objt_conn(sess->origin)->addr.from;
1467 else
1468 memset(&es->src, 0, sizeof(es->src));
1469
1470 es->buf_wrap = b_wrap(buf) - b_peek(buf, buf_out);
1471 es->buf_out = buf_out;
1472 es->buf_ofs = buf_ofs;
1473
1474 /* be sure to indicate the offset of the first IN byte */
1475 if (es->buf_ofs >= es->buf_len)
1476 es->buf_ofs -= es->buf_len;
1477 else
1478 es->buf_ofs = 0;
1479
1480 /* protocol-specific part now */
1481 if (ctx)
1482 es->ctx = *ctx;
1483 else
1484 memset(&es->ctx, 0, sizeof(es->ctx));
1485 es->show = show;
1486
1487 /* note: we still lock since we have to be certain that nobody is
1488 * dumping the output while we free.
1489 */
1490 HA_SPIN_LOCK(PROXY_LOCK, &proxy->lock);
1491 if (is_back) {
1492 es = HA_ATOMIC_XCHG(&proxy->invalid_rep, es);
1493 } else {
1494 es = HA_ATOMIC_XCHG(&proxy->invalid_req, es);
1495 }
1496 free(es);
1497 HA_SPIN_UNLOCK(PROXY_LOCK, &proxy->lock);
1498 }
1499
1500 /* Config keywords below */
1501
1502 static struct cfg_kw_list cfg_kws = {ILH, {
1503 { CFG_GLOBAL, "hard-stop-after", proxy_parse_hard_stop_after },
1504 { CFG_LISTEN, "timeout", proxy_parse_timeout },
1505 { CFG_LISTEN, "clitimeout", proxy_parse_timeout },
1506 { CFG_LISTEN, "contimeout", proxy_parse_timeout },
1507 { CFG_LISTEN, "srvtimeout", proxy_parse_timeout },
1508 { CFG_LISTEN, "rate-limit", proxy_parse_rate_limit },
1509 { CFG_LISTEN, "max-keep-alive-queue", proxy_parse_max_ka_queue },
1510 { CFG_LISTEN, "declare", proxy_parse_declare },
1511 { 0, NULL, NULL },
1512 }};
1513
1514 INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
1515
1516 /* Expects to find a frontend named <arg> and returns it, otherwise displays various
1517 * adequate error messages and returns NULL. This function is designed to be used by
1518 * functions requiring a frontend on the CLI.
1519 */
cli_find_frontend(struct appctx * appctx,const char * arg)1520 struct proxy *cli_find_frontend(struct appctx *appctx, const char *arg)
1521 {
1522 struct proxy *px;
1523
1524 if (!*arg) {
1525 appctx->ctx.cli.severity = LOG_ERR;
1526 appctx->ctx.cli.msg = "A frontend name is expected.\n";
1527 appctx->st0 = CLI_ST_PRINT;
1528 return NULL;
1529 }
1530
1531 px = proxy_fe_by_name(arg);
1532 if (!px) {
1533 appctx->ctx.cli.severity = LOG_ERR;
1534 appctx->ctx.cli.msg = "No such frontend.\n";
1535 appctx->st0 = CLI_ST_PRINT;
1536 return NULL;
1537 }
1538 return px;
1539 }
1540
1541 /* Expects to find a backend named <arg> and returns it, otherwise displays various
1542 * adequate error messages and returns NULL. This function is designed to be used by
1543 * functions requiring a frontend on the CLI.
1544 */
cli_find_backend(struct appctx * appctx,const char * arg)1545 struct proxy *cli_find_backend(struct appctx *appctx, const char *arg)
1546 {
1547 struct proxy *px;
1548
1549 if (!*arg) {
1550 appctx->ctx.cli.severity = LOG_ERR;
1551 appctx->ctx.cli.msg = "A backend name is expected.\n";
1552 appctx->st0 = CLI_ST_PRINT;
1553 return NULL;
1554 }
1555
1556 px = proxy_be_by_name(arg);
1557 if (!px) {
1558 appctx->ctx.cli.severity = LOG_ERR;
1559 appctx->ctx.cli.msg = "No such backend.\n";
1560 appctx->st0 = CLI_ST_PRINT;
1561 return NULL;
1562 }
1563 return px;
1564 }
1565
1566
1567 /* parse a "show servers" CLI line, returns 0 if it wants to start the dump or
1568 * 1 if it stops immediately. If an argument is specified, it will set the proxy
1569 * pointer into cli.p0 and its ID into cli.i0.
1570 */
cli_parse_show_servers(char ** args,char * payload,struct appctx * appctx,void * private)1571 static int cli_parse_show_servers(char **args, char *payload, struct appctx *appctx, void *private)
1572 {
1573 struct proxy *px;
1574
1575 /* check if a backend name has been provided */
1576 if (*args[3]) {
1577 /* read server state from local file */
1578 px = proxy_be_by_name(args[3]);
1579
1580 if (!px) {
1581 appctx->ctx.cli.severity = LOG_ERR;
1582 appctx->ctx.cli.msg = "Can't find backend.\n";
1583 appctx->st0 = CLI_ST_PRINT;
1584 return 1;
1585 }
1586 appctx->ctx.cli.p0 = px;
1587 appctx->ctx.cli.i0 = px->uuid;
1588 }
1589 return 0;
1590 }
1591
1592 /* dumps server state information for all the servers found in backend cli.p0.
1593 * These information are all the parameters which may change during HAProxy runtime.
1594 * By default, we only export to the last known server state file format.
1595 * These information can be used at next startup to recover same level of server state.
1596 * It uses the proxy pointer from cli.p0, the proxy's id from cli.i0 and the server's
1597 * pointer from cli.p1.
1598 */
dump_servers_state(struct stream_interface * si)1599 static int dump_servers_state(struct stream_interface *si)
1600 {
1601 struct appctx *appctx = __objt_appctx(si->end);
1602 struct proxy *px = appctx->ctx.cli.p0;
1603 struct server *srv;
1604 char srv_addr[INET6_ADDRSTRLEN + 1];
1605 time_t srv_time_since_last_change;
1606 int bk_f_forced_id, srv_f_forced_id;
1607 char *srvrecord;
1608
1609 /* we don't want to report any state if the backend is not enabled on this process */
1610 if (px->bind_proc && !(px->bind_proc & pid_bit))
1611 return 1;
1612
1613 if (!appctx->ctx.cli.p1)
1614 appctx->ctx.cli.p1 = px->srv;
1615
1616 for (; appctx->ctx.cli.p1 != NULL; appctx->ctx.cli.p1 = srv->next) {
1617 srv = appctx->ctx.cli.p1;
1618 srv_addr[0] = '\0';
1619
1620 switch (srv->addr.ss_family) {
1621 case AF_INET:
1622 inet_ntop(srv->addr.ss_family, &((struct sockaddr_in *)&srv->addr)->sin_addr,
1623 srv_addr, INET_ADDRSTRLEN + 1);
1624 break;
1625 case AF_INET6:
1626 inet_ntop(srv->addr.ss_family, &((struct sockaddr_in6 *)&srv->addr)->sin6_addr,
1627 srv_addr, INET6_ADDRSTRLEN + 1);
1628 break;
1629 default:
1630 memcpy(srv_addr, "-\0", 2);
1631 break;
1632 }
1633 srv_time_since_last_change = now.tv_sec - srv->last_change;
1634 bk_f_forced_id = px->options & PR_O_FORCED_ID ? 1 : 0;
1635 srv_f_forced_id = srv->flags & SRV_F_FORCED_ID ? 1 : 0;
1636
1637 srvrecord = NULL;
1638 if (srv->srvrq && srv->srvrq->name)
1639 srvrecord = srv->srvrq->name;
1640
1641 chunk_printf(&trash,
1642 "%d %s "
1643 "%d %s %s "
1644 "%d %d %d %d %ld "
1645 "%d %d %d %d %d "
1646 "%d %d %s %u %s"
1647 "\n",
1648 px->uuid, px->id,
1649 srv->puid, srv->id, srv_addr,
1650 srv->cur_state, srv->cur_admin, srv->uweight, srv->iweight, (long int)srv_time_since_last_change,
1651 srv->check.status, srv->check.result, srv->check.health, srv->check.state, srv->agent.state,
1652 bk_f_forced_id, srv_f_forced_id, srv->hostname ? srv->hostname : "-", srv->svc_port,
1653 srvrecord ? srvrecord : "-");
1654 if (ci_putchk(si_ic(si), &trash) == -1) {
1655 si_rx_room_blk(si);
1656 return 0;
1657 }
1658 }
1659 return 1;
1660 }
1661
1662 /* Parses backend list or simply use backend name provided by the user to return
1663 * states of servers to stdout. It dumps proxy <cli.p0> and stops if <cli.i0> is
1664 * non-null.
1665 */
cli_io_handler_servers_state(struct appctx * appctx)1666 static int cli_io_handler_servers_state(struct appctx *appctx)
1667 {
1668 struct stream_interface *si = appctx->owner;
1669 struct proxy *curproxy;
1670
1671 chunk_reset(&trash);
1672
1673 if (appctx->st2 == STAT_ST_INIT) {
1674 if (!appctx->ctx.cli.p0)
1675 appctx->ctx.cli.p0 = proxies_list;
1676 appctx->st2 = STAT_ST_HEAD;
1677 }
1678
1679 if (appctx->st2 == STAT_ST_HEAD) {
1680 chunk_printf(&trash, "%d\n# %s\n", SRV_STATE_FILE_VERSION, SRV_STATE_FILE_FIELD_NAMES);
1681 if (ci_putchk(si_ic(si), &trash) == -1) {
1682 si_rx_room_blk(si);
1683 return 0;
1684 }
1685 appctx->st2 = STAT_ST_INFO;
1686 }
1687
1688 /* STAT_ST_INFO */
1689 for (; appctx->ctx.cli.p0 != NULL; appctx->ctx.cli.p0 = curproxy->next) {
1690 curproxy = appctx->ctx.cli.p0;
1691 /* servers are only in backends */
1692 if (curproxy->cap & PR_CAP_BE) {
1693 if (!dump_servers_state(si))
1694 return 0;
1695 }
1696 /* only the selected proxy is dumped */
1697 if (appctx->ctx.cli.i0)
1698 break;
1699 }
1700
1701 return 1;
1702 }
1703
1704 /* Parses backend list and simply report backend names. It keeps the proxy
1705 * pointer in cli.p0.
1706 */
cli_io_handler_show_backend(struct appctx * appctx)1707 static int cli_io_handler_show_backend(struct appctx *appctx)
1708 {
1709 struct stream_interface *si = appctx->owner;
1710 struct proxy *curproxy;
1711
1712 chunk_reset(&trash);
1713
1714 if (!appctx->ctx.cli.p0) {
1715 chunk_printf(&trash, "# name\n");
1716 if (ci_putchk(si_ic(si), &trash) == -1) {
1717 si_rx_room_blk(si);
1718 return 0;
1719 }
1720 appctx->ctx.cli.p0 = proxies_list;
1721 }
1722
1723 for (; appctx->ctx.cli.p0 != NULL; appctx->ctx.cli.p0 = curproxy->next) {
1724 curproxy = appctx->ctx.cli.p0;
1725
1726 /* looking for backends only */
1727 if (!(curproxy->cap & PR_CAP_BE))
1728 continue;
1729
1730 /* we don't want to list a backend which is bound to this process */
1731 if (curproxy->bind_proc && !(curproxy->bind_proc & pid_bit))
1732 continue;
1733
1734 chunk_appendf(&trash, "%s\n", curproxy->id);
1735 if (ci_putchk(si_ic(si), &trash) == -1) {
1736 si_rx_room_blk(si);
1737 return 0;
1738 }
1739 }
1740
1741 return 1;
1742 }
1743
1744 /* Parses the "enable dynamic-cookies backend" directive, it always returns 1.
1745 *
1746 * Grabs the proxy lock and each server's lock.
1747 */
cli_parse_enable_dyncookie_backend(char ** args,char * payload,struct appctx * appctx,void * private)1748 static int cli_parse_enable_dyncookie_backend(char **args, char *payload, struct appctx *appctx, void *private)
1749 {
1750 struct proxy *px;
1751 struct server *s;
1752
1753 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1754 return 1;
1755
1756 px = cli_find_backend(appctx, args[3]);
1757 if (!px)
1758 return 1;
1759
1760 /* Note: this lock is to make sure this doesn't change while another
1761 * thread is in srv_set_dyncookie().
1762 */
1763 HA_SPIN_LOCK(PROXY_LOCK, &px->lock);
1764 px->ck_opts |= PR_CK_DYNAMIC;
1765 HA_SPIN_UNLOCK(PROXY_LOCK, &px->lock);
1766
1767 for (s = px->srv; s != NULL; s = s->next) {
1768 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
1769 srv_set_dyncookie(s);
1770 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
1771 }
1772
1773 return 1;
1774 }
1775
1776 /* Parses the "disable dynamic-cookies backend" directive, it always returns 1.
1777 *
1778 * Grabs the proxy lock and each server's lock.
1779 */
cli_parse_disable_dyncookie_backend(char ** args,char * payload,struct appctx * appctx,void * private)1780 static int cli_parse_disable_dyncookie_backend(char **args, char *payload, struct appctx *appctx, void *private)
1781 {
1782 struct proxy *px;
1783 struct server *s;
1784
1785 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1786 return 1;
1787
1788 px = cli_find_backend(appctx, args[3]);
1789 if (!px)
1790 return 1;
1791
1792 /* Note: this lock is to make sure this doesn't change while another
1793 * thread is in srv_set_dyncookie().
1794 */
1795 HA_SPIN_LOCK(PROXY_LOCK, &px->lock);
1796 px->ck_opts &= ~PR_CK_DYNAMIC;
1797 HA_SPIN_UNLOCK(PROXY_LOCK, &px->lock);
1798
1799 for (s = px->srv; s != NULL; s = s->next) {
1800 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
1801 if (!(s->flags & SRV_F_COOKIESET)) {
1802 free(s->cookie);
1803 s->cookie = NULL;
1804 }
1805 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
1806 }
1807
1808 return 1;
1809 }
1810
1811 /* Parses the "set dynamic-cookie-key backend" directive, it always returns 1.
1812 *
1813 * Grabs the proxy lock and each server's lock.
1814 */
cli_parse_set_dyncookie_key_backend(char ** args,char * payload,struct appctx * appctx,void * private)1815 static int cli_parse_set_dyncookie_key_backend(char **args, char *payload, struct appctx *appctx, void *private)
1816 {
1817 struct proxy *px;
1818 struct server *s;
1819 char *newkey;
1820
1821 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1822 return 1;
1823
1824 px = cli_find_backend(appctx, args[3]);
1825 if (!px)
1826 return 1;
1827
1828 if (!*args[4]) {
1829 appctx->ctx.cli.severity = LOG_ERR;
1830 appctx->ctx.cli.msg = "String value expected.\n";
1831 appctx->st0 = CLI_ST_PRINT;
1832 return 1;
1833 }
1834
1835 newkey = strdup(args[4]);
1836 if (!newkey) {
1837 appctx->ctx.cli.severity = LOG_ERR;
1838 appctx->ctx.cli.msg = "Failed to allocate memory.\n";
1839 appctx->st0 = CLI_ST_PRINT;
1840 return 1;
1841 }
1842
1843 /* Note: this lock is to make sure this doesn't change while another
1844 * thread is in srv_set_dyncookie().
1845 */
1846 HA_SPIN_LOCK(PROXY_LOCK, &px->lock);
1847 free(px->dyncookie_key);
1848 px->dyncookie_key = newkey;
1849 HA_SPIN_UNLOCK(PROXY_LOCK, &px->lock);
1850
1851 for (s = px->srv; s != NULL; s = s->next) {
1852 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
1853 srv_set_dyncookie(s);
1854 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
1855 }
1856
1857 return 1;
1858 }
1859
1860 /* Parses the "set maxconn frontend" directive, it always returns 1.
1861 *
1862 * Grabs the proxy lock.
1863 */
cli_parse_set_maxconn_frontend(char ** args,char * payload,struct appctx * appctx,void * private)1864 static int cli_parse_set_maxconn_frontend(char **args, char *payload, struct appctx *appctx, void *private)
1865 {
1866 struct proxy *px;
1867 struct listener *l;
1868 int v;
1869
1870 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1871 return 1;
1872
1873 px = cli_find_frontend(appctx, args[3]);
1874 if (!px)
1875 return 1;
1876
1877 if (!*args[4]) {
1878 appctx->ctx.cli.severity = LOG_ERR;
1879 appctx->ctx.cli.msg = "Integer value expected.\n";
1880 appctx->st0 = CLI_ST_PRINT;
1881 return 1;
1882 }
1883
1884 v = atoi(args[4]);
1885 if (v < 0) {
1886 appctx->ctx.cli.severity = LOG_ERR;
1887 appctx->ctx.cli.msg = "Value out of range.\n";
1888 appctx->st0 = CLI_ST_PRINT;
1889 return 1;
1890 }
1891
1892 /* OK, the value is fine, so we assign it to the proxy and to all of
1893 * its listeners. The blocked ones will be dequeued.
1894 */
1895 HA_SPIN_LOCK(PROXY_LOCK, &px->lock);
1896
1897 px->maxconn = v;
1898 list_for_each_entry(l, &px->conf.listeners, by_fe) {
1899 l->maxconn = v;
1900 if (l->state == LI_FULL)
1901 resume_listener(l);
1902 }
1903
1904 if (px->maxconn > px->feconn && !LIST_ISEMPTY(&px->listener_queue))
1905 dequeue_all_listeners(&px->listener_queue);
1906
1907 HA_SPIN_UNLOCK(PROXY_LOCK, &px->lock);
1908
1909 return 1;
1910 }
1911
1912 /* Parses the "shutdown frontend" directive, it always returns 1.
1913 *
1914 * Grabs the proxy lock.
1915 */
cli_parse_shutdown_frontend(char ** args,char * payload,struct appctx * appctx,void * private)1916 static int cli_parse_shutdown_frontend(char **args, char *payload, struct appctx *appctx, void *private)
1917 {
1918 struct proxy *px;
1919
1920 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1921 return 1;
1922
1923 px = cli_find_frontend(appctx, args[2]);
1924 if (!px)
1925 return 1;
1926
1927 if (px->state == PR_STSTOPPED) {
1928 appctx->ctx.cli.severity = LOG_NOTICE;
1929 appctx->ctx.cli.msg = "Frontend was already shut down.\n";
1930 appctx->st0 = CLI_ST_PRINT;
1931 return 1;
1932 }
1933
1934 ha_warning("Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
1935 px->id, px->fe_counters.cum_conn, px->be_counters.cum_conn);
1936 send_log(px, LOG_WARNING, "Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
1937 px->id, px->fe_counters.cum_conn, px->be_counters.cum_conn);
1938
1939 stop_proxy(px);
1940 return 1;
1941 }
1942
1943 /* Parses the "disable frontend" directive, it always returns 1.
1944 *
1945 * Grabs the proxy lock.
1946 */
cli_parse_disable_frontend(char ** args,char * payload,struct appctx * appctx,void * private)1947 static int cli_parse_disable_frontend(char **args, char *payload, struct appctx *appctx, void *private)
1948 {
1949 struct proxy *px;
1950 int ret;
1951
1952 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1953 return 1;
1954
1955 px = cli_find_frontend(appctx, args[2]);
1956 if (!px)
1957 return 1;
1958
1959 if (px->state == PR_STSTOPPED) {
1960 appctx->ctx.cli.severity = LOG_NOTICE;
1961 appctx->ctx.cli.msg = "Frontend was previously shut down, cannot disable.\n";
1962 appctx->st0 = CLI_ST_PRINT;
1963 return 1;
1964 }
1965
1966 if (px->state == PR_STPAUSED) {
1967 appctx->ctx.cli.severity = LOG_NOTICE;
1968 appctx->ctx.cli.msg = "Frontend is already disabled.\n";
1969 appctx->st0 = CLI_ST_PRINT;
1970 return 1;
1971 }
1972
1973 HA_SPIN_LOCK(PROXY_LOCK, &px->lock);
1974 ret = pause_proxy(px);
1975 HA_SPIN_UNLOCK(PROXY_LOCK, &px->lock);
1976
1977 if (!ret) {
1978 appctx->ctx.cli.severity = LOG_ERR;
1979 appctx->ctx.cli.msg = "Failed to pause frontend, check logs for precise cause.\n";
1980 appctx->st0 = CLI_ST_PRINT;
1981 return 1;
1982 }
1983 return 1;
1984 }
1985
1986 /* Parses the "enable frontend" directive, it always returns 1.
1987 *
1988 * Grabs the proxy lock.
1989 */
cli_parse_enable_frontend(char ** args,char * payload,struct appctx * appctx,void * private)1990 static int cli_parse_enable_frontend(char **args, char *payload, struct appctx *appctx, void *private)
1991 {
1992 struct proxy *px;
1993 int ret;
1994
1995 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1996 return 1;
1997
1998 px = cli_find_frontend(appctx, args[2]);
1999 if (!px)
2000 return 1;
2001
2002 if (px->state == PR_STSTOPPED) {
2003 appctx->ctx.cli.severity = LOG_ERR;
2004 appctx->ctx.cli.msg = "Frontend was previously shut down, cannot enable.\n";
2005 appctx->st0 = CLI_ST_PRINT;
2006 return 1;
2007 }
2008
2009 if (px->state != PR_STPAUSED) {
2010 appctx->ctx.cli.severity = LOG_NOTICE;
2011 appctx->ctx.cli.msg = "Frontend is already enabled.\n";
2012 appctx->st0 = CLI_ST_PRINT;
2013 return 1;
2014 }
2015
2016 HA_SPIN_LOCK(PROXY_LOCK, &px->lock);
2017 ret = resume_proxy(px);
2018 HA_SPIN_UNLOCK(PROXY_LOCK, &px->lock);
2019
2020 if (!ret) {
2021 appctx->ctx.cli.severity = LOG_ERR;
2022 appctx->ctx.cli.msg = "Failed to resume frontend, check logs for precise cause (port conflict?).\n";
2023 appctx->st0 = CLI_ST_PRINT;
2024 return 1;
2025 }
2026 return 1;
2027 }
2028
2029 /* "show errors" handler for the CLI. Returns 0 if wants to continue, 1 to stop
2030 * now.
2031 */
cli_parse_show_errors(char ** args,char * payload,struct appctx * appctx,void * private)2032 static int cli_parse_show_errors(char **args, char *payload, struct appctx *appctx, void *private)
2033 {
2034 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
2035 return 1;
2036
2037 if (*args[2]) {
2038 struct proxy *px;
2039
2040 px = proxy_find_by_name(args[2], 0, 0);
2041 if (px)
2042 appctx->ctx.errors.iid = px->uuid;
2043 else
2044 appctx->ctx.errors.iid = atoi(args[2]);
2045
2046 if (!appctx->ctx.errors.iid) {
2047 appctx->ctx.cli.severity = LOG_ERR;
2048 appctx->ctx.cli.msg = "No such proxy.\n";
2049 appctx->st0 = CLI_ST_PRINT;
2050 return 1;
2051 }
2052 }
2053 else
2054 appctx->ctx.errors.iid = -1; // dump all proxies
2055
2056 appctx->ctx.errors.flag = 0;
2057 if (strcmp(args[3], "request") == 0)
2058 appctx->ctx.errors.flag |= 4; // ignore response
2059 else if (strcmp(args[3], "response") == 0)
2060 appctx->ctx.errors.flag |= 2; // ignore request
2061 appctx->ctx.errors.px = NULL;
2062 return 0;
2063 }
2064
2065 /* This function dumps all captured errors onto the stream interface's
2066 * read buffer. It returns 0 if the output buffer is full and it needs
2067 * to be called again, otherwise non-zero.
2068 */
cli_io_handler_show_errors(struct appctx * appctx)2069 static int cli_io_handler_show_errors(struct appctx *appctx)
2070 {
2071 struct stream_interface *si = appctx->owner;
2072 extern const char *monthname[12];
2073
2074 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
2075 return 1;
2076
2077 chunk_reset(&trash);
2078
2079 if (!appctx->ctx.errors.px) {
2080 /* the function had not been called yet, let's prepare the
2081 * buffer for a response.
2082 */
2083 struct tm tm;
2084
2085 get_localtime(date.tv_sec, &tm);
2086 chunk_appendf(&trash, "Total events captured on [%02d/%s/%04d:%02d:%02d:%02d.%03d] : %u\n",
2087 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2088 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(date.tv_usec/1000),
2089 error_snapshot_id);
2090
2091 if (ci_putchk(si_ic(si), &trash) == -1)
2092 goto cant_send;
2093
2094 appctx->ctx.errors.px = proxies_list;
2095 appctx->ctx.errors.bol = 0;
2096 appctx->ctx.errors.ptr = -1;
2097 }
2098
2099 /* we have two inner loops here, one for the proxy, the other one for
2100 * the buffer.
2101 */
2102 while (appctx->ctx.errors.px) {
2103 struct error_snapshot *es;
2104
2105 HA_SPIN_LOCK(PROXY_LOCK, &appctx->ctx.errors.px->lock);
2106
2107 if ((appctx->ctx.errors.flag & 1) == 0) {
2108 es = appctx->ctx.errors.px->invalid_req;
2109 if (appctx->ctx.errors.flag & 2) // skip req
2110 goto next;
2111 }
2112 else {
2113 es = appctx->ctx.errors.px->invalid_rep;
2114 if (appctx->ctx.errors.flag & 4) // skip resp
2115 goto next;
2116 }
2117
2118 if (!es)
2119 goto next;
2120
2121 if (appctx->ctx.errors.iid >= 0 &&
2122 appctx->ctx.errors.px->uuid != appctx->ctx.errors.iid &&
2123 es->oe->uuid != appctx->ctx.errors.iid)
2124 goto next;
2125
2126 if (appctx->ctx.errors.ptr < 0) {
2127 /* just print headers now */
2128
2129 char pn[INET6_ADDRSTRLEN];
2130 struct tm tm;
2131 int port;
2132
2133 get_localtime(es->when.tv_sec, &tm);
2134 chunk_appendf(&trash, " \n[%02d/%s/%04d:%02d:%02d:%02d.%03d]",
2135 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2136 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(es->when.tv_usec/1000));
2137
2138 switch (addr_to_str(&es->src, pn, sizeof(pn))) {
2139 case AF_INET:
2140 case AF_INET6:
2141 port = get_host_port(&es->src);
2142 break;
2143 default:
2144 port = 0;
2145 }
2146
2147 switch (appctx->ctx.errors.flag & 1) {
2148 case 0:
2149 chunk_appendf(&trash,
2150 " frontend %s (#%d): invalid request\n"
2151 " backend %s (#%d)",
2152 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
2153 (es->oe->cap & PR_CAP_BE) ? es->oe->id : "<NONE>",
2154 (es->oe->cap & PR_CAP_BE) ? es->oe->uuid : -1);
2155 break;
2156 case 1:
2157 chunk_appendf(&trash,
2158 " backend %s (#%d): invalid response\n"
2159 " frontend %s (#%d)",
2160 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
2161 es->oe->id, es->oe->uuid);
2162 break;
2163 }
2164
2165 chunk_appendf(&trash,
2166 ", server %s (#%d), event #%u, src %s:%d\n"
2167 " buffer starts at %llu (including %u out), %u free,\n"
2168 " len %u, wraps at %u, error at position %u\n",
2169 es->srv ? es->srv->id : "<NONE>",
2170 es->srv ? es->srv->puid : -1,
2171 es->ev_id, pn, port,
2172 es->buf_ofs, es->buf_out,
2173 global.tune.bufsize - es->buf_out - es->buf_len,
2174 es->buf_len, es->buf_wrap, es->buf_err);
2175
2176 if (es->show)
2177 es->show(&trash, es);
2178
2179 chunk_appendf(&trash, " \n");
2180
2181 if (ci_putchk(si_ic(si), &trash) == -1)
2182 goto cant_send_unlock;
2183
2184 appctx->ctx.errors.ptr = 0;
2185 appctx->ctx.errors.ev_id = es->ev_id;
2186 }
2187
2188 if (appctx->ctx.errors.ev_id != es->ev_id) {
2189 /* the snapshot changed while we were dumping it */
2190 chunk_appendf(&trash,
2191 " WARNING! update detected on this snapshot, dump interrupted. Please re-check!\n");
2192 if (ci_putchk(si_ic(si), &trash) == -1)
2193 goto cant_send_unlock;
2194
2195 goto next;
2196 }
2197
2198 /* OK, ptr >= 0, so we have to dump the current line */
2199 while (appctx->ctx.errors.ptr < es->buf_len && appctx->ctx.errors.ptr < global.tune.bufsize) {
2200 int newptr;
2201 int newline;
2202
2203 newline = appctx->ctx.errors.bol;
2204 newptr = dump_text_line(&trash, es->buf, global.tune.bufsize, es->buf_len, &newline, appctx->ctx.errors.ptr);
2205 if (newptr == appctx->ctx.errors.ptr)
2206 goto cant_send_unlock;
2207
2208 if (ci_putchk(si_ic(si), &trash) == -1)
2209 goto cant_send_unlock;
2210
2211 appctx->ctx.errors.ptr = newptr;
2212 appctx->ctx.errors.bol = newline;
2213 };
2214 next:
2215 HA_SPIN_UNLOCK(PROXY_LOCK, &appctx->ctx.errors.px->lock);
2216 appctx->ctx.errors.bol = 0;
2217 appctx->ctx.errors.ptr = -1;
2218 appctx->ctx.errors.flag ^= 1;
2219 if (!(appctx->ctx.errors.flag & 1))
2220 appctx->ctx.errors.px = appctx->ctx.errors.px->next;
2221 }
2222
2223 /* dump complete */
2224 return 1;
2225
2226 cant_send_unlock:
2227 HA_SPIN_UNLOCK(PROXY_LOCK, &appctx->ctx.errors.px->lock);
2228 cant_send:
2229 si_rx_room_blk(si);
2230 return 0;
2231 }
2232
2233 /* register cli keywords */
2234 static struct cli_kw_list cli_kws = {{ },{
2235 { { "disable", "frontend", NULL }, "disable frontend : temporarily disable specific frontend", cli_parse_disable_frontend, NULL, NULL },
2236 { { "enable", "frontend", NULL }, "enable frontend : re-enable specific frontend", cli_parse_enable_frontend, NULL, NULL },
2237 { { "set", "maxconn", "frontend", NULL }, "set maxconn frontend : change a frontend's maxconn setting", cli_parse_set_maxconn_frontend, NULL },
2238 { { "show","servers", "state", NULL }, "show servers state [id]: dump volatile server information (for backend <id>)", cli_parse_show_servers, cli_io_handler_servers_state },
2239 { { "show", "backend", NULL }, "show backend : list backends in the current running config", NULL, cli_io_handler_show_backend },
2240 { { "shutdown", "frontend", NULL }, "shutdown frontend : stop a specific frontend", cli_parse_shutdown_frontend, NULL, NULL },
2241 { { "set", "dynamic-cookie-key", "backend", NULL }, "set dynamic-cookie-key backend : change a backend secret key for dynamic cookies", cli_parse_set_dyncookie_key_backend, NULL },
2242 { { "enable", "dynamic-cookie", "backend", NULL }, "enable dynamic-cookie backend : enable dynamic cookies on a specific backend", cli_parse_enable_dyncookie_backend, NULL },
2243 { { "disable", "dynamic-cookie", "backend", NULL }, "disable dynamic-cookie backend : disable dynamic cookies on a specific backend", cli_parse_disable_dyncookie_backend, NULL },
2244 { { "show", "errors", NULL }, "show errors : report last request and response errors for each proxy", cli_parse_show_errors, cli_io_handler_show_errors, NULL },
2245 {{},}
2246 }};
2247
2248 INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2249
2250 /*
2251 * Local variables:
2252 * c-indent-level: 8
2253 * c-basic-offset: 8
2254 * End:
2255 */
2256