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