1 /*
2  * Health-checks functions.
3  *
4  * Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
5  * Copyright 2007-2009 Krzysztof Piotr Oledzki <ole@ans.pl>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version
10  * 2 of the License, or (at your option) any later version.
11  *
12  */
13 
14 #include <assert.h>
15 #include <ctype.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <signal.h>
19 #include <stdarg.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <time.h>
24 #include <unistd.h>
25 #include <sys/resource.h>
26 #include <sys/socket.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <netinet/in.h>
30 #include <netinet/tcp.h>
31 #include <arpa/inet.h>
32 
33 #include <common/chunk.h>
34 #include <common/compat.h>
35 #include <common/config.h>
36 #include <common/mini-clist.h>
37 #include <common/standard.h>
38 #include <common/time.h>
39 #include <common/hathreads.h>
40 
41 #include <types/global.h>
42 #include <types/dns.h>
43 #include <types/stats.h>
44 
45 #include <proto/backend.h>
46 #include <proto/checks.h>
47 #include <proto/stats.h>
48 #include <proto/fd.h>
49 #include <proto/log.h>
50 #include <proto/mux_pt.h>
51 #include <proto/queue.h>
52 #include <proto/port_range.h>
53 #include <proto/proto_tcp.h>
54 #include <proto/protocol.h>
55 #include <proto/proxy.h>
56 #include <proto/server.h>
57 #include <proto/signal.h>
58 #include <proto/stream_interface.h>
59 #include <proto/task.h>
60 #include <proto/log.h>
61 #include <proto/dns.h>
62 #include <proto/proto_udp.h>
63 
64 #ifdef USE_OPENSSL
65 #include <proto/ssl_sock.h>
66 #endif /* USE_OPENSSL */
67 
68 static int httpchk_expect(struct server *s, int done);
69 static int tcpcheck_get_step_id(struct check *);
70 static char * tcpcheck_get_step_comment(struct check *, int);
71 static int tcpcheck_main(struct check *);
72 static void __event_srv_chk_w(struct conn_stream *cs);
73 static int wake_srv_chk(struct conn_stream *cs);
74 static void __event_srv_chk_r(struct conn_stream *cs);
75 
76 DECLARE_STATIC_POOL(pool_head_email_alert,   "email_alert",   sizeof(struct email_alert));
77 DECLARE_STATIC_POOL(pool_head_tcpcheck_rule, "tcpcheck_rule", sizeof(struct tcpcheck_rule));
78 
79 
80 static const struct check_status check_statuses[HCHK_STATUS_SIZE] = {
81 	[HCHK_STATUS_UNKNOWN]	= { CHK_RES_UNKNOWN,  "UNK",     "Unknown" },
82 	[HCHK_STATUS_INI]	= { CHK_RES_UNKNOWN,  "INI",     "Initializing" },
83 	[HCHK_STATUS_START]	= { /* SPECIAL STATUS*/ },
84 
85 	/* Below we have finished checks */
86 	[HCHK_STATUS_CHECKED]	= { CHK_RES_NEUTRAL,  "CHECKED", "No status change" },
87 	[HCHK_STATUS_HANA]	= { CHK_RES_FAILED,   "HANA",    "Health analyze" },
88 
89 	[HCHK_STATUS_SOCKERR]	= { CHK_RES_FAILED,   "SOCKERR", "Socket error" },
90 
91 	[HCHK_STATUS_L4OK]	= { CHK_RES_PASSED,   "L4OK",    "Layer4 check passed" },
92 	[HCHK_STATUS_L4TOUT]	= { CHK_RES_FAILED,   "L4TOUT",  "Layer4 timeout" },
93 	[HCHK_STATUS_L4CON]	= { CHK_RES_FAILED,   "L4CON",   "Layer4 connection problem" },
94 
95 	[HCHK_STATUS_L6OK]	= { CHK_RES_PASSED,   "L6OK",    "Layer6 check passed" },
96 	[HCHK_STATUS_L6TOUT]	= { CHK_RES_FAILED,   "L6TOUT",  "Layer6 timeout" },
97 	[HCHK_STATUS_L6RSP]	= { CHK_RES_FAILED,   "L6RSP",   "Layer6 invalid response" },
98 
99 	[HCHK_STATUS_L7TOUT]	= { CHK_RES_FAILED,   "L7TOUT",  "Layer7 timeout" },
100 	[HCHK_STATUS_L7RSP]	= { CHK_RES_FAILED,   "L7RSP",   "Layer7 invalid response" },
101 
102 	[HCHK_STATUS_L57DATA]	= { /* DUMMY STATUS */ },
103 
104 	[HCHK_STATUS_L7OKD]	= { CHK_RES_PASSED,   "L7OK",    "Layer7 check passed" },
105 	[HCHK_STATUS_L7OKCD]	= { CHK_RES_CONDPASS, "L7OKC",   "Layer7 check conditionally passed" },
106 	[HCHK_STATUS_L7STS]	= { CHK_RES_FAILED,   "L7STS",   "Layer7 wrong status" },
107 
108 	[HCHK_STATUS_PROCERR]	= { CHK_RES_FAILED,   "PROCERR",  "External check error" },
109 	[HCHK_STATUS_PROCTOUT]	= { CHK_RES_FAILED,   "PROCTOUT", "External check timeout" },
110 	[HCHK_STATUS_PROCOK]	= { CHK_RES_PASSED,   "PROCOK",   "External check passed" },
111 };
112 
113 const struct extcheck_env extcheck_envs[EXTCHK_SIZE] = {
114 	[EXTCHK_PATH]                   = { "PATH",                   EXTCHK_SIZE_EVAL_INIT },
115 	[EXTCHK_HAPROXY_PROXY_NAME]     = { "HAPROXY_PROXY_NAME",     EXTCHK_SIZE_EVAL_INIT },
116 	[EXTCHK_HAPROXY_PROXY_ID]       = { "HAPROXY_PROXY_ID",       EXTCHK_SIZE_EVAL_INIT },
117 	[EXTCHK_HAPROXY_PROXY_ADDR]     = { "HAPROXY_PROXY_ADDR",     EXTCHK_SIZE_EVAL_INIT },
118 	[EXTCHK_HAPROXY_PROXY_PORT]     = { "HAPROXY_PROXY_PORT",     EXTCHK_SIZE_EVAL_INIT },
119 	[EXTCHK_HAPROXY_SERVER_NAME]    = { "HAPROXY_SERVER_NAME",    EXTCHK_SIZE_EVAL_INIT },
120 	[EXTCHK_HAPROXY_SERVER_ID]      = { "HAPROXY_SERVER_ID",      EXTCHK_SIZE_EVAL_INIT },
121 	[EXTCHK_HAPROXY_SERVER_ADDR]    = { "HAPROXY_SERVER_ADDR",    EXTCHK_SIZE_ADDR },
122 	[EXTCHK_HAPROXY_SERVER_PORT]    = { "HAPROXY_SERVER_PORT",    EXTCHK_SIZE_UINT },
123 	[EXTCHK_HAPROXY_SERVER_MAXCONN] = { "HAPROXY_SERVER_MAXCONN", EXTCHK_SIZE_EVAL_INIT },
124 	[EXTCHK_HAPROXY_SERVER_CURCONN] = { "HAPROXY_SERVER_CURCONN", EXTCHK_SIZE_ULONG },
125 };
126 
127 static const struct analyze_status analyze_statuses[HANA_STATUS_SIZE] = {		/* 0: ignore, 1: error, 2: OK */
128 	[HANA_STATUS_UNKNOWN]		= { "Unknown",                         { 0, 0 }},
129 
130 	[HANA_STATUS_L4_OK]		= { "L4 successful connection",        { 2, 0 }},
131 	[HANA_STATUS_L4_ERR]		= { "L4 unsuccessful connection",      { 1, 1 }},
132 
133 	[HANA_STATUS_HTTP_OK]		= { "Correct http response",           { 0, 2 }},
134 	[HANA_STATUS_HTTP_STS]		= { "Wrong http response",             { 0, 1 }},
135 	[HANA_STATUS_HTTP_HDRRSP]	= { "Invalid http response (headers)", { 0, 1 }},
136 	[HANA_STATUS_HTTP_RSP]		= { "Invalid http response",           { 0, 1 }},
137 
138 	[HANA_STATUS_HTTP_READ_ERROR]	= { "Read error (http)",               { 0, 1 }},
139 	[HANA_STATUS_HTTP_READ_TIMEOUT]	= { "Read timeout (http)",             { 0, 1 }},
140 	[HANA_STATUS_HTTP_BROKEN_PIPE]	= { "Close from server (http)",        { 0, 1 }},
141 };
142 
143 /* checks if <err> is a real error for errno or one that can be ignored, and
144  * return 0 for these ones or <err> for real ones.
145  */
unclean_errno(int err)146 static inline int unclean_errno(int err)
147 {
148 	if (err == EAGAIN || err == EINPROGRESS ||
149 	    err == EISCONN || err == EALREADY)
150 		return 0;
151 	return err;
152 }
153 
154 /*
155  * Convert check_status code to description
156  */
get_check_status_description(short check_status)157 const char *get_check_status_description(short check_status) {
158 
159 	const char *desc;
160 
161 	if (check_status < HCHK_STATUS_SIZE)
162 		desc = check_statuses[check_status].desc;
163 	else
164 		desc = NULL;
165 
166 	if (desc && *desc)
167 		return desc;
168 	else
169 		return check_statuses[HCHK_STATUS_UNKNOWN].desc;
170 }
171 
172 /*
173  * Convert check_status code to short info
174  */
get_check_status_info(short check_status)175 const char *get_check_status_info(short check_status) {
176 
177 	const char *info;
178 
179 	if (check_status < HCHK_STATUS_SIZE)
180 		info = check_statuses[check_status].info;
181 	else
182 		info = NULL;
183 
184 	if (info && *info)
185 		return info;
186 	else
187 		return check_statuses[HCHK_STATUS_UNKNOWN].info;
188 }
189 
get_analyze_status(short analyze_status)190 const char *get_analyze_status(short analyze_status) {
191 
192 	const char *desc;
193 
194 	if (analyze_status < HANA_STATUS_SIZE)
195 		desc = analyze_statuses[analyze_status].desc;
196 	else
197 		desc = NULL;
198 
199 	if (desc && *desc)
200 		return desc;
201 	else
202 		return analyze_statuses[HANA_STATUS_UNKNOWN].desc;
203 }
204 
205 /*
206  * Set check->status, update check->duration and fill check->result with
207  * an adequate CHK_RES_* value. The new check->health is computed based
208  * on the result.
209  *
210  * Show information in logs about failed health check if server is UP
211  * or succeeded health checks if server is DOWN.
212  */
set_server_check_status(struct check * check,short status,const char * desc)213 static void set_server_check_status(struct check *check, short status, const char *desc)
214 {
215 	struct server *s = check->server;
216 	short prev_status = check->status;
217 	int report = 0;
218 
219 	if (status == HCHK_STATUS_START) {
220 		check->result = CHK_RES_UNKNOWN;	/* no result yet */
221 		check->desc[0] = '\0';
222 		check->start = now;
223 		return;
224 	}
225 
226 	if (!check->status)
227 		return;
228 
229 	if (desc && *desc) {
230 		strncpy(check->desc, desc, HCHK_DESC_LEN-1);
231 		check->desc[HCHK_DESC_LEN-1] = '\0';
232 	} else
233 		check->desc[0] = '\0';
234 
235 	check->status = status;
236 	if (check_statuses[status].result)
237 		check->result = check_statuses[status].result;
238 
239 	if (status == HCHK_STATUS_HANA)
240 		check->duration = -1;
241 	else if (!tv_iszero(&check->start)) {
242 		/* set_server_check_status() may be called more than once */
243 		check->duration = tv_ms_elapsed(&check->start, &now);
244 		tv_zero(&check->start);
245 	}
246 
247 	/* no change is expected if no state change occurred */
248 	if (check->result == CHK_RES_NEUTRAL)
249 		return;
250 
251 	/* If the check was really just sending a mail, it won't have an
252 	 * associated server, so we're done now.
253 	 */
254 	if (!s)
255 	    return;
256 	report = 0;
257 
258 	switch (check->result) {
259 	case CHK_RES_FAILED:
260 		/* Failure to connect to the agent as a secondary check should not
261 		 * cause the server to be marked down.
262 		 */
263 		if ((!(check->state & CHK_ST_AGENT) ||
264 		    (check->status >= HCHK_STATUS_L57DATA)) &&
265 		    (check->health > 0)) {
266 			HA_ATOMIC_ADD(&s->counters.failed_checks, 1);
267 			report = 1;
268 			check->health--;
269 			if (check->health < check->rise)
270 				check->health = 0;
271 		}
272 		break;
273 
274 	case CHK_RES_PASSED:
275 	case CHK_RES_CONDPASS:	/* "condpass" cannot make the first step but it OK after a "passed" */
276 		if ((check->health < check->rise + check->fall - 1) &&
277 		    (check->result == CHK_RES_PASSED || check->health > 0)) {
278 			report = 1;
279 			check->health++;
280 
281 			if (check->health >= check->rise)
282 				check->health = check->rise + check->fall - 1; /* OK now */
283 		}
284 
285 		/* clear consecutive_errors if observing is enabled */
286 		if (s->onerror)
287 			s->consecutive_errors = 0;
288 		break;
289 
290 	default:
291 		break;
292 	}
293 
294 	if (s->proxy->options2 & PR_O2_LOGHCHKS &&
295 	    (status != prev_status || report)) {
296 		chunk_printf(&trash,
297 		             "%s check for %sserver %s/%s %s%s",
298 			     (check->state & CHK_ST_AGENT) ? "Agent" : "Health",
299 		             s->flags & SRV_F_BACKUP ? "backup " : "",
300 		             s->proxy->id, s->id,
301 		             (check->result == CHK_RES_CONDPASS) ? "conditionally ":"",
302 		             (check->result >= CHK_RES_PASSED)   ? "succeeded" : "failed");
303 
304 		srv_append_status(&trash, s, check, -1, 0);
305 
306 		chunk_appendf(&trash, ", status: %d/%d %s",
307 		             (check->health >= check->rise) ? check->health - check->rise + 1 : check->health,
308 		             (check->health >= check->rise) ? check->fall : check->rise,
309 			     (check->health >= check->rise) ? (s->uweight ? "UP" : "DRAIN") : "DOWN");
310 
311 		ha_warning("%s.\n", trash.area);
312 		send_log(s->proxy, LOG_NOTICE, "%s.\n", trash.area);
313 		send_email_alert(s, LOG_INFO, "%s", trash.area);
314 	}
315 }
316 
317 /* Marks the check <check>'s server down if the current check is already failed
318  * and the server is not down yet nor in maintenance.
319  */
check_notify_failure(struct check * check)320 static void check_notify_failure(struct check *check)
321 {
322 	struct server *s = check->server;
323 
324 	/* The agent secondary check should only cause a server to be marked
325 	 * as down if check->status is HCHK_STATUS_L7STS, which indicates
326 	 * that the agent returned "fail", "stopped" or "down".
327 	 * The implication here is that failure to connect to the agent
328 	 * as a secondary check should not cause the server to be marked
329 	 * down. */
330 	if ((check->state & CHK_ST_AGENT) && check->status != HCHK_STATUS_L7STS)
331 		return;
332 
333 	if (check->health > 0)
334 		return;
335 
336 	/* We only report a reason for the check if we did not do so previously */
337 	srv_set_stopped(s, NULL, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check : NULL);
338 }
339 
340 /* Marks the check <check> as valid and tries to set its server up, provided
341  * it isn't in maintenance, it is not tracking a down server and other checks
342  * comply. The rule is simple : by default, a server is up, unless any of the
343  * following conditions is true :
344  *   - health check failed (check->health < rise)
345  *   - agent check failed (agent->health < rise)
346  *   - the server tracks a down server (track && track->state == STOPPED)
347  * Note that if the server has a slowstart, it will switch to STARTING instead
348  * of RUNNING. Also, only the health checks support the nolb mode, so the
349  * agent's success may not take the server out of this mode.
350  */
check_notify_success(struct check * check)351 static void check_notify_success(struct check *check)
352 {
353 	struct server *s = check->server;
354 
355 	if (s->next_admin & SRV_ADMF_MAINT)
356 		return;
357 
358 	if (s->track && s->track->next_state == SRV_ST_STOPPED)
359 		return;
360 
361 	if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
362 		return;
363 
364 	if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
365 		return;
366 
367 	if ((check->state & CHK_ST_AGENT) && s->next_state == SRV_ST_STOPPING)
368 		return;
369 
370 	srv_set_running(s, NULL, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check : NULL);
371 }
372 
373 /* Marks the check <check> as valid and tries to set its server into stopping mode
374  * if it was running or starting, and provided it isn't in maintenance and other
375  * checks comply. The conditions for the server to be marked in stopping mode are
376  * the same as for it to be turned up. Also, only the health checks support the
377  * nolb mode.
378  */
check_notify_stopping(struct check * check)379 static void check_notify_stopping(struct check *check)
380 {
381 	struct server *s = check->server;
382 
383 	if (s->next_admin & SRV_ADMF_MAINT)
384 		return;
385 
386 	if (check->state & CHK_ST_AGENT)
387 		return;
388 
389 	if (s->track && s->track->next_state == SRV_ST_STOPPED)
390 		return;
391 
392 	if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
393 		return;
394 
395 	if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
396 		return;
397 
398 	srv_set_stopping(s, NULL, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check : NULL);
399 }
400 
401 /* note: use health_adjust() only, which first checks that the observe mode is
402  * enabled.
403  */
__health_adjust(struct server * s,short status)404 void __health_adjust(struct server *s, short status)
405 {
406 	int failed;
407 	int expire;
408 
409 	if (s->observe >= HANA_OBS_SIZE)
410 		return;
411 
412 	if (status >= HANA_STATUS_SIZE || !analyze_statuses[status].desc)
413 		return;
414 
415 	switch (analyze_statuses[status].lr[s->observe - 1]) {
416 		case 1:
417 			failed = 1;
418 			break;
419 
420 		case 2:
421 			failed = 0;
422 			break;
423 
424 		default:
425 			return;
426 	}
427 
428 	if (!failed) {
429 		/* good: clear consecutive_errors */
430 		s->consecutive_errors = 0;
431 		return;
432 	}
433 
434 	HA_ATOMIC_ADD(&s->consecutive_errors, 1);
435 
436 	if (s->consecutive_errors < s->consecutive_errors_limit)
437 		return;
438 
439 	chunk_printf(&trash, "Detected %d consecutive errors, last one was: %s",
440 	             s->consecutive_errors, get_analyze_status(status));
441 
442 	switch (s->onerror) {
443 		case HANA_ONERR_FASTINTER:
444 		/* force fastinter - nothing to do here as all modes force it */
445 			break;
446 
447 		case HANA_ONERR_SUDDTH:
448 		/* simulate a pre-fatal failed health check */
449 			if (s->check.health > s->check.rise)
450 				s->check.health = s->check.rise + 1;
451 
452 			/* no break - fall through */
453 
454 		case HANA_ONERR_FAILCHK:
455 		/* simulate a failed health check */
456 			set_server_check_status(&s->check, HCHK_STATUS_HANA,
457 						trash.area);
458 			check_notify_failure(&s->check);
459 			break;
460 
461 		case HANA_ONERR_MARKDWN:
462 		/* mark server down */
463 			s->check.health = s->check.rise;
464 			set_server_check_status(&s->check, HCHK_STATUS_HANA,
465 						trash.area);
466 			check_notify_failure(&s->check);
467 			break;
468 
469 		default:
470 			/* write a warning? */
471 			break;
472 	}
473 
474 	s->consecutive_errors = 0;
475 	HA_ATOMIC_ADD(&s->counters.failed_hana, 1);
476 
477 	if (s->check.fastinter) {
478 		expire = tick_add(now_ms, MS_TO_TICKS(s->check.fastinter));
479 		if (s->check.task->expire > expire) {
480 			s->check.task->expire = expire;
481 			/* requeue check task with new expire */
482 			task_queue(s->check.task);
483 		}
484 	}
485 }
486 
httpchk_build_status_header(struct server * s,char * buffer,int size)487 static int httpchk_build_status_header(struct server *s, char *buffer, int size)
488 {
489 	int sv_state;
490 	int ratio;
491 	int hlen = 0;
492 	char addr[46];
493 	char port[6];
494 	const char *srv_hlt_st[7] = { "DOWN", "DOWN %d/%d",
495 				      "UP %d/%d", "UP",
496 				      "NOLB %d/%d", "NOLB",
497 				      "no check" };
498 
499 	memcpy(buffer + hlen, "X-Haproxy-Server-State: ", 24);
500 	hlen += 24;
501 
502 	if (!(s->check.state & CHK_ST_ENABLED))
503 		sv_state = 6;
504 	else if (s->cur_state != SRV_ST_STOPPED) {
505 		if (s->check.health == s->check.rise + s->check.fall - 1)
506 			sv_state = 3; /* UP */
507 		else
508 			sv_state = 2; /* going down */
509 
510 		if (s->cur_state == SRV_ST_STOPPING)
511 			sv_state += 2;
512 	} else {
513 		if (s->check.health)
514 			sv_state = 1; /* going up */
515 		else
516 			sv_state = 0; /* DOWN */
517 	}
518 
519 	hlen += snprintf(buffer + hlen, size - hlen,
520 			     srv_hlt_st[sv_state],
521 			     (s->cur_state != SRV_ST_STOPPED) ? (s->check.health - s->check.rise + 1) : (s->check.health),
522 			     (s->cur_state != SRV_ST_STOPPED) ? (s->check.fall) : (s->check.rise));
523 
524 	addr_to_str(&s->addr, addr, sizeof(addr));
525 	if (s->addr.ss_family == AF_INET || s->addr.ss_family == AF_INET6)
526 		snprintf(port, sizeof(port), "%u", s->svc_port);
527 	else
528 		*port = 0;
529 
530 	hlen += snprintf(buffer + hlen,  size - hlen, "; address=%s; port=%s; name=%s/%s; node=%s; weight=%d/%d; scur=%d/%d; qcur=%d",
531 			     addr, port, s->proxy->id, s->id,
532 			     global.node,
533 			     (s->cur_eweight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
534 			     (s->proxy->lbprm.tot_weight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
535 			     s->cur_sess, s->proxy->beconn - s->proxy->nbpend,
536 			     s->nbpend);
537 
538 	if ((s->cur_state == SRV_ST_STARTING) &&
539 	    now.tv_sec < s->last_change + s->slowstart &&
540 	    now.tv_sec >= s->last_change) {
541 		ratio = MAX(1, 100 * (now.tv_sec - s->last_change) / s->slowstart);
542 		hlen += snprintf(buffer + hlen, size - hlen, "; throttle=%d%%", ratio);
543 	}
544 
545 	buffer[hlen++] = '\r';
546 	buffer[hlen++] = '\n';
547 
548 	return hlen;
549 }
550 
551 /* Check the connection. If an error has already been reported or the socket is
552  * closed, keep errno intact as it is supposed to contain the valid error code.
553  * If no error is reported, check the socket's error queue using getsockopt().
554  * Warning, this must be done only once when returning from poll, and never
555  * after an I/O error was attempted, otherwise the error queue might contain
556  * inconsistent errors. If an error is detected, the CO_FL_ERROR is set on the
557  * socket. Returns non-zero if an error was reported, zero if everything is
558  * clean (including a properly closed socket).
559  */
retrieve_errno_from_socket(struct connection * conn)560 static int retrieve_errno_from_socket(struct connection *conn)
561 {
562 	int skerr;
563 	socklen_t lskerr = sizeof(skerr);
564 
565 	if (conn->flags & CO_FL_ERROR && (unclean_errno(errno) || !conn->ctrl))
566 		return 1;
567 
568 	if (!conn_ctrl_ready(conn))
569 		return 0;
570 
571 	if (getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) == 0)
572 		errno = skerr;
573 
574 	errno = unclean_errno(errno);
575 
576 	if (!errno) {
577 		/* we could not retrieve an error, that does not mean there is
578 		 * none. Just don't change anything and only report the prior
579 		 * error if any.
580 		 */
581 		if (conn->flags & CO_FL_ERROR)
582 			return 1;
583 		else
584 			return 0;
585 	}
586 
587 	conn->flags |= CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_SOCK_RD_SH;
588 	return 1;
589 }
590 
591 /* Try to collect as much information as possible on the connection status,
592  * and adjust the server status accordingly. It may make use of <errno_bck>
593  * if non-null when the caller is absolutely certain of its validity (eg:
594  * checked just after a syscall). If the caller doesn't have a valid errno,
595  * it can pass zero, and retrieve_errno_from_socket() will be called to try
596  * to extract errno from the socket. If no error is reported, it will consider
597  * the <expired> flag. This is intended to be used when a connection error was
598  * reported in conn->flags or when a timeout was reported in <expired>. The
599  * function takes care of not updating a server status which was already set.
600  * All situations where at least one of <expired> or CO_FL_ERROR are set
601  * produce a status.
602  */
chk_report_conn_err(struct check * check,int errno_bck,int expired)603 static void chk_report_conn_err(struct check *check, int errno_bck, int expired)
604 {
605 	struct conn_stream *cs = check->cs;
606 	struct connection *conn = cs_conn(cs);
607 	const char *err_msg;
608 	struct buffer *chk;
609 	int step;
610 	char *comment;
611 
612 	if (check->result != CHK_RES_UNKNOWN)
613 		return;
614 
615 	errno = unclean_errno(errno_bck);
616 	if (conn && errno)
617 		retrieve_errno_from_socket(conn);
618 
619 	if (conn && !(conn->flags & CO_FL_ERROR) &&
620 	    !(cs->flags & CS_FL_ERROR) && !expired)
621 		return;
622 
623 	/* we'll try to build a meaningful error message depending on the
624 	 * context of the error possibly present in conn->err_code, and the
625 	 * socket error possibly collected above. This is useful to know the
626 	 * exact step of the L6 layer (eg: SSL handshake).
627 	 */
628 	chk = get_trash_chunk();
629 
630 	if (check->type == PR_O2_TCPCHK_CHK) {
631 		step = tcpcheck_get_step_id(check);
632 		if (!step)
633 			chunk_printf(chk, " at initial connection step of tcp-check");
634 		else {
635 			chunk_printf(chk, " at step %d of tcp-check", step);
636 			/* we were looking for a string */
637 			if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_CONNECT) {
638 				if (check->last_started_step->port)
639 					chunk_appendf(chk, " (connect port %d)" ,check->last_started_step->port);
640 				else
641 					chunk_appendf(chk, " (connect)");
642 			}
643 			else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_EXPECT) {
644 				if (check->last_started_step->string)
645 					chunk_appendf(chk, " (expect string '%s')", check->last_started_step->string);
646 				else if (check->last_started_step->expect_regex)
647 					chunk_appendf(chk, " (expect regex)");
648 			}
649 			else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_SEND) {
650 				chunk_appendf(chk, " (send)");
651 			}
652 
653 			comment = tcpcheck_get_step_comment(check, step);
654 			if (comment)
655 				chunk_appendf(chk, " comment: '%s'", comment);
656 		}
657 	}
658 
659 	if (conn && conn->err_code) {
660 		if (unclean_errno(errno))
661 			chunk_printf(&trash, "%s (%s)%s", conn_err_code_str(conn), strerror(errno),
662 				     chk->area);
663 		else
664 			chunk_printf(&trash, "%s%s", conn_err_code_str(conn),
665 				     chk->area);
666 		err_msg = trash.area;
667 	}
668 	else {
669 		if (unclean_errno(errno)) {
670 			chunk_printf(&trash, "%s%s", strerror(errno),
671 				     chk->area);
672 			err_msg = trash.area;
673 		}
674 		else {
675 			err_msg = chk->area;
676 		}
677 	}
678 
679 	if (check->state & CHK_ST_PORT_MISS) {
680 		/* NOTE: this is reported after <fall> tries */
681 		chunk_printf(chk, "No port available for the TCP connection");
682 		set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
683 	}
684 
685 	if (!conn) {
686 		/* connection allocation error before the connection was established */
687 		set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
688 	}
689 	else if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L4_CONN)) == CO_FL_WAIT_L4_CONN) {
690 		/* L4 not established (yet) */
691 		if (conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR)
692 			set_server_check_status(check, HCHK_STATUS_L4CON, err_msg);
693 		else if (expired)
694 			set_server_check_status(check, HCHK_STATUS_L4TOUT, err_msg);
695 
696 		/*
697 		 * might be due to a server IP change.
698 		 * Let's trigger a DNS resolution if none are currently running.
699 		 */
700 		if (check->server)
701 			dns_trigger_resolution(check->server->dns_requester);
702 
703 	}
704 	else if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L6_CONN)) == CO_FL_WAIT_L6_CONN) {
705 		/* L6 not established (yet) */
706 		if (conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR)
707 			set_server_check_status(check, HCHK_STATUS_L6RSP, err_msg);
708 		else if (expired)
709 			set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
710 	}
711 	else if (conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR) {
712 		/* I/O error after connection was established and before we could diagnose */
713 		set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
714 	}
715 	else if (expired) {
716 		/* connection established but expired check */
717 		if (check->type == PR_O2_SSL3_CHK)
718 			set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
719 		else	/* HTTP, SMTP, ... */
720 			set_server_check_status(check, HCHK_STATUS_L7TOUT, err_msg);
721 	}
722 
723 	return;
724 }
725 
726 /* This function checks if any I/O is wanted, and if so, attempts to do so */
event_srv_chk_io(struct task * t,void * ctx,unsigned short state)727 static struct task *event_srv_chk_io(struct task *t, void *ctx, unsigned short state)
728 {
729 	struct check *check = ctx;
730 	struct conn_stream *cs = check->cs;
731 	struct email_alertq *q = container_of(check, typeof(*q), check);
732 	int ret = 0;
733 
734 	if (!(check->wait_list.events & SUB_RETRY_SEND))
735 		ret = wake_srv_chk(cs);
736 	if (ret == 0 && !(check->wait_list.events & SUB_RETRY_RECV)) {
737 		if (check->server)
738 			HA_SPIN_LOCK(SERVER_LOCK, &check->server->lock);
739 		else
740 			HA_SPIN_LOCK(EMAIL_ALERTS_LOCK, &q->lock);
741 		__event_srv_chk_r(cs);
742 		if (check->server)
743 			HA_SPIN_UNLOCK(SERVER_LOCK, &check->server->lock);
744 		else
745 			HA_SPIN_UNLOCK(EMAIL_ALERTS_LOCK, &q->lock);
746 	}
747 	return NULL;
748 }
749 
750 /* same as above but protected by the server lock.
751  *
752  * Please do NOT place any return statement in this function and only leave
753  * via the out label. NOTE THAT THIS FUNCTION DOESN'T LOCK, YOU PROBABLY WANT
754  * TO USE event_srv_chk_w() instead.
755  */
__event_srv_chk_w(struct conn_stream * cs)756 static void __event_srv_chk_w(struct conn_stream *cs)
757 {
758 	struct connection *conn = cs->conn;
759 	struct check *check = cs->data;
760 	struct server *s = check->server;
761 	struct task *t = check->task;
762 
763 	if (unlikely(check->result == CHK_RES_FAILED))
764 		goto out_wakeup;
765 
766 	if (conn->flags & CO_FL_HANDSHAKE) {
767 		if (!(conn->flags & CO_FL_ERROR))
768 			cs->conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
769 		goto out;
770 	}
771 
772 	if (retrieve_errno_from_socket(conn)) {
773 		chk_report_conn_err(check, errno, 0);
774 		goto out_wakeup;
775 	}
776 
777 	if (conn->flags & CO_FL_SOCK_WR_SH) {
778 		/* if the output is closed, we can't do anything */
779 		conn->flags |= CO_FL_ERROR;
780 		chk_report_conn_err(check, 0, 0);
781 		goto out_wakeup;
782 	}
783 
784 	/* here, we know that the connection is established. That's enough for
785 	 * a pure TCP check.
786 	 */
787 	if (!check->type)
788 		goto out_wakeup;
789 
790 	/* wake() will take care of calling tcpcheck_main() */
791 	if (check->type == PR_O2_TCPCHK_CHK)
792 		goto out;
793 
794 	if (b_data(&check->bo)) {
795 		cs->conn->mux->snd_buf(cs, &check->bo, b_data(&check->bo), 0);
796 		b_realign_if_empty(&check->bo);
797 		if (conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR) {
798 			chk_report_conn_err(check, errno, 0);
799 			goto out_wakeup;
800 		}
801 		if (b_data(&check->bo)) {
802 			conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
803 			goto out;
804 		}
805 	}
806 
807 	/* full request sent, we allow up to <timeout.check> if nonzero for a response */
808 	if (s->proxy->timeout.check) {
809 		t->expire = tick_add_ifset(now_ms, s->proxy->timeout.check);
810 		task_queue(t);
811 	}
812 	goto out;
813 
814  out_wakeup:
815 	task_wakeup(t, TASK_WOKEN_IO);
816  out:
817 	return;
818 }
819 
820 /*
821  * This function is used only for server health-checks. It handles the server's
822  * reply to an HTTP request, SSL HELLO or MySQL client Auth. It calls
823  * set_server_check_status() to update check->status, check->duration
824  * and check->result.
825 
826  * The set_server_check_status function is called with HCHK_STATUS_L7OKD if
827  * an HTTP server replies HTTP 2xx or 3xx (valid responses), if an SMTP server
828  * returns 2xx, HCHK_STATUS_L6OK if an SSL server returns at least 5 bytes in
829  * response to an SSL HELLO (the principle is that this is enough to
830  * distinguish between an SSL server and a pure TCP relay). All other cases will
831  * call it with a proper error status like HCHK_STATUS_L7STS, HCHK_STATUS_L6RSP,
832  * etc.
833  *
834  * Please do NOT place any return statement in this function and only leave
835  * via the out label.
836  *
837  * This must be called with the server lock held.
838  */
__event_srv_chk_r(struct conn_stream * cs)839 static void __event_srv_chk_r(struct conn_stream *cs)
840 {
841 	struct connection *conn = cs->conn;
842 	struct check *check = cs->data;
843 	struct server *s = check->server;
844 	struct task *t = check->task;
845 	char *desc;
846 	int done;
847 	unsigned short msglen;
848 
849 	if (unlikely(check->result == CHK_RES_FAILED))
850 		goto out_wakeup;
851 
852 	if (conn->flags & CO_FL_HANDSHAKE) {
853 		if (!(conn->flags & CO_FL_ERROR))
854 			cs->conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
855 		goto out;
856 	}
857 
858 	/* wake() will take care of calling tcpcheck_main() */
859 	if (check->type == PR_O2_TCPCHK_CHK)
860 		goto out;
861 
862 	/* Warning! Linux returns EAGAIN on SO_ERROR if data are still available
863 	 * but the connection was closed on the remote end. Fortunately, recv still
864 	 * works correctly and we don't need to do the getsockopt() on linux.
865 	 */
866 
867 	/* Set buffer to point to the end of the data already read, and check
868 	 * that there is free space remaining. If the buffer is full, proceed
869 	 * with running the checks without attempting another socket read.
870 	 */
871 
872 	done = 0;
873 
874 	cs->conn->mux->rcv_buf(cs, &check->bi, b_size(&check->bi), 0);
875 	if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH) || cs->flags & CS_FL_ERROR) {
876 		done = 1;
877 		if ((conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR) && !b_data(&check->bi)) {
878 			/* Report network errors only if we got no other data. Otherwise
879 			 * we'll let the upper layers decide whether the response is OK
880 			 * or not. It is very common that an RST sent by the server is
881 			 * reported as an error just after the last data chunk.
882 			 */
883 			chk_report_conn_err(check, errno, 0);
884 			goto out_wakeup;
885 		}
886 	}
887 
888 
889 	/* Intermediate or complete response received.
890 	 * Terminate string in b_head(&check->bi) buffer.
891 	 */
892 	if (b_data(&check->bi) < b_size(&check->bi))
893 		b_head(&check->bi)[b_data(&check->bi)] = '\0';
894 	else {
895 		b_head(&check->bi)[b_data(&check->bi) - 1] = '\0';
896 		done = 1; /* buffer full, don't wait for more data */
897 	}
898 
899 	/* Run the checks... */
900 	switch (check->type) {
901 	case PR_O2_HTTP_CHK:
902 		if (!done && b_data(&check->bi) < strlen("HTTP/1.0 000\r"))
903 			goto wait_more_data;
904 
905 		/* Check if the server speaks HTTP 1.X */
906 		if ((b_data(&check->bi) < strlen("HTTP/1.0 000\r")) ||
907 		    (memcmp(b_head(&check->bi), "HTTP/1.", 7) != 0 ||
908 		    (*(b_head(&check->bi) + 12) != ' ' && *(b_head(&check->bi) + 12) != '\r')) ||
909 		    !isdigit((unsigned char) *(b_head(&check->bi) + 9)) || !isdigit((unsigned char) *(b_head(&check->bi) + 10)) ||
910 		    !isdigit((unsigned char) *(b_head(&check->bi) + 11))) {
911 			cut_crlf(b_head(&check->bi));
912 			set_server_check_status(check, HCHK_STATUS_L7RSP, b_head(&check->bi));
913 
914 			goto out_wakeup;
915 		}
916 
917 		check->code = str2uic(b_head(&check->bi) + 9);
918 		desc = ltrim(b_head(&check->bi) + 12, ' ');
919 
920 		if ((s->proxy->options & PR_O_DISABLE404) &&
921 			 (s->next_state != SRV_ST_STOPPED) && (check->code == 404)) {
922 			/* 404 may be accepted as "stopping" only if the server was up */
923 			cut_crlf(desc);
924 			set_server_check_status(check, HCHK_STATUS_L7OKCD, desc);
925 		}
926 		else if (s->proxy->options2 & PR_O2_EXP_TYPE) {
927 			/* Run content verification check... We know we have at least 13 chars */
928 			if (!httpchk_expect(s, done))
929 				goto wait_more_data;
930 		}
931 		/* check the reply : HTTP/1.X 2xx and 3xx are OK */
932 		else if (*(b_head(&check->bi) + 9) == '2' || *(b_head(&check->bi) + 9) == '3') {
933 			cut_crlf(desc);
934 			set_server_check_status(check,  HCHK_STATUS_L7OKD, desc);
935 		}
936 		else {
937 			cut_crlf(desc);
938 			set_server_check_status(check, HCHK_STATUS_L7STS, desc);
939 		}
940 		break;
941 
942 	case PR_O2_SSL3_CHK:
943 		if (!done && b_data(&check->bi) < 5)
944 			goto wait_more_data;
945 
946 		/* Check for SSLv3 alert or handshake */
947 		if ((b_data(&check->bi) >= 5) && (*b_head(&check->bi) == 0x15 || *b_head(&check->bi) == 0x16))
948 			set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
949 		else
950 			set_server_check_status(check, HCHK_STATUS_L6RSP, NULL);
951 		break;
952 
953 	case PR_O2_SMTP_CHK:
954 		if (!done && b_data(&check->bi) < strlen("000\r"))
955 			goto wait_more_data;
956 
957 		/* do not reset when closing, servers don't like this */
958 		if (conn_ctrl_ready(cs->conn))
959 			fdtab[cs->conn->handle.fd].linger_risk = 0;
960 
961 		/* Check if the server speaks SMTP */
962 		if ((b_data(&check->bi) < strlen("000\r")) ||
963 		    (*(b_head(&check->bi) + 3) != ' ' && *(b_head(&check->bi) + 3) != '\r') ||
964 		    !isdigit((unsigned char) *b_head(&check->bi)) || !isdigit((unsigned char) *(b_head(&check->bi) + 1)) ||
965 		    !isdigit((unsigned char) *(b_head(&check->bi) + 2))) {
966 			cut_crlf(b_head(&check->bi));
967 			set_server_check_status(check, HCHK_STATUS_L7RSP, b_head(&check->bi));
968 			goto out_wakeup;
969 		}
970 
971 		check->code = str2uic(b_head(&check->bi));
972 
973 		desc = ltrim(b_head(&check->bi) + 3, ' ');
974 		cut_crlf(desc);
975 
976 		/* Check for SMTP code 2xx (should be 250) */
977 		if (*b_head(&check->bi) == '2')
978 			set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
979 		else
980 			set_server_check_status(check, HCHK_STATUS_L7STS, desc);
981 		break;
982 
983 	case PR_O2_LB_AGENT_CHK: {
984 		int status = HCHK_STATUS_CHECKED;
985 		const char *hs = NULL; /* health status      */
986 		const char *as = NULL; /* admin status */
987 		const char *ps = NULL; /* performance status */
988 		const char *cs = NULL; /* maxconn */
989 		const char *err = NULL; /* first error to report */
990 		const char *wrn = NULL; /* first warning to report */
991 		char *cmd, *p;
992 
993 		/* We're getting an agent check response. The agent could
994 		 * have been disabled in the mean time with a long check
995 		 * still pending. It is important that we ignore the whole
996 		 * response.
997 		 */
998 		if (!(check->server->agent.state & CHK_ST_ENABLED))
999 			break;
1000 
1001 		/* The agent supports strings made of a single line ended by the
1002 		 * first CR ('\r') or LF ('\n'). This line is composed of words
1003 		 * delimited by spaces (' '), tabs ('\t'), or commas (','). The
1004 		 * line may optionally contained a description of a state change
1005 		 * after a sharp ('#'), which is only considered if a health state
1006 		 * is announced.
1007 		 *
1008 		 * Words may be composed of :
1009 		 *   - a numeric weight suffixed by the percent character ('%').
1010 		 *   - a health status among "up", "down", "stopped", and "fail".
1011 		 *   - an admin status among "ready", "drain", "maint".
1012 		 *
1013 		 * These words may appear in any order. If multiple words of the
1014 		 * same category appear, the last one wins.
1015 		 */
1016 
1017 		p = b_head(&check->bi);
1018 		while (*p && *p != '\n' && *p != '\r')
1019 			p++;
1020 
1021 		if (!*p) {
1022 			if (!done)
1023 				goto wait_more_data;
1024 
1025 			/* at least inform the admin that the agent is mis-behaving */
1026 			set_server_check_status(check, check->status, "Ignoring incomplete line from agent");
1027 			break;
1028 		}
1029 
1030 		*p = 0;
1031 		cmd = b_head(&check->bi);
1032 
1033 		while (*cmd) {
1034 			/* look for next word */
1035 			if (*cmd == ' ' || *cmd == '\t' || *cmd == ',') {
1036 				cmd++;
1037 				continue;
1038 			}
1039 
1040 			if (*cmd == '#') {
1041 				/* this is the beginning of a health status description,
1042 				 * skip the sharp and blanks.
1043 				 */
1044 				cmd++;
1045 				while (*cmd == '\t' || *cmd == ' ')
1046 					cmd++;
1047 				break;
1048 			}
1049 
1050 			/* find the end of the word so that we have a null-terminated
1051 			 * word between <cmd> and <p>.
1052 			 */
1053 			p = cmd + 1;
1054 			while (*p && *p != '\t' && *p != ' ' && *p != '\n' && *p != ',')
1055 				p++;
1056 			if (*p)
1057 				*p++ = 0;
1058 
1059 			/* first, health statuses */
1060 			if (strcasecmp(cmd, "up") == 0) {
1061 				check->health = check->rise + check->fall - 1;
1062 				status = HCHK_STATUS_L7OKD;
1063 				hs = cmd;
1064 			}
1065 			else if (strcasecmp(cmd, "down") == 0) {
1066 				check->health = 0;
1067 				status = HCHK_STATUS_L7STS;
1068 				hs = cmd;
1069 			}
1070 			else if (strcasecmp(cmd, "stopped") == 0) {
1071 				check->health = 0;
1072 				status = HCHK_STATUS_L7STS;
1073 				hs = cmd;
1074 			}
1075 			else if (strcasecmp(cmd, "fail") == 0) {
1076 				check->health = 0;
1077 				status = HCHK_STATUS_L7STS;
1078 				hs = cmd;
1079 			}
1080 			/* admin statuses */
1081 			else if (strcasecmp(cmd, "ready") == 0) {
1082 				as = cmd;
1083 			}
1084 			else if (strcasecmp(cmd, "drain") == 0) {
1085 				as = cmd;
1086 			}
1087 			else if (strcasecmp(cmd, "maint") == 0) {
1088 				as = cmd;
1089 			}
1090 			/* try to parse a weight here and keep the last one */
1091 			else if (isdigit((unsigned char)*cmd) && strchr(cmd, '%') != NULL) {
1092 				ps = cmd;
1093 			}
1094 			/* try to parse a maxconn here */
1095 			else if (strncasecmp(cmd, "maxconn:", strlen("maxconn:")) == 0) {
1096 				cs = cmd;
1097 			}
1098 			else {
1099 				/* keep a copy of the first error */
1100 				if (!err)
1101 					err = cmd;
1102 			}
1103 			/* skip to next word */
1104 			cmd = p;
1105 		}
1106 		/* here, cmd points either to \0 or to the beginning of a
1107 		 * description. Skip possible leading spaces.
1108 		 */
1109 		while (*cmd == ' ' || *cmd == '\n')
1110 			cmd++;
1111 
1112 		/* First, update the admin status so that we avoid sending other
1113 		 * possibly useless warnings and can also update the health if
1114 		 * present after going back up.
1115 		 */
1116 		if (as) {
1117 			if (strcasecmp(as, "drain") == 0)
1118 				srv_adm_set_drain(check->server);
1119 			else if (strcasecmp(as, "maint") == 0)
1120 				srv_adm_set_maint(check->server);
1121 			else
1122 				srv_adm_set_ready(check->server);
1123 		}
1124 
1125 		/* now change weights */
1126 		if (ps) {
1127 			const char *msg;
1128 
1129 			msg = server_parse_weight_change_request(s, ps);
1130 			if (!wrn || !*wrn)
1131 				wrn = msg;
1132 		}
1133 
1134 		if (cs) {
1135 			const char *msg;
1136 
1137 			cs += strlen("maxconn:");
1138 
1139 			msg = server_parse_maxconn_change_request(s, cs);
1140 			if (!wrn || !*wrn)
1141 				wrn = msg;
1142 		}
1143 
1144 		/* and finally health status */
1145 		if (hs) {
1146 			/* We'll report some of the warnings and errors we have
1147 			 * here. Down reports are critical, we leave them untouched.
1148 			 * Lack of report, or report of 'UP' leaves the room for
1149 			 * ERR first, then WARN.
1150 			 */
1151 			const char *msg = cmd;
1152 			struct buffer *t;
1153 
1154 			if (!*msg || status == HCHK_STATUS_L7OKD) {
1155 				if (err && *err)
1156 					msg = err;
1157 				else if (wrn && *wrn)
1158 					msg = wrn;
1159 			}
1160 
1161 			t = get_trash_chunk();
1162 			chunk_printf(t, "via agent : %s%s%s%s",
1163 				     hs, *msg ? " (" : "",
1164 				     msg, *msg ? ")" : "");
1165 
1166 			set_server_check_status(check, status, t->area);
1167 		}
1168 		else if (err && *err) {
1169 			/* No status change but we'd like to report something odd.
1170 			 * Just report the current state and copy the message.
1171 			 */
1172 			chunk_printf(&trash, "agent reports an error : %s", err);
1173 			set_server_check_status(check, status/*check->status*/,
1174                                                 trash.area);
1175 
1176 		}
1177 		else if (wrn && *wrn) {
1178 			/* No status change but we'd like to report something odd.
1179 			 * Just report the current state and copy the message.
1180 			 */
1181 			chunk_printf(&trash, "agent warns : %s", wrn);
1182 			set_server_check_status(check, status/*check->status*/,
1183                                                 trash.area);
1184 		}
1185 		else
1186 			set_server_check_status(check, status, NULL);
1187 		break;
1188 	}
1189 
1190 	case PR_O2_PGSQL_CHK:
1191 		if (!done && b_data(&check->bi) < 9)
1192 			goto wait_more_data;
1193 
1194 		/* do not reset when closing, servers don't like this */
1195 		if (conn_ctrl_ready(cs->conn))
1196 			fdtab[cs->conn->handle.fd].linger_risk = 0;
1197 
1198 		if (b_head(&check->bi)[0] == 'R') {
1199 			set_server_check_status(check, HCHK_STATUS_L7OKD, "PostgreSQL server is ok");
1200 		}
1201 		else {
1202 			if ((b_head(&check->bi)[0] == 'E') && (b_head(&check->bi)[5]!=0) && (b_head(&check->bi)[6]!=0))
1203 				desc = &b_head(&check->bi)[6];
1204 			else
1205 				desc = "PostgreSQL unknown error";
1206 
1207 			set_server_check_status(check, HCHK_STATUS_L7STS, desc);
1208 		}
1209 		break;
1210 
1211 	case PR_O2_REDIS_CHK:
1212 		if (!done && b_data(&check->bi) < 7)
1213 			goto wait_more_data;
1214 
1215 		if (strcmp(b_head(&check->bi), "+PONG\r\n") == 0) {
1216 			set_server_check_status(check, HCHK_STATUS_L7OKD, "Redis server is ok");
1217 		}
1218 		else {
1219 			set_server_check_status(check, HCHK_STATUS_L7STS, b_head(&check->bi));
1220 		}
1221 		break;
1222 
1223 	case PR_O2_MYSQL_CHK:
1224 		if (!done && b_data(&check->bi) < 5)
1225 			goto wait_more_data;
1226 
1227 		/* do not reset when closing, servers don't like this */
1228 		if (conn_ctrl_ready(cs->conn))
1229 			fdtab[cs->conn->handle.fd].linger_risk = 0;
1230 
1231 		if (s->proxy->check_len == 0) { // old mode
1232 			if (*(b_head(&check->bi) + 4) != '\xff') {
1233 				/* We set the MySQL Version in description for information purpose
1234 				 * FIXME : it can be cool to use MySQL Version for other purpose,
1235 				 * like mark as down old MySQL server.
1236 				 */
1237 				if (b_data(&check->bi) > 51) {
1238 					desc = ltrim(b_head(&check->bi) + 5, ' ');
1239 					set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
1240 				}
1241 				else {
1242 					if (!done)
1243 						goto wait_more_data;
1244 
1245 					/* it seems we have a OK packet but without a valid length,
1246 					 * it must be a protocol error
1247 					 */
1248 					set_server_check_status(check, HCHK_STATUS_L7RSP, b_head(&check->bi));
1249 				}
1250 			}
1251 			else {
1252 				/* An error message is attached in the Error packet */
1253 				desc = ltrim(b_head(&check->bi) + 7, ' ');
1254 				set_server_check_status(check, HCHK_STATUS_L7STS, desc);
1255 			}
1256 		} else {
1257 			unsigned int first_packet_len = ((unsigned int) *b_head(&check->bi)) +
1258 			                                (((unsigned int) *(b_head(&check->bi) + 1)) << 8) +
1259 			                                (((unsigned int) *(b_head(&check->bi) + 2)) << 16);
1260 
1261 			if (b_data(&check->bi) == first_packet_len + 4) {
1262 				/* MySQL Error packet always begin with field_count = 0xff */
1263 				if (*(b_head(&check->bi) + 4) != '\xff') {
1264 					/* We have only one MySQL packet and it is a Handshake Initialization packet
1265 					* but we need to have a second packet to know if it is alright
1266 					*/
1267 					if (!done && b_data(&check->bi) < first_packet_len + 5)
1268 						goto wait_more_data;
1269 				}
1270 				else {
1271 					/* We have only one packet and it is an Error packet,
1272 					* an error message is attached, so we can display it
1273 					*/
1274 					desc = &b_head(&check->bi)[7];
1275 					//ha_warning("onlyoneERR: %s\n", desc);
1276 					set_server_check_status(check, HCHK_STATUS_L7STS, desc);
1277 				}
1278 			} else if (b_data(&check->bi) > first_packet_len + 4) {
1279 				unsigned int second_packet_len = ((unsigned int) *(b_head(&check->bi) + first_packet_len + 4)) +
1280 				                                 (((unsigned int) *(b_head(&check->bi) + first_packet_len + 5)) << 8) +
1281 				                                 (((unsigned int) *(b_head(&check->bi) + first_packet_len + 6)) << 16);
1282 
1283 				if (b_data(&check->bi) == first_packet_len + 4 + second_packet_len + 4 ) {
1284 					/* We have 2 packets and that's good */
1285 					/* Check if the second packet is a MySQL Error packet or not */
1286 					if (*(b_head(&check->bi) + first_packet_len + 8) != '\xff') {
1287 						/* No error packet */
1288 						/* We set the MySQL Version in description for information purpose */
1289 						desc = &b_head(&check->bi)[5];
1290 						//ha_warning("2packetOK: %s\n", desc);
1291 						set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
1292 					}
1293 					else {
1294 						/* An error message is attached in the Error packet
1295 						* so we can display it ! :)
1296 						*/
1297 						desc = &b_head(&check->bi)[first_packet_len+11];
1298 						//ha_warning("2packetERR: %s\n", desc);
1299 						set_server_check_status(check, HCHK_STATUS_L7STS, desc);
1300 					}
1301 				}
1302 			}
1303 			else {
1304 				if (!done)
1305 					goto wait_more_data;
1306 
1307 				/* it seems we have a Handshake Initialization packet but without a valid length,
1308 				 * it must be a protocol error
1309 				 */
1310 				desc = &b_head(&check->bi)[5];
1311 				//ha_warning("protoerr: %s\n", desc);
1312 				set_server_check_status(check, HCHK_STATUS_L7RSP, desc);
1313 			}
1314 		}
1315 		break;
1316 
1317 	case PR_O2_LDAP_CHK:
1318 		if (!done && b_data(&check->bi) < 14)
1319 			goto wait_more_data;
1320 
1321 		/* Check if the server speaks LDAP (ASN.1/BER)
1322 		 * http://en.wikipedia.org/wiki/Basic_Encoding_Rules
1323 		 * http://tools.ietf.org/html/rfc4511
1324 		 */
1325 
1326 		/* http://tools.ietf.org/html/rfc4511#section-4.1.1
1327 		 *   LDAPMessage: 0x30: SEQUENCE
1328 		 */
1329 		if ((b_data(&check->bi) < 14) || (*(b_head(&check->bi)) != '\x30')) {
1330 			set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
1331 		}
1332 		else {
1333 			 /* size of LDAPMessage */
1334 			msglen = (*(b_head(&check->bi) + 1) & 0x80) ? (*(b_head(&check->bi) + 1) & 0x7f) : 0;
1335 
1336 			/* http://tools.ietf.org/html/rfc4511#section-4.2.2
1337 			 *   messageID: 0x02 0x01 0x01: INTEGER 1
1338 			 *   protocolOp: 0x61: bindResponse
1339 			 */
1340 			if ((msglen > 2) ||
1341 			    (memcmp(b_head(&check->bi) + 2 + msglen, "\x02\x01\x01\x61", 4) != 0)) {
1342 				set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
1343 				goto out_wakeup;
1344 			}
1345 
1346 			/* size of bindResponse */
1347 			msglen += (*(b_head(&check->bi) + msglen + 6) & 0x80) ? (*(b_head(&check->bi) + msglen + 6) & 0x7f) : 0;
1348 
1349 			/* http://tools.ietf.org/html/rfc4511#section-4.1.9
1350 			 *   ldapResult: 0x0a 0x01: ENUMERATION
1351 			 */
1352 			if ((msglen > 4) ||
1353 			    (memcmp(b_head(&check->bi) + 7 + msglen, "\x0a\x01", 2) != 0)) {
1354 				set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
1355 				goto out_wakeup;
1356 			}
1357 
1358 			/* http://tools.ietf.org/html/rfc4511#section-4.1.9
1359 			 *   resultCode
1360 			 */
1361 			check->code = *(b_head(&check->bi) + msglen + 9);
1362 			if (check->code) {
1363 				set_server_check_status(check, HCHK_STATUS_L7STS, "See RFC: http://tools.ietf.org/html/rfc4511#section-4.1.9");
1364 			} else {
1365 				set_server_check_status(check, HCHK_STATUS_L7OKD, "Success");
1366 			}
1367 		}
1368 		break;
1369 
1370 	case PR_O2_SPOP_CHK: {
1371 		unsigned int framesz;
1372 		char	     err[HCHK_DESC_LEN];
1373 
1374 		if (!done && b_data(&check->bi) < 4)
1375 			goto wait_more_data;
1376 
1377 		memcpy(&framesz, b_head(&check->bi), 4);
1378 		framesz = ntohl(framesz);
1379 
1380 		if (!done && b_data(&check->bi) < (4+framesz))
1381 		    goto wait_more_data;
1382 
1383 		if (!spoe_handle_healthcheck_response(b_head(&check->bi)+4, framesz, err, HCHK_DESC_LEN-1))
1384 			set_server_check_status(check, HCHK_STATUS_L7OKD, "SPOA server is ok");
1385 		else
1386 			set_server_check_status(check, HCHK_STATUS_L7STS, err);
1387 		break;
1388 	}
1389 
1390 	default:
1391 		/* for other checks (eg: pure TCP), delegate to the main task */
1392 		break;
1393 	} /* switch */
1394 
1395  out_wakeup:
1396 	/* collect possible new errors */
1397 	if (conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR)
1398 		chk_report_conn_err(check, 0, 0);
1399 
1400 	/* Reset the check buffer... */
1401 	*b_head(&check->bi) = '\0';
1402 	b_reset(&check->bi);
1403 
1404 	/* Close the connection... We still attempt to nicely close if,
1405 	 * for instance, SSL needs to send a "close notify." Later, we perform
1406 	 * a hard close and reset the connection if some data are pending,
1407 	 * otherwise we end up with many TIME_WAITs and eat all the source port
1408 	 * range quickly.  To avoid sending RSTs all the time, we first try to
1409 	 * drain pending data.
1410 	 */
1411 	/* Call cs_shutr() first, to add the CO_FL_SOCK_RD_SH flag on the
1412 	 * connection, to make sure cs_shutw() will not lead to a shutdown()
1413 	 * that would provoke TIME_WAITs.
1414 	 */
1415 	cs_shutr(cs, CS_SHR_DRAIN);
1416 	cs_shutw(cs, CS_SHW_NORMAL);
1417 
1418 	/* OK, let's not stay here forever */
1419 	if (check->result == CHK_RES_FAILED)
1420 		conn->flags |= CO_FL_ERROR;
1421 
1422 	task_wakeup(t, TASK_WOKEN_IO);
1423 out:
1424 	return;
1425 
1426  wait_more_data:
1427 	cs->conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
1428         goto out;
1429 }
1430 
1431 /*
1432  * This function is used only for server health-checks. It handles connection
1433  * status updates including errors. If necessary, it wakes the check task up.
1434  * It returns 0 on normal cases, <0 if at least one close() has happened on the
1435  * connection (eg: reconnect).
1436  */
wake_srv_chk(struct conn_stream * cs)1437 static int wake_srv_chk(struct conn_stream *cs)
1438 {
1439 	struct connection *conn = cs->conn;
1440 	struct check *check = cs->data;
1441 	struct email_alertq *q = container_of(check, typeof(*q), check);
1442 	int ret = 0;
1443 
1444 	if (check->server)
1445 		HA_SPIN_LOCK(SERVER_LOCK, &check->server->lock);
1446 	else
1447 		HA_SPIN_LOCK(EMAIL_ALERTS_LOCK, &q->lock);
1448 
1449 	/* we may have to make progress on the TCP checks */
1450 	if (check->type == PR_O2_TCPCHK_CHK) {
1451 		ret = tcpcheck_main(check);
1452 		cs = check->cs;
1453 		conn = cs->conn;
1454 	} else if (!(check->wait_list.events & SUB_RETRY_SEND))
1455 		__event_srv_chk_w(cs);
1456 
1457 	if (unlikely(conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR)) {
1458 		/* We may get error reports bypassing the I/O handlers, typically
1459 		 * the case when sending a pure TCP check which fails, then the I/O
1460 		 * handlers above are not called. This is completely handled by the
1461 		 * main processing task so let's simply wake it up. If we get here,
1462 		 * we expect errno to still be valid.
1463 		 */
1464 		chk_report_conn_err(check, errno, 0);
1465 		task_wakeup(check->task, TASK_WOKEN_IO);
1466 	}
1467 	else if (!(conn->flags & CO_FL_HANDSHAKE) && !check->type) {
1468 		/* we may get here if only a connection probe was required : we
1469 		 * don't have any data to send nor anything expected in response,
1470 		 * so the completion of the connection establishment is enough.
1471 		 */
1472 		task_wakeup(check->task, TASK_WOKEN_IO);
1473 	}
1474 
1475 	if (check->result != CHK_RES_UNKNOWN) {
1476 		/* Check complete or aborted. If connection not yet closed do it
1477 		 * now and wake the check task up to be sure the result is
1478 		 * handled ASAP. */
1479 		conn_sock_drain(conn);
1480 		cs_close(cs);
1481 		ret = -1;
1482 		/* We may have been scheduled to run, and the
1483 		 * I/O handler expects to have a cs, so remove
1484 		 * the tasklet
1485 		 */
1486 		task_remove_from_tasklet_list((struct task *)check->wait_list.task);
1487 		task_wakeup(check->task, TASK_WOKEN_IO);
1488 	}
1489 
1490 	if (check->server)
1491 		HA_SPIN_UNLOCK(SERVER_LOCK, &check->server->lock);
1492 	else
1493 		HA_SPIN_UNLOCK(EMAIL_ALERTS_LOCK, &q->lock);
1494 
1495 	/* if a connection got replaced, we must absolutely prevent the connection
1496 	 * handler from touching its fd, and perform the FD polling updates ourselves
1497 	 */
1498 	if (ret < 0)
1499 		conn_cond_update_polling(conn);
1500 
1501 	return ret;
1502 }
1503 
1504 struct data_cb check_conn_cb = {
1505 	.wake = wake_srv_chk,
1506 	.name = "CHCK",
1507 };
1508 
1509 /*
1510  * updates the server's weight during a warmup stage. Once the final weight is
1511  * reached, the task automatically stops. Note that any server status change
1512  * must have updated s->last_change accordingly.
1513  */
server_warmup(struct task * t,void * context,unsigned short state)1514 static struct task *server_warmup(struct task *t, void *context, unsigned short state)
1515 {
1516 	struct server *s = context;
1517 
1518 	/* by default, plan on stopping the task */
1519 	t->expire = TICK_ETERNITY;
1520 	if ((s->next_admin & SRV_ADMF_MAINT) ||
1521 	    (s->next_state != SRV_ST_STARTING))
1522 		return t;
1523 
1524 	HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
1525 
1526 	/* recalculate the weights and update the state */
1527 	server_recalc_eweight(s, 1);
1528 
1529 	/* probably that we can refill this server with a bit more connections */
1530 	pendconn_grab_from_px(s);
1531 
1532 	HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
1533 
1534 	/* get back there in 1 second or 1/20th of the slowstart interval,
1535 	 * whichever is greater, resulting in small 5% steps.
1536 	 */
1537 	if (s->next_state == SRV_ST_STARTING)
1538 		t->expire = tick_add(now_ms, MS_TO_TICKS(MAX(1000, s->slowstart / 20)));
1539 	return t;
1540 }
1541 
1542 /* returns the first NON-COMMENT tcp-check rule from list <list> or NULL if
1543  * none was found.
1544  */
get_first_tcpcheck_rule(struct list * list)1545 static struct tcpcheck_rule *get_first_tcpcheck_rule(struct list *list)
1546 {
1547 	struct tcpcheck_rule *r;
1548 
1549 	list_for_each_entry(r, list, list) {
1550 		if (r->action != TCPCHK_ACT_COMMENT)
1551 			return r;
1552 	}
1553 	return NULL;
1554 }
1555 
1556 /*
1557  * establish a server health-check that makes use of a connection.
1558  *
1559  * It can return one of :
1560  *  - SF_ERR_NONE if everything's OK and tcpcheck_main() was not called
1561  *  - SF_ERR_UP if if everything's OK and tcpcheck_main() was called
1562  *  - SF_ERR_SRVTO if there are no more servers
1563  *  - SF_ERR_SRVCL if the connection was refused by the server
1564  *  - SF_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1565  *  - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1566  *  - SF_ERR_INTERNAL for any other purely internal errors
1567  *  - SF_ERR_CHK_PORT if no port could be found to run a health check on an AF_INET* socket
1568  * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
1569  * Note that we try to prevent the network stack from sending the ACK during the
1570  * connect() when a pure TCP check is used (without PROXY protocol).
1571  */
connect_conn_chk(struct task * t)1572 static int connect_conn_chk(struct task *t)
1573 {
1574 	struct check *check = t->context;
1575 	struct server *s = check->server;
1576 	struct conn_stream *cs = check->cs;
1577 	struct connection *conn = cs_conn(cs);
1578 	struct protocol *proto;
1579 	struct tcpcheck_rule *tcp_rule = NULL;
1580 	int ret;
1581 	int quickack;
1582 
1583 	/* we cannot have a connection here */
1584 	if (conn)
1585 		return SF_ERR_INTERNAL;
1586 
1587 	/* tcpcheck send/expect initialisation */
1588 	if (check->type == PR_O2_TCPCHK_CHK) {
1589 		check->current_step = NULL;
1590 		tcp_rule = get_first_tcpcheck_rule(check->tcpcheck_rules);
1591 	}
1592 
1593 	/* prepare the check buffer.
1594 	 * This should not be used if check is the secondary agent check
1595 	 * of a server as s->proxy->check_req will relate to the
1596 	 * configuration of the primary check. Similarly, tcp-check uses
1597 	 * its own strings.
1598 	 */
1599 	if (check->type && check->type != PR_O2_TCPCHK_CHK && !(check->state & CHK_ST_AGENT)) {
1600 		b_putblk(&check->bo, s->proxy->check_req, s->proxy->check_len);
1601 
1602 		/* we want to check if this host replies to HTTP or SSLv3 requests
1603 		 * so we'll send the request, and won't wake the checker up now.
1604 		 */
1605 		if ((check->type) == PR_O2_SSL3_CHK) {
1606 			/* SSL requires that we put Unix time in the request */
1607 			int gmt_time = htonl(date.tv_sec);
1608 			memcpy(b_head(&check->bo) + 11, &gmt_time, 4);
1609 		}
1610 		else if ((check->type) == PR_O2_HTTP_CHK) {
1611 			/* prevent HTTP keep-alive when "http-check expect" is used */
1612 			if (s->proxy->options2 & PR_O2_EXP_TYPE)
1613 				b_putist(&check->bo, ist("Connection: close\r\n"));
1614 
1615 			/* If there is a body, add its content-length */
1616 			if (s->proxy->check_body_len)
1617 				chunk_appendf(&check->bo, "Content-Length: %s\r\n", ultoa(s->proxy->check_body_len));
1618 
1619 			/* Add configured headers */
1620 			if (s->proxy->check_hdrs)
1621 				b_putblk(&check->bo, s->proxy->check_hdrs, s->proxy->check_hdrs_len);
1622 
1623 			/* Add send-state header */
1624 			if (s->proxy->options2 & PR_O2_CHK_SNDST)
1625 				b_putblk(&check->bo, trash.area,
1626 					 httpchk_build_status_header(s, trash.area, trash.size));
1627 
1628 			/* end-of-header */
1629 			b_putist(&check->bo, ist("\r\n"));
1630 
1631 			/* Add the body */
1632 			if (s->proxy->check_body)
1633 				b_putblk(&check->bo, s->proxy->check_body, s->proxy->check_body_len);
1634 
1635 			*b_tail(&check->bo) = '\0'; /* to make gdb output easier to read */
1636 		}
1637 	}
1638 
1639 	if ((check->type & PR_O2_LB_AGENT_CHK) && check->send_string_len) {
1640 		b_putblk(&check->bo, check->send_string, check->send_string_len);
1641 	}
1642 
1643 	/* for tcp-checks, the initial connection setup is handled separately as
1644 	 * it may be sent to a specific port and not to the server's.
1645 	 */
1646 	if (tcp_rule && tcp_rule->action == TCPCHK_ACT_CONNECT) {
1647 		tcpcheck_main(check);
1648 		return SF_ERR_UP;
1649 	}
1650 
1651 	/* prepare a new connection */
1652 	cs = check->cs = cs_new(NULL);
1653 	if (!check->cs)
1654 		return SF_ERR_RESOURCE;
1655 	conn = cs->conn;
1656 	/* Maybe there were an older connection we were waiting on */
1657 	check->wait_list.events = 0;
1658 
1659 	if (is_addr(&check->addr)) {
1660 		/* we'll connect to the check addr specified on the server */
1661 		conn->addr.to = check->addr;
1662 	}
1663 	else {
1664 		/* we'll connect to the addr on the server */
1665 		conn->addr.to = s->addr;
1666 	}
1667 
1668 	proto = protocol_by_family(conn->addr.to.ss_family);
1669 	conn->target = &s->obj_type;
1670 
1671 	if ((conn->addr.to.ss_family == AF_INET) || (conn->addr.to.ss_family == AF_INET6)) {
1672 		int i = 0;
1673 
1674 		i = srv_check_healthcheck_port(check);
1675 		if (i == 0)
1676 			return SF_ERR_CHK_PORT;
1677 
1678 		set_host_port(&conn->addr.to, i);
1679 	}
1680 
1681 	/* no client address */
1682 	clear_addr(&conn->addr.from);
1683 
1684 	conn_prepare(conn, proto, check->xprt);
1685 	if (conn_install_mux(conn, &mux_pt_ops, cs, s->proxy, NULL) < 0)
1686 		return SF_ERR_RESOURCE;
1687 	cs_attach(cs, check, &check_conn_cb);
1688 
1689 	/* only plain tcp-check supports quick ACK */
1690 	quickack = check->type == 0 || check->type == PR_O2_TCPCHK_CHK;
1691 
1692 	if (tcp_rule && tcp_rule->action == TCPCHK_ACT_EXPECT)
1693 		quickack = 0;
1694 
1695 	ret = SF_ERR_INTERNAL;
1696 	if (proto && proto->connect)
1697 		ret = proto->connect(conn, check->type, quickack ? 2 : 0);
1698 
1699 
1700 #ifdef USE_OPENSSL
1701 	if (ret == SF_ERR_NONE) {
1702 		if (s->check.sni)
1703 			ssl_sock_set_servername(conn, s->check.sni);
1704 		if (s->check.alpn_str)
1705 			ssl_sock_set_alpn(conn, (unsigned char *)s->check.alpn_str,
1706 			    s->check.alpn_len);
1707 	}
1708 #endif
1709 	if (s->check.send_proxy && !(check->state & CHK_ST_AGENT)) {
1710 		conn->send_proxy_ofs = 1;
1711 		conn->flags |= CO_FL_SEND_PROXY;
1712 	}
1713 
1714 	return ret;
1715 }
1716 
1717 static struct list pid_list = LIST_HEAD_INIT(pid_list);
1718 static struct pool_head *pool_head_pid_list;
1719 __decl_spinlock(pid_list_lock);
1720 
block_sigchld(void)1721 void block_sigchld(void)
1722 {
1723 	sigset_t set;
1724 	sigemptyset(&set);
1725 	sigaddset(&set, SIGCHLD);
1726 	assert(ha_sigmask(SIG_BLOCK, &set, NULL) == 0);
1727 }
1728 
unblock_sigchld(void)1729 void unblock_sigchld(void)
1730 {
1731 	sigset_t set;
1732 	sigemptyset(&set);
1733 	sigaddset(&set, SIGCHLD);
1734 	assert(ha_sigmask(SIG_UNBLOCK, &set, NULL) == 0);
1735 }
1736 
pid_list_add(pid_t pid,struct task * t)1737 static struct pid_list *pid_list_add(pid_t pid, struct task *t)
1738 {
1739 	struct pid_list *elem;
1740 	struct check *check = t->context;
1741 
1742 	elem = pool_alloc(pool_head_pid_list);
1743 	if (!elem)
1744 		return NULL;
1745 	elem->pid = pid;
1746 	elem->t = t;
1747 	elem->exited = 0;
1748 	check->curpid = elem;
1749 	LIST_INIT(&elem->list);
1750 
1751 	HA_SPIN_LOCK(PID_LIST_LOCK, &pid_list_lock);
1752 	LIST_ADD(&pid_list, &elem->list);
1753 	HA_SPIN_UNLOCK(PID_LIST_LOCK, &pid_list_lock);
1754 
1755 	return elem;
1756 }
1757 
pid_list_del(struct pid_list * elem)1758 static void pid_list_del(struct pid_list *elem)
1759 {
1760 	struct check *check;
1761 
1762 	if (!elem)
1763 		return;
1764 
1765 	HA_SPIN_LOCK(PID_LIST_LOCK, &pid_list_lock);
1766 	LIST_DEL(&elem->list);
1767 	HA_SPIN_UNLOCK(PID_LIST_LOCK, &pid_list_lock);
1768 
1769 	if (!elem->exited)
1770 		kill(elem->pid, SIGTERM);
1771 
1772 	check = elem->t->context;
1773 	check->curpid = NULL;
1774 	pool_free(pool_head_pid_list, elem);
1775 }
1776 
1777 /* Called from inside SIGCHLD handler, SIGCHLD is blocked */
pid_list_expire(pid_t pid,int status)1778 static void pid_list_expire(pid_t pid, int status)
1779 {
1780 	struct pid_list *elem;
1781 
1782 	HA_SPIN_LOCK(PID_LIST_LOCK, &pid_list_lock);
1783 	list_for_each_entry(elem, &pid_list, list) {
1784 		if (elem->pid == pid) {
1785 			elem->t->expire = now_ms;
1786 			elem->status = status;
1787 			elem->exited = 1;
1788 			task_wakeup(elem->t, TASK_WOKEN_IO);
1789 			break;
1790 		}
1791 	}
1792 	HA_SPIN_UNLOCK(PID_LIST_LOCK, &pid_list_lock);
1793 }
1794 
sigchld_handler(struct sig_handler * sh)1795 static void sigchld_handler(struct sig_handler *sh)
1796 {
1797 	pid_t pid;
1798 	int status;
1799 
1800 	while ((pid = waitpid(0, &status, WNOHANG)) > 0)
1801 		pid_list_expire(pid, status);
1802 }
1803 
init_pid_list(void)1804 static int init_pid_list(void)
1805 {
1806 	if (pool_head_pid_list != NULL)
1807 		/* Nothing to do */
1808 		return 0;
1809 
1810 	if (!signal_register_fct(SIGCHLD, sigchld_handler, SIGCHLD)) {
1811 		ha_alert("Failed to set signal handler for external health checks: %s. Aborting.\n",
1812 			 strerror(errno));
1813 		return 1;
1814 	}
1815 
1816 	pool_head_pid_list = create_pool("pid_list", sizeof(struct pid_list), MEM_F_SHARED);
1817 	if (pool_head_pid_list == NULL) {
1818 		ha_alert("Failed to allocate memory pool for external health checks: %s. Aborting.\n",
1819 			 strerror(errno));
1820 		return 1;
1821 	}
1822 
1823 	return 0;
1824 }
1825 
1826 /* helper macro to set an environment variable and jump to a specific label on failure. */
1827 #define EXTCHK_SETENV(check, envidx, value, fail) { if (extchk_setenv(check, envidx, value)) goto fail; }
1828 
1829 /*
1830  * helper function to allocate enough memory to store an environment variable.
1831  * It will also check that the environment variable is updatable, and silently
1832  * fail if not.
1833  */
extchk_setenv(struct check * check,int idx,const char * value)1834 static int extchk_setenv(struct check *check, int idx, const char *value)
1835 {
1836 	int len, ret;
1837 	char *envname;
1838 	int vmaxlen;
1839 
1840 	if (idx < 0 || idx >= EXTCHK_SIZE) {
1841 		ha_alert("Illegal environment variable index %d. Aborting.\n", idx);
1842 		return 1;
1843 	}
1844 
1845 	envname = extcheck_envs[idx].name;
1846 	vmaxlen = extcheck_envs[idx].vmaxlen;
1847 
1848 	/* Check if the environment variable is already set, and silently reject
1849 	 * the update if this one is not updatable. */
1850 	if ((vmaxlen == EXTCHK_SIZE_EVAL_INIT) && (check->envp[idx]))
1851 		return 0;
1852 
1853 	/* Instead of sending NOT_USED, sending an empty value is preferable */
1854 	if (strcmp(value, "NOT_USED") == 0) {
1855 		value = "";
1856 	}
1857 
1858 	len = strlen(envname) + 1;
1859 	if (vmaxlen == EXTCHK_SIZE_EVAL_INIT)
1860 		len += strlen(value);
1861 	else
1862 		len += vmaxlen;
1863 
1864 	if (!check->envp[idx])
1865 		check->envp[idx] = malloc(len + 1);
1866 
1867 	if (!check->envp[idx]) {
1868 		ha_alert("Failed to allocate memory for the environment variable '%s'. Aborting.\n", envname);
1869 		return 1;
1870 	}
1871 	ret = snprintf(check->envp[idx], len + 1, "%s=%s", envname, value);
1872 	if (ret < 0) {
1873 		ha_alert("Failed to store the environment variable '%s'. Reason : %s. Aborting.\n", envname, strerror(errno));
1874 		return 1;
1875 	}
1876 	else if (ret > len) {
1877 		ha_alert("Environment variable '%s' was truncated. Aborting.\n", envname);
1878 		return 1;
1879 	}
1880 	return 0;
1881 }
1882 
prepare_external_check(struct check * check)1883 static int prepare_external_check(struct check *check)
1884 {
1885 	struct server *s = check->server;
1886 	struct proxy *px = s->proxy;
1887 	struct listener *listener = NULL, *l;
1888 	int i;
1889 	const char *path = px->check_path ? px->check_path : DEF_CHECK_PATH;
1890 	char buf[256];
1891 
1892 	list_for_each_entry(l, &px->conf.listeners, by_fe)
1893 		/* Use the first INET, INET6 or UNIX listener */
1894 		if (l->addr.ss_family == AF_INET ||
1895 		    l->addr.ss_family == AF_INET6 ||
1896 		    l->addr.ss_family == AF_UNIX) {
1897 			listener = l;
1898 			break;
1899 		}
1900 
1901 	check->curpid = NULL;
1902 	check->envp = calloc((EXTCHK_SIZE + 1), sizeof(char *));
1903 	if (!check->envp) {
1904 		ha_alert("Failed to allocate memory for environment variables. Aborting\n");
1905 		goto err;
1906 	}
1907 
1908 	check->argv = calloc(6, sizeof(char *));
1909 	if (!check->argv) {
1910 		ha_alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
1911 		goto err;
1912 	}
1913 
1914 	check->argv[0] = px->check_command;
1915 
1916 	if (!listener) {
1917 		check->argv[1] = strdup("NOT_USED");
1918 		check->argv[2] = strdup("NOT_USED");
1919 	}
1920 	else if (listener->addr.ss_family == AF_INET ||
1921 	    listener->addr.ss_family == AF_INET6) {
1922 		addr_to_str(&listener->addr, buf, sizeof(buf));
1923 		check->argv[1] = strdup(buf);
1924 		port_to_str(&listener->addr, buf, sizeof(buf));
1925 		check->argv[2] = strdup(buf);
1926 	}
1927 	else if (listener->addr.ss_family == AF_UNIX) {
1928 		const struct sockaddr_un *un;
1929 
1930 		un = (struct sockaddr_un *)&listener->addr;
1931 		check->argv[1] = strdup(un->sun_path);
1932 		check->argv[2] = strdup("NOT_USED");
1933 	}
1934 	else {
1935 		ha_alert("Starting [%s:%s] check: unsupported address family.\n", px->id, s->id);
1936 		goto err;
1937 	}
1938 
1939 	if (!check->argv[1] || !check->argv[2]) {
1940 		ha_alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
1941 		goto err;
1942 	}
1943 
1944 	check->argv[3] = calloc(EXTCHK_SIZE_ADDR, sizeof(*check->argv[3]));
1945 	check->argv[4] = calloc(EXTCHK_SIZE_UINT, sizeof(*check->argv[4]));
1946 	if (!check->argv[3] || !check->argv[4]) {
1947 		ha_alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
1948 		goto err;
1949 	}
1950 
1951 	addr_to_str(&s->addr, check->argv[3], EXTCHK_SIZE_ADDR);
1952 	if (s->addr.ss_family == AF_INET || s->addr.ss_family == AF_INET6)
1953 		snprintf(check->argv[4], EXTCHK_SIZE_UINT, "%u", s->svc_port);
1954 
1955 	for (i = 0; i < 5; i++) {
1956 		if (!check->argv[i]) {
1957 			ha_alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
1958 			goto err;
1959 		}
1960 	}
1961 
1962 	EXTCHK_SETENV(check, EXTCHK_PATH, path, err);
1963 	/* Add proxy environment variables */
1964 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_NAME, px->id, err);
1965 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ID, ultoa_r(px->uuid, buf, sizeof(buf)), err);
1966 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ADDR, check->argv[1], err);
1967 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_PORT, check->argv[2], err);
1968 	/* Add server environment variables */
1969 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_NAME, s->id, err);
1970 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ID, ultoa_r(s->puid, buf, sizeof(buf)), err);
1971 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ADDR, check->argv[3], err);
1972 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_PORT, check->argv[4], err);
1973 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_MAXCONN, ultoa_r(s->maxconn, buf, sizeof(buf)), err);
1974 	EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)), err);
1975 
1976 	/* Ensure that we don't leave any hole in check->envp */
1977 	for (i = 0; i < EXTCHK_SIZE; i++)
1978 		if (!check->envp[i])
1979 			EXTCHK_SETENV(check, i, "", err);
1980 
1981 	return 1;
1982 err:
1983 	if (check->envp) {
1984 		for (i = 0; i < EXTCHK_SIZE; i++)
1985 			free(check->envp[i]);
1986 		free(check->envp);
1987 		check->envp = NULL;
1988 	}
1989 
1990 	if (check->argv) {
1991 		for (i = 1; i < 5; i++)
1992 			free(check->argv[i]);
1993 		free(check->argv);
1994 		check->argv = NULL;
1995 	}
1996 	return 0;
1997 }
1998 
1999 /*
2000  * establish a server health-check that makes use of a process.
2001  *
2002  * It can return one of :
2003  *  - SF_ERR_NONE if everything's OK
2004  *  - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
2005  * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
2006  *
2007  * Blocks and then unblocks SIGCHLD
2008  */
connect_proc_chk(struct task * t)2009 static int connect_proc_chk(struct task *t)
2010 {
2011 	char buf[256];
2012 	struct check *check = t->context;
2013 	struct server *s = check->server;
2014 	struct proxy *px = s->proxy;
2015 	int status;
2016 	pid_t pid;
2017 
2018 	status = SF_ERR_RESOURCE;
2019 
2020 	block_sigchld();
2021 
2022 	pid = fork();
2023 	if (pid < 0) {
2024 		ha_alert("Failed to fork process for external health check: %s. Aborting.\n",
2025 			 strerror(errno));
2026 		set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
2027 		goto out;
2028 	}
2029 	if (pid == 0) {
2030 		/* Child */
2031 		extern char **environ;
2032 		struct rlimit limit;
2033 		int fd;
2034 
2035 		/* close all FDs. Keep stdin/stdout/stderr in verbose mode */
2036 		fd = (global.mode & (MODE_QUIET|MODE_VERBOSE)) == MODE_QUIET ? 0 : 3;
2037 
2038 		while (fd < global.rlimit_nofile)
2039 			close(fd++);
2040 
2041 		/* restore the initial FD limits */
2042 		limit.rlim_cur = rlim_fd_cur_at_boot;
2043 		limit.rlim_max = rlim_fd_max_at_boot;
2044 		if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
2045 			getrlimit(RLIMIT_NOFILE, &limit);
2046 			ha_warning("External check: failed to restore initial FD limits (cur=%u max=%u), using cur=%u max=%u\n",
2047 				   rlim_fd_cur_at_boot, rlim_fd_max_at_boot,
2048 				   (unsigned int)limit.rlim_cur, (unsigned int)limit.rlim_max);
2049 		}
2050 
2051 		environ = check->envp;
2052 
2053 		/* Update some environment variables and command args: curconn, server addr and server port */
2054 		extchk_setenv(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)));
2055 
2056 		addr_to_str(&s->addr, check->argv[3], EXTCHK_SIZE_ADDR);
2057 		extchk_setenv(check, EXTCHK_HAPROXY_SERVER_ADDR, check->argv[3]);
2058 
2059 		*check->argv[4] = 0;
2060 		if (s->addr.ss_family == AF_INET || s->addr.ss_family == AF_INET6)
2061 			snprintf(check->argv[4], EXTCHK_SIZE_UINT, "%u", s->svc_port);
2062 		extchk_setenv(check, EXTCHK_HAPROXY_SERVER_PORT, check->argv[4]);
2063 
2064 		execvp(px->check_command, check->argv);
2065 		ha_alert("Failed to exec process for external health check: %s. Aborting.\n",
2066 			 strerror(errno));
2067 		exit(-1);
2068 	}
2069 
2070 	/* Parent */
2071 	if (check->result == CHK_RES_UNKNOWN) {
2072 		if (pid_list_add(pid, t) != NULL) {
2073 			t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2074 
2075 			if (px->timeout.check && px->timeout.connect) {
2076 				int t_con = tick_add(now_ms, px->timeout.connect);
2077 				t->expire = tick_first(t->expire, t_con);
2078 			}
2079 			status = SF_ERR_NONE;
2080 			goto out;
2081 		}
2082 		else {
2083 			set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
2084 		}
2085 		kill(pid, SIGTERM); /* process creation error */
2086 	}
2087 	else
2088 		set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
2089 
2090 out:
2091 	unblock_sigchld();
2092 	return status;
2093 }
2094 
2095 /*
2096  * manages a server health-check that uses an external process. Returns
2097  * the time the task accepts to wait, or TIME_ETERNITY for infinity.
2098  *
2099  * Please do NOT place any return statement in this function and only leave
2100  * via the out_unlock label.
2101  */
process_chk_proc(struct task * t,void * context,unsigned short state)2102 static struct task *process_chk_proc(struct task *t, void *context, unsigned short state)
2103 {
2104 	struct check *check = context;
2105 	struct server *s = check->server;
2106 	int rv;
2107 	int ret;
2108 	int expired = tick_is_expired(t->expire, now_ms);
2109 
2110 	HA_SPIN_LOCK(SERVER_LOCK, &check->server->lock);
2111 	if (!(check->state & CHK_ST_INPROGRESS)) {
2112 		/* no check currently running */
2113 		if (!expired) /* woke up too early */
2114 			goto out_unlock;
2115 
2116 		/* we don't send any health-checks when the proxy is
2117 		 * stopped, the server should not be checked or the check
2118 		 * is disabled.
2119 		 */
2120 		if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
2121 		    s->proxy->state == PR_STSTOPPED)
2122 			goto reschedule;
2123 
2124 		/* we'll initiate a new check */
2125 		set_server_check_status(check, HCHK_STATUS_START, NULL);
2126 
2127 		check->state |= CHK_ST_INPROGRESS;
2128 
2129 		ret = connect_proc_chk(t);
2130 		if (ret == SF_ERR_NONE) {
2131 			/* the process was forked, we allow up to min(inter,
2132 			 * timeout.connect) for it to report its status, but
2133 			 * only when timeout.check is set as it may be to short
2134 			 * for a full check otherwise.
2135 			 */
2136 			t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2137 
2138 			if (s->proxy->timeout.check && s->proxy->timeout.connect) {
2139 				int t_con = tick_add(now_ms, s->proxy->timeout.connect);
2140 				t->expire = tick_first(t->expire, t_con);
2141 			}
2142 			task_set_affinity(t, tid_bit);
2143 			goto reschedule;
2144 		}
2145 
2146 		/* here, we failed to start the check */
2147 
2148 		check->state &= ~CHK_ST_INPROGRESS;
2149 		check_notify_failure(check);
2150 
2151 		/* we allow up to min(inter, timeout.connect) for a connection
2152 		 * to establish but only when timeout.check is set
2153 		 * as it may be to short for a full check otherwise
2154 		 */
2155 		while (tick_is_expired(t->expire, now_ms)) {
2156 			int t_con;
2157 
2158 			t_con = tick_add(t->expire, s->proxy->timeout.connect);
2159 			t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2160 
2161 			if (s->proxy->timeout.check)
2162 				t->expire = tick_first(t->expire, t_con);
2163 		}
2164 	}
2165 	else {
2166 		/* there was a test running.
2167 		 * First, let's check whether there was an uncaught error,
2168 		 * which can happen on connect timeout or error.
2169 		 */
2170 		if (check->result == CHK_RES_UNKNOWN) {
2171 			/* good connection is enough for pure TCP check */
2172 			struct pid_list *elem = check->curpid;
2173 			int status = HCHK_STATUS_UNKNOWN;
2174 
2175 			if (elem->exited) {
2176 				status = elem->status; /* Save in case the process exits between use below */
2177 				if (!WIFEXITED(status))
2178 					check->code = -1;
2179 				else
2180 					check->code = WEXITSTATUS(status);
2181 				if (!WIFEXITED(status) || WEXITSTATUS(status))
2182 					status = HCHK_STATUS_PROCERR;
2183 				else
2184 					status = HCHK_STATUS_PROCOK;
2185 			} else if (expired) {
2186 				status = HCHK_STATUS_PROCTOUT;
2187 				ha_warning("kill %d\n", (int)elem->pid);
2188 				kill(elem->pid, SIGTERM);
2189 			}
2190 			set_server_check_status(check, status, NULL);
2191 		}
2192 
2193 		if (check->result == CHK_RES_FAILED) {
2194 			/* a failure or timeout detected */
2195 			check_notify_failure(check);
2196 		}
2197 		else if (check->result == CHK_RES_CONDPASS) {
2198 			/* check is OK but asks for stopping mode */
2199 			check_notify_stopping(check);
2200 		}
2201 		else if (check->result == CHK_RES_PASSED) {
2202 			/* a success was detected */
2203 			check_notify_success(check);
2204 		}
2205 		task_set_affinity(t, 1);
2206 		check->state &= ~CHK_ST_INPROGRESS;
2207 
2208 		pid_list_del(check->curpid);
2209 
2210 		rv = 0;
2211 		if (global.spread_checks > 0) {
2212 			rv = srv_getinter(check) * global.spread_checks / 100;
2213 			rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
2214 		}
2215 		t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
2216 	}
2217 
2218  reschedule:
2219 	while (tick_is_expired(t->expire, now_ms))
2220 		t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2221 
2222  out_unlock:
2223 	HA_SPIN_UNLOCK(SERVER_LOCK, &check->server->lock);
2224 	return t;
2225 }
2226 
2227 /*
2228  * manages a server health-check that uses a connection. Returns
2229  * the time the task accepts to wait, or TIME_ETERNITY for infinity.
2230  *
2231  * Please do NOT place any return statement in this function and only leave
2232  * via the out_unlock label.
2233  */
process_chk_conn(struct task * t,void * context,unsigned short state)2234 static struct task *process_chk_conn(struct task *t, void *context, unsigned short state)
2235 {
2236 	struct check *check = context;
2237 	struct proxy *proxy = check->proxy;
2238 	struct conn_stream *cs = check->cs;
2239 	struct connection *conn = cs_conn(cs);
2240 	int rv;
2241 	int ret;
2242 	int expired = tick_is_expired(t->expire, now_ms);
2243 
2244 	if (check->server)
2245 		HA_SPIN_LOCK(SERVER_LOCK, &check->server->lock);
2246 	if (!(check->state & CHK_ST_INPROGRESS)) {
2247 		/* no check currently running */
2248 		if (!expired) /* woke up too early */
2249 			goto out_unlock;
2250 
2251 		/* we don't send any health-checks when the proxy is
2252 		 * stopped, the server should not be checked or the check
2253 		 * is disabled.
2254 		 */
2255 		if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
2256 		    proxy->state == PR_STSTOPPED)
2257 			goto reschedule;
2258 
2259 		/* we'll initiate a new check */
2260 		set_server_check_status(check, HCHK_STATUS_START, NULL);
2261 
2262 		check->state |= CHK_ST_INPROGRESS;
2263 		b_reset(&check->bi);
2264 		b_reset(&check->bo);
2265 
2266 		task_set_affinity(t, tid_bit);
2267 		ret = connect_conn_chk(t);
2268 		cs = check->cs;
2269 		conn = cs_conn(cs);
2270 
2271 		switch (ret) {
2272 		case SF_ERR_UP:
2273 			goto out_unlock;
2274 
2275 		case SF_ERR_NONE:
2276 			/* we allow up to min(inter, timeout.connect) for a connection
2277 			 * to establish but only when timeout.check is set
2278 			 * as it may be to short for a full check otherwise
2279 			 */
2280 			t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2281 
2282 			if (proxy->timeout.check && proxy->timeout.connect) {
2283 				int t_con = tick_add(now_ms, proxy->timeout.connect);
2284 				t->expire = tick_first(t->expire, t_con);
2285 			}
2286 
2287 			if (check->type)
2288 				__event_srv_chk_r(cs);
2289 
2290 			goto reschedule;
2291 
2292 		case SF_ERR_SRVTO: /* ETIMEDOUT */
2293 		case SF_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
2294 			if (conn)
2295 				conn->flags |= CO_FL_ERROR;
2296 			chk_report_conn_err(check, errno, 0);
2297 			break;
2298 		/* should share same code than cases below */
2299 		case SF_ERR_CHK_PORT:
2300 			check->state |= CHK_ST_PORT_MISS;
2301 		case SF_ERR_PRXCOND:
2302 		case SF_ERR_RESOURCE:
2303 		case SF_ERR_INTERNAL:
2304 			if (conn)
2305 				conn->flags |= CO_FL_ERROR;
2306 			chk_report_conn_err(check, conn ? 0 : ENOMEM, 0);
2307 			break;
2308 		}
2309 
2310 		/* here, we have seen a synchronous error, no fd was allocated */
2311 		task_set_affinity(t, MAX_THREADS_MASK);
2312 		if (cs) {
2313 			if (check->wait_list.events)
2314 				cs->conn->xprt->unsubscribe(cs->conn,
2315 							    check->wait_list.events,
2316 							    &check->wait_list);
2317 			/* We may have been scheduled to run, and the
2318 			 * I/O handler expects to have a cs, so remove
2319 			 * the tasklet
2320 			 */
2321 			task_remove_from_tasklet_list((struct task *)check->wait_list.task);
2322 			cs_destroy(cs);
2323 			cs = check->cs = NULL;
2324 			conn = NULL;
2325 		}
2326 
2327 		check->state &= ~CHK_ST_INPROGRESS;
2328 		check_notify_failure(check);
2329 
2330 		/* we allow up to min(inter, timeout.connect) for a connection
2331 		 * to establish but only when timeout.check is set
2332 		 * as it may be to short for a full check otherwise
2333 		 */
2334 		while (tick_is_expired(t->expire, now_ms)) {
2335 			int t_con;
2336 
2337 			t_con = tick_add(t->expire, proxy->timeout.connect);
2338 			t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2339 
2340 			if (proxy->timeout.check)
2341 				t->expire = tick_first(t->expire, t_con);
2342 		}
2343 	}
2344 	else {
2345 		/* there was a test running.
2346 		 * First, let's check whether there was an uncaught error,
2347 		 * which can happen on connect timeout or error.
2348 		 */
2349 		if (check->result == CHK_RES_UNKNOWN) {
2350 			/* good connection is enough for pure TCP check */
2351 			if ((conn->flags & CO_FL_CONNECTED) && !check->type) {
2352 				if (check->use_ssl == 1)
2353 					set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
2354 				else
2355 					set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
2356 			}
2357 			else if ((conn->flags & CO_FL_ERROR) || cs->flags & CS_FL_ERROR || expired) {
2358 				chk_report_conn_err(check, 0, expired);
2359 			}
2360 			else
2361 				goto out_unlock; /* timeout not reached, wait again */
2362 		}
2363 
2364 		/* check complete or aborted */
2365 		if (conn && conn->xprt) {
2366 			/* The check was aborted and the connection was not yet closed.
2367 			 * This can happen upon timeout, or when an external event such
2368 			 * as a failed response coupled with "observe layer7" caused the
2369 			 * server state to be suddenly changed.
2370 			 */
2371 			conn_sock_drain(conn);
2372 			cs_close(cs);
2373 		}
2374 
2375 		if (cs) {
2376 			if (check->wait_list.events)
2377 				cs->conn->xprt->unsubscribe(cs->conn,
2378 				    check->wait_list.events,
2379 				    &check->wait_list);
2380 			/* We may have been scheduled to run, and the
2381                          * I/O handler expects to have a cs, so remove
2382                          * the tasklet
2383                          */
2384                         task_remove_from_tasklet_list((struct task *)check->wait_list.task);
2385 			cs_destroy(cs);
2386 			cs = check->cs = NULL;
2387 			conn = NULL;
2388 		}
2389 
2390 		if (check->server) {
2391 			if (check->result == CHK_RES_FAILED) {
2392 				/* a failure or timeout detected */
2393 				check_notify_failure(check);
2394 			}
2395 			else if (check->result == CHK_RES_CONDPASS) {
2396 				/* check is OK but asks for stopping mode */
2397 				check_notify_stopping(check);
2398 			}
2399 			else if (check->result == CHK_RES_PASSED) {
2400 				/* a success was detected */
2401 				check_notify_success(check);
2402 			}
2403 		}
2404 		task_set_affinity(t, MAX_THREADS_MASK);
2405 		check->state &= ~CHK_ST_INPROGRESS;
2406 
2407 		if (check->server) {
2408 			rv = 0;
2409 			if (global.spread_checks > 0) {
2410 				rv = srv_getinter(check) * global.spread_checks / 100;
2411 				rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
2412 			}
2413 			t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
2414 		}
2415 	}
2416 
2417  reschedule:
2418 	while (tick_is_expired(t->expire, now_ms))
2419 		t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2420  out_unlock:
2421 	if (check->server)
2422 		HA_SPIN_UNLOCK(SERVER_LOCK, &check->server->lock);
2423 	return t;
2424 }
2425 
2426 /*
2427  * manages a server health-check. Returns
2428  * the time the task accepts to wait, or TIME_ETERNITY for infinity.
2429  */
process_chk(struct task * t,void * context,unsigned short state)2430 static struct task *process_chk(struct task *t, void *context, unsigned short state)
2431 {
2432 	struct check *check = context;
2433 
2434 	if (check->type == PR_O2_EXT_CHK)
2435 		return process_chk_proc(t, context, state);
2436 	return process_chk_conn(t, context, state);
2437 
2438 }
2439 
start_check_task(struct check * check,int mininter,int nbcheck,int srvpos)2440 static int start_check_task(struct check *check, int mininter,
2441 			    int nbcheck, int srvpos)
2442 {
2443 	struct task *t;
2444 	unsigned long thread_mask = MAX_THREADS_MASK;
2445 
2446 	if (check->type == PR_O2_EXT_CHK)
2447 		thread_mask = 1;
2448 
2449 	/* task for the check */
2450 	if ((t = task_new(thread_mask)) == NULL) {
2451 		ha_alert("Starting [%s:%s] check: out of memory.\n",
2452 			 check->server->proxy->id, check->server->id);
2453 		return 0;
2454 	}
2455 
2456 	check->task = t;
2457 	t->process = process_chk;
2458 	t->context = check;
2459 
2460 	if (mininter < srv_getinter(check))
2461 		mininter = srv_getinter(check);
2462 
2463 	if (global.max_spread_checks && mininter > global.max_spread_checks)
2464 		mininter = global.max_spread_checks;
2465 
2466 	/* check this every ms */
2467 	t->expire = tick_add(now_ms, MS_TO_TICKS(mininter * srvpos / nbcheck));
2468 	check->start = now;
2469 	task_queue(t);
2470 
2471 	return 1;
2472 }
2473 
2474 /*
2475  * Start health-check.
2476  * Returns 0 if OK, ERR_FATAL on error, and prints the error in this case.
2477  */
start_checks()2478 static int start_checks()
2479 {
2480 
2481 	struct proxy *px;
2482 	struct server *s;
2483 	struct task *t;
2484 	int nbcheck=0, mininter=0, srvpos=0;
2485 
2486 	/* 1- count the checkers to run simultaneously.
2487 	 * We also determine the minimum interval among all of those which
2488 	 * have an interval larger than SRV_CHK_INTER_THRES. This interval
2489 	 * will be used to spread their start-up date. Those which have
2490 	 * a shorter interval will start independently and will not dictate
2491 	 * too short an interval for all others.
2492 	 */
2493 	for (px = proxies_list; px; px = px->next) {
2494 		for (s = px->srv; s; s = s->next) {
2495 			if (s->slowstart) {
2496 				if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2497 					ha_alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
2498 					return ERR_ALERT | ERR_FATAL;
2499 				}
2500 				/* We need a warmup task that will be called when the server
2501 				 * state switches from down to up.
2502 				 */
2503 				s->warmup = t;
2504 				t->process = server_warmup;
2505 				t->context = s;
2506 				/* server can be in this state only because of */
2507 				if (s->next_state == SRV_ST_STARTING)
2508 					task_schedule(s->warmup, tick_add(now_ms, MS_TO_TICKS(MAX(1000, (now.tv_sec - s->last_change)) / 20)));
2509 			}
2510 
2511 			if (s->check.state & CHK_ST_CONFIGURED) {
2512 				nbcheck++;
2513 				if ((srv_getinter(&s->check) >= SRV_CHK_INTER_THRES) &&
2514 				    (!mininter || mininter > srv_getinter(&s->check)))
2515 					mininter = srv_getinter(&s->check);
2516 			}
2517 
2518 			if (s->agent.state & CHK_ST_CONFIGURED) {
2519 				nbcheck++;
2520 				if ((srv_getinter(&s->agent) >= SRV_CHK_INTER_THRES) &&
2521 				    (!mininter || mininter > srv_getinter(&s->agent)))
2522 					mininter = srv_getinter(&s->agent);
2523 			}
2524 		}
2525 	}
2526 
2527 	if (!nbcheck)
2528 		return 0;
2529 
2530 	srand((unsigned)time(NULL));
2531 
2532 	/*
2533 	 * 2- start them as far as possible from each others. For this, we will
2534 	 * start them after their interval set to the min interval divided by
2535 	 * the number of servers, weighted by the server's position in the list.
2536 	 */
2537 	for (px = proxies_list; px; px = px->next) {
2538 		if ((px->options2 & PR_O2_CHK_ANY) == PR_O2_EXT_CHK) {
2539 			if (init_pid_list()) {
2540 				ha_alert("Starting [%s] check: out of memory.\n", px->id);
2541 				return ERR_ALERT | ERR_FATAL;
2542 			}
2543 		}
2544 
2545 		for (s = px->srv; s; s = s->next) {
2546 			/* A task for the main check */
2547 			if (s->check.state & CHK_ST_CONFIGURED) {
2548 				if (s->check.type == PR_O2_EXT_CHK) {
2549 					if (!prepare_external_check(&s->check))
2550 						return ERR_ALERT | ERR_FATAL;
2551 				}
2552 				if (!start_check_task(&s->check, mininter, nbcheck, srvpos))
2553 					return ERR_ALERT | ERR_FATAL;
2554 				srvpos++;
2555 			}
2556 
2557 			/* A task for a auxiliary agent check */
2558 			if (s->agent.state & CHK_ST_CONFIGURED) {
2559 				if (!start_check_task(&s->agent, mininter, nbcheck, srvpos)) {
2560 					return ERR_ALERT | ERR_FATAL;
2561 				}
2562 				srvpos++;
2563 			}
2564 		}
2565 	}
2566 	return 0;
2567 }
2568 
2569 /*
2570  * Perform content verification check on data in s->check.buffer buffer.
2571  * The buffer MUST be terminated by a null byte before calling this function.
2572  * Sets server status appropriately. The caller is responsible for ensuring
2573  * that the buffer contains at least 13 characters. If <done> is zero, we may
2574  * return 0 to indicate that data is required to decide of a match.
2575  */
httpchk_expect(struct server * s,int done)2576 static int httpchk_expect(struct server *s, int done)
2577 {
2578 	static THREAD_LOCAL char status_msg[] = "HTTP status check returned code <000>";
2579 	char status_code[] = "000";
2580 	char *contentptr;
2581 	int crlf;
2582 	int ret;
2583 
2584 	switch (s->proxy->options2 & PR_O2_EXP_TYPE) {
2585 	case PR_O2_EXP_STS:
2586 	case PR_O2_EXP_RSTS:
2587 		memcpy(status_code, b_head(&s->check.bi) + 9, 3);
2588 		memcpy(status_msg + strlen(status_msg) - 4, b_head(&s->check.bi) + 9, 3);
2589 
2590 		if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STS)
2591 			ret = strncmp(s->proxy->expect_str, status_code, 3) == 0;
2592 		else
2593 			ret = regex_exec(s->proxy->expect_regex, status_code);
2594 
2595 		/* we necessarily have the response, so there are no partial failures */
2596 		if (s->proxy->options2 & PR_O2_EXP_INV)
2597 			ret = !ret;
2598 
2599 		set_server_check_status(&s->check, ret ? HCHK_STATUS_L7OKD : HCHK_STATUS_L7STS, status_msg);
2600 		break;
2601 
2602 	case PR_O2_EXP_STR:
2603 	case PR_O2_EXP_RSTR:
2604 		/* very simple response parser: ignore CR and only count consecutive LFs,
2605 		 * stop with contentptr pointing to first char after the double CRLF or
2606 		 * to '\0' if crlf < 2.
2607 		 */
2608 		crlf = 0;
2609 		for (contentptr = b_head(&s->check.bi); *contentptr; contentptr++) {
2610 			if (crlf >= 2)
2611 				break;
2612 			if (*contentptr == '\r')
2613 				continue;
2614 			else if (*contentptr == '\n')
2615 				crlf++;
2616 			else
2617 				crlf = 0;
2618 		}
2619 
2620 		/* Check that response contains a body... */
2621 		if (crlf < 2) {
2622 			if (!done)
2623 				return 0;
2624 
2625 			set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
2626 						"HTTP content check could not find a response body");
2627 			return 1;
2628 		}
2629 
2630 		/* Check that response body is not empty... */
2631 		if (*contentptr == '\0') {
2632 			if (!done)
2633 				return 0;
2634 
2635 			set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
2636 						"HTTP content check found empty response body");
2637 			return 1;
2638 		}
2639 
2640 		/* Check the response content against the supplied string
2641 		 * or regex... */
2642 		if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STR)
2643 			ret = strstr(contentptr, s->proxy->expect_str) != NULL;
2644 		else
2645 			ret = regex_exec(s->proxy->expect_regex, contentptr);
2646 
2647 		/* if we don't match, we may need to wait more */
2648 		if (!ret && !done)
2649 			return 0;
2650 
2651 		if (ret) {
2652 			/* content matched */
2653 			if (s->proxy->options2 & PR_O2_EXP_INV)
2654 				set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
2655 							"HTTP check matched unwanted content");
2656 			else
2657 				set_server_check_status(&s->check, HCHK_STATUS_L7OKD,
2658 							"HTTP content check matched");
2659 		}
2660 		else {
2661 			if (s->proxy->options2 & PR_O2_EXP_INV)
2662 				set_server_check_status(&s->check, HCHK_STATUS_L7OKD,
2663 							"HTTP check did not match unwanted content");
2664 			else
2665 				set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
2666 							"HTTP content check did not match");
2667 		}
2668 		break;
2669 	}
2670 	return 1;
2671 }
2672 
2673 /*
2674  * return the id of a step in a send/expect session
2675  */
tcpcheck_get_step_id(struct check * check)2676 static int tcpcheck_get_step_id(struct check *check)
2677 {
2678 	struct tcpcheck_rule *cur = NULL, *next = NULL;
2679 	int i = 0;
2680 
2681 	/* not even started anything yet => step 0 = initial connect */
2682 	if (!check->current_step)
2683 		return 0;
2684 
2685 	cur = check->last_started_step;
2686 
2687 	/* no step => first step */
2688 	if (cur == NULL)
2689 		return 1;
2690 
2691 	/* increment i until current step */
2692 	list_for_each_entry(next, check->tcpcheck_rules, list) {
2693 		if (next->list.p == &cur->list)
2694 			break;
2695 		++i;
2696 	}
2697 
2698 	return i;
2699 }
2700 
2701 /*
2702  * return the latest known comment before (including) the given stepid
2703  * returns NULL if no comment found
2704  */
tcpcheck_get_step_comment(struct check * check,int stepid)2705 static char * tcpcheck_get_step_comment(struct check *check, int stepid)
2706 {
2707 	struct tcpcheck_rule *cur = NULL;
2708 	char *ret = NULL;
2709 	int i = 0;
2710 
2711 	/* not even started anything yet, return latest comment found before any action */
2712 	if (!check->current_step) {
2713 		list_for_each_entry(cur, check->tcpcheck_rules, list) {
2714 			if (cur->action == TCPCHK_ACT_COMMENT)
2715 				ret = cur->comment;
2716 			else
2717 				goto return_comment;
2718 		}
2719 	}
2720 
2721 	i = 1;
2722 	list_for_each_entry(cur, check->tcpcheck_rules, list) {
2723 		if (cur->comment)
2724 			ret = cur->comment;
2725 
2726 		if (i >= stepid)
2727 			goto return_comment;
2728 
2729 		++i;
2730 	}
2731 
2732  return_comment:
2733 	return ret;
2734 }
2735 
2736 /* proceed with next steps for the TCP checks <check>. Note that this is called
2737  * both from the connection's wake() callback and from the check scheduling task.
2738  * It returns 0 on normal cases, or <0 if a close() has happened on an existing
2739  * connection, presenting the risk of an fd replacement.
2740  *
2741  * Please do NOT place any return statement in this function and only leave
2742  * via the out_end_tcpcheck label after setting retcode.
2743  */
tcpcheck_main(struct check * check)2744 static int tcpcheck_main(struct check *check)
2745 {
2746 	char *contentptr, *comment;
2747 	struct tcpcheck_rule *next;
2748 	int done = 0, ret = 0, step = 0;
2749 	struct conn_stream *cs = check->cs;
2750 	struct connection *conn = cs_conn(cs);
2751 	struct server *s = check->server;
2752 	struct proxy *proxy = check->proxy;
2753 	struct task *t = check->task;
2754 	struct list *head = check->tcpcheck_rules;
2755 	int retcode = 0;
2756 
2757 	/* here, we know that the check is complete or that it failed */
2758 	if (check->result != CHK_RES_UNKNOWN)
2759 		goto out_end_tcpcheck;
2760 
2761 	/* We have 4 possibilities here :
2762 	 *   1. we've not yet attempted step 1, and step 1 is a connect, so no
2763 	 *      connection attempt was made yet ; conn==NULL;current_step==NULL.
2764 	 *   2. we've not yet attempted step 1, and step 1 is a not connect or
2765 	 *      does not exist (no rule), so a connection attempt was made
2766 	 *      before coming here, conn!=NULL.
2767 	 *   3. we're coming back after having started with step 1, so we may
2768 	 *      be waiting for a connection attempt to complete. conn!=NULL.
2769 	 *   4. the connection + handshake are complete. conn!=NULL.
2770 	 *
2771 	 * #2 and #3 are quite similar, we want both the connection and the
2772 	 * handshake to complete before going any further. Thus we must always
2773 	 * wait for a connection to complete unless we're before and existing
2774 	 * step 1.
2775 	 */
2776 
2777 	/* find first rule and skip comments */
2778 	next = LIST_NEXT(head, struct tcpcheck_rule *, list);
2779 	while (&next->list != head && next->action == TCPCHK_ACT_COMMENT)
2780 		next = LIST_NEXT(&next->list, struct tcpcheck_rule *, list);
2781 
2782 	if ((check->current_step || &next->list == head) &&
2783 	    (!(conn->flags & CO_FL_CONNECTED) || (conn->flags & CO_FL_HANDSHAKE))) {
2784 		/* we allow up to min(inter, timeout.connect) for a connection
2785 		 * to establish but only when timeout.check is set
2786 		 * as it may be to short for a full check otherwise
2787 		 */
2788 		while (tick_is_expired(t->expire, now_ms)) {
2789 			int t_con;
2790 
2791 			t_con = tick_add(t->expire, proxy->timeout.connect);
2792 			t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2793 
2794 			if (proxy->timeout.check)
2795 				t->expire = tick_first(t->expire, t_con);
2796 		}
2797 		goto out;
2798 	}
2799 
2800 	/* special case: option tcp-check with no rule, a connect is enough */
2801 	if (&next->list == head) {
2802 		set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
2803 		goto out_end_tcpcheck;
2804 	}
2805 
2806 	/* no step means first step initialisation */
2807 	if (check->current_step == NULL) {
2808 		check->last_started_step = NULL;
2809 		b_reset(&check->bo);
2810 		b_reset(&check->bi);
2811 		check->current_step = next;
2812 		t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2813 		if (proxy->timeout.check)
2814 			t->expire = tick_add_ifset(now_ms, proxy->timeout.check);
2815 	}
2816 
2817 	while (1) {
2818 		/* We have to try to flush the output buffer before reading, at
2819 		 * the end, or if we're about to send a string that does not fit
2820 		 * in the remaining space. That explains why we break out of the
2821 		 * loop after this control. If we have data, conn is valid.
2822 		 */
2823 		if (b_data(&check->bo) &&
2824 		    (&check->current_step->list == head ||
2825 		     check->current_step->action != TCPCHK_ACT_SEND ||
2826 		     check->current_step->string_len >= b_room(&check->bo))) {
2827 			int ret;
2828 
2829 			ret = cs->conn->mux->snd_buf(cs, &check->bo, b_data(&check->bo), 0);
2830 			b_realign_if_empty(&check->bo);
2831 
2832 			if (ret <= 0) {
2833 				if (conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR) {
2834 					chk_report_conn_err(check, errno, 0);
2835 					goto out_end_tcpcheck;
2836 				}
2837 				break;
2838 			}
2839 			if (b_data(&check->bo)) {
2840 				cs->conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
2841 				goto out;
2842 			}
2843 		}
2844 
2845 		if (&check->current_step->list == head)
2846 			break;
2847 
2848 		/* have 'next' point to the next rule or NULL if we're on the
2849 		 * last one, connect() needs this.
2850 		 */
2851 		next = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
2852 
2853 		/* bypass all comment rules */
2854 		while (&next->list != head && next->action == TCPCHK_ACT_COMMENT)
2855 			next = LIST_NEXT(&next->list, struct tcpcheck_rule *, list);
2856 
2857 		/* NULL if we're on the last rule */
2858 		if (&next->list == head)
2859 			next = NULL;
2860 
2861 		if (check->current_step->action == TCPCHK_ACT_CONNECT) {
2862 			struct protocol *proto;
2863 			struct xprt_ops *xprt;
2864 
2865 			/* For a connect action we'll create a new connection.
2866 			 * We may also have to kill a previous one. But we don't
2867 			 * want to leave *without* a connection if we came here
2868 			 * from the connection layer, hence with a connection.
2869 			 * Thus we'll proceed in the following order :
2870 			 *   1: close but not release previous connection
2871 			 *   2: try to get a new connection
2872 			 *   3: release and replace the old one on success
2873 			 */
2874 			if (check->cs) {
2875 				cs_close(check->cs);
2876 				retcode = -1; /* do not reuse the fd in the caller! */
2877 			}
2878 
2879 			/* mark the step as started */
2880 			check->last_started_step = check->current_step;
2881 
2882 			/* prepare new connection */
2883 			cs = cs_new(NULL);
2884 			if (!cs) {
2885 				step = tcpcheck_get_step_id(check);
2886 				chunk_printf(&trash, "TCPCHK error allocating connection at step %d", step);
2887 				comment = tcpcheck_get_step_comment(check, step);
2888 				if (comment)
2889 					chunk_appendf(&trash, " comment: '%s'", comment);
2890 				set_server_check_status(check, HCHK_STATUS_SOCKERR,
2891 							trash.area);
2892 				check->current_step = NULL;
2893 				goto out;
2894 			}
2895 
2896 			if (check->cs) {
2897 				if (check->wait_list.events)
2898 					cs->conn->xprt->unsubscribe(cs->conn,
2899 								    check->wait_list.events,
2900 								    &check->wait_list);
2901 			/* We may have been scheduled to run, and the
2902                          * I/O handler expects to have a cs, so remove
2903                          * the tasklet
2904                          */
2905                         task_remove_from_tasklet_list((struct task *)check->wait_list.task);
2906 
2907 
2908 				cs_destroy(check->cs);
2909 			}
2910 
2911 			check->cs = cs;
2912 			conn = cs->conn;
2913 			/* Maybe there were an older connection we were waiting on */
2914 			check->wait_list.events = 0;
2915 			conn->target = s ? &s->obj_type : &proxy->obj_type;
2916 
2917 			/* no client address */
2918 			clear_addr(&conn->addr.from);
2919 
2920 			if (is_addr(&check->addr)) {
2921 				/* we'll connect to the check addr specified on the server */
2922 				conn->addr.to = check->addr;
2923 			}
2924 			else {
2925 				/* we'll connect to the addr on the server */
2926 				conn->addr.to = s->addr;
2927 			}
2928 			proto = protocol_by_family(conn->addr.to.ss_family);
2929 
2930 			/* port */
2931 			if (check->current_step->port)
2932 				set_host_port(&conn->addr.to, check->current_step->port);
2933 			else if (check->port)
2934 				set_host_port(&conn->addr.to, check->port);
2935 			else if (s->svc_port)
2936 				set_host_port(&conn->addr.to, s->svc_port);
2937 
2938 			if (check->current_step->conn_opts & TCPCHK_OPT_SSL) {
2939 				xprt = xprt_get(XPRT_SSL);
2940 			}
2941 			else {
2942 				xprt = xprt_get(XPRT_RAW);
2943 			}
2944 
2945 			conn_prepare(conn, proto, xprt);
2946 
2947 			if (conn_install_mux(conn, &mux_pt_ops, cs, proxy, NULL) < 0) {
2948 				ret = SF_ERR_RESOURCE;
2949 				goto fail_check;
2950 			}
2951 
2952 			cs_attach(cs, check, &check_conn_cb);
2953 
2954 			ret = SF_ERR_INTERNAL;
2955 			if (proto && proto->connect)
2956 				ret = proto->connect(conn,
2957 						     1 /* I/O polling is always needed */,
2958 						     (next && next->action == TCPCHK_ACT_EXPECT) ? 0 : 2);
2959 			if (check->current_step->conn_opts & TCPCHK_OPT_SEND_PROXY) {
2960 				conn->send_proxy_ofs = 1;
2961 				conn->flags |= CO_FL_SEND_PROXY;
2962 			}
2963 
2964 			/* It can return one of :
2965 			 *  - SF_ERR_NONE if everything's OK
2966 			 *  - SF_ERR_SRVTO if there are no more servers
2967 			 *  - SF_ERR_SRVCL if the connection was refused by the server
2968 			 *  - SF_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
2969 			 *  - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
2970 			 *  - SF_ERR_INTERNAL for any other purely internal errors
2971 			 * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
2972 			 * Note that we try to prevent the network stack from sending the ACK during the
2973 			 * connect() when a pure TCP check is used (without PROXY protocol).
2974 			 */
2975 		fail_check:
2976 			switch (ret) {
2977 			case SF_ERR_NONE:
2978 				/* we allow up to min(inter, timeout.connect) for a connection
2979 				 * to establish but only when timeout.check is set
2980 				 * as it may be to short for a full check otherwise
2981 				 */
2982 				t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2983 
2984 				if (proxy->timeout.check && proxy->timeout.connect) {
2985 					int t_con = tick_add(now_ms, proxy->timeout.connect);
2986 					t->expire = tick_first(t->expire, t_con);
2987 				}
2988 				break;
2989 			case SF_ERR_SRVTO: /* ETIMEDOUT */
2990 			case SF_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
2991 				step = tcpcheck_get_step_id(check);
2992 				chunk_printf(&trash, "TCPCHK error establishing connection at step %d: %s",
2993 						step, strerror(errno));
2994 				comment = tcpcheck_get_step_comment(check, step);
2995 				if (comment)
2996 					chunk_appendf(&trash, " comment: '%s'", comment);
2997 				set_server_check_status(check, HCHK_STATUS_L4CON,
2998 							trash.area);
2999 				goto out_end_tcpcheck;
3000 			case SF_ERR_PRXCOND:
3001 			case SF_ERR_RESOURCE:
3002 			case SF_ERR_INTERNAL:
3003 				step = tcpcheck_get_step_id(check);
3004 				chunk_printf(&trash, "TCPCHK error establishing connection at step %d", step);
3005 				comment = tcpcheck_get_step_comment(check, step);
3006 				if (comment)
3007 					chunk_appendf(&trash, " comment: '%s'", comment);
3008 				set_server_check_status(check, HCHK_STATUS_SOCKERR,
3009 							trash.area);
3010 				goto out_end_tcpcheck;
3011 			}
3012 
3013 			/* allow next rule */
3014 			check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3015 
3016 			/* bypass all comment rules */
3017 			while (&check->current_step->list != head &&
3018 				check->current_step->action == TCPCHK_ACT_COMMENT)
3019 				check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3020 
3021 			if (&check->current_step->list == head)
3022 				break;
3023 
3024 			/* don't do anything until the connection is established */
3025 			if (!(conn->flags & CO_FL_CONNECTED))
3026 				break;
3027 
3028 		} /* end 'connect' */
3029 		else if (check->current_step->action == TCPCHK_ACT_SEND) {
3030 			/* mark the step as started */
3031 			check->last_started_step = check->current_step;
3032 
3033 			/* reset the read buffer */
3034 			if (*b_head(&check->bi) != '\0') {
3035 				*b_head(&check->bi) = '\0';
3036 				b_reset(&check->bi);
3037 			}
3038 
3039 			if (conn->flags & CO_FL_SOCK_WR_SH) {
3040 				conn->flags |= CO_FL_ERROR;
3041 				chk_report_conn_err(check, 0, 0);
3042 				goto out_end_tcpcheck;
3043 			}
3044 
3045 			if (check->current_step->string_len >= b_size(&check->bo)) {
3046 				chunk_printf(&trash, "tcp-check send : string too large (%d) for buffer size (%u) at step %d",
3047 					     check->current_step->string_len, (unsigned int)b_size(&check->bo),
3048 					     tcpcheck_get_step_id(check));
3049 				set_server_check_status(check, HCHK_STATUS_L7RSP,
3050 							trash.area);
3051 				goto out_end_tcpcheck;
3052 			}
3053 
3054 			/* do not try to send if there is no space */
3055 			if (check->current_step->string_len >= b_room(&check->bo))
3056 				continue;
3057 
3058 			b_putblk(&check->bo, check->current_step->string, check->current_step->string_len);
3059 			*b_tail(&check->bo) = '\0'; /* to make gdb output easier to read */
3060 
3061 			/* go to next rule and try to send */
3062 			check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3063 
3064 			/* bypass all comment rules */
3065 			while (&check->current_step->list != head &&
3066 				check->current_step->action == TCPCHK_ACT_COMMENT)
3067 				check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3068 
3069 		} /* end 'send' */
3070 		else if (check->current_step->action == TCPCHK_ACT_EXPECT) {
3071 			if (unlikely(check->result == CHK_RES_FAILED))
3072 				goto out_end_tcpcheck;
3073 
3074 			/* If we already subscribed, then we tried to received
3075 			 * and failed, so there's no point trying again.
3076 			 */
3077 			if (check->wait_list.events & SUB_RETRY_RECV)
3078 				break;
3079 			if (cs->conn->mux->rcv_buf(cs, &check->bi, b_size(&check->bi), 0) <= 0) {
3080 				if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH) || cs->flags & CS_FL_ERROR) {
3081 					done = 1;
3082 					if ((conn->flags & CO_FL_ERROR || cs->flags & CS_FL_ERROR) && !b_data(&check->bi)) {
3083 						/* Report network errors only if we got no other data. Otherwise
3084 						 * we'll let the upper layers decide whether the response is OK
3085 						 * or not. It is very common that an RST sent by the server is
3086 						 * reported as an error just after the last data chunk.
3087 						 */
3088 						chk_report_conn_err(check, errno, 0);
3089 						goto out_end_tcpcheck;
3090 					}
3091 				}
3092 				else {
3093 					conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
3094 					break;
3095 				}
3096 			}
3097 
3098 			/* mark the step as started */
3099 			check->last_started_step = check->current_step;
3100 
3101 
3102 			/* Intermediate or complete response received.
3103 			 * Terminate string in b_head(&check->bi) buffer.
3104 			 */
3105 			if (b_data(&check->bi) < b_size(&check->bi)) {
3106 				b_head(&check->bi)[b_data(&check->bi)] = '\0';
3107 			}
3108 			else {
3109 				b_head(&check->bi)[b_data(&check->bi) - 1] = '\0';
3110 				done = 1; /* buffer full, don't wait for more data */
3111 			}
3112 
3113 			contentptr = b_head(&check->bi);
3114 
3115 			/* Check that response body is not empty... */
3116 			if (!b_data(&check->bi)) {
3117 				if (!done)
3118 					continue;
3119 
3120 				/* empty response */
3121 				step = tcpcheck_get_step_id(check);
3122 				chunk_printf(&trash, "TCPCHK got an empty response at step %d", step);
3123 				comment = tcpcheck_get_step_comment(check, step);
3124 				if (comment)
3125 					chunk_appendf(&trash, " comment: '%s'", comment);
3126 				set_server_check_status(check, HCHK_STATUS_L7RSP,
3127 							trash.area);
3128 
3129 				goto out_end_tcpcheck;
3130 			}
3131 
3132 		tcpcheck_expect:
3133 			if (!done && (check->current_step->string != NULL) && (b_data(&check->bi) < check->current_step->string_len) )
3134 				continue; /* try to read more */
3135 
3136 			if (check->current_step->string != NULL)
3137 				ret = my_memmem(contentptr, b_data(&check->bi), check->current_step->string, check->current_step->string_len) != NULL;
3138 			else if (check->current_step->expect_regex != NULL)
3139 				ret = regex_exec(check->current_step->expect_regex, contentptr);
3140 
3141 			if (!ret && !done)
3142 				continue; /* try to read more */
3143 
3144 			/* matched */
3145 			step = tcpcheck_get_step_id(check);
3146 			if (ret) {
3147 				/* matched but we did not want to => ERROR */
3148 				if (check->current_step->inverse) {
3149 					/* we were looking for a string */
3150 					if (check->current_step->string != NULL) {
3151 						chunk_printf(&trash, "TCPCHK matched unwanted content '%s' at step %d",
3152 						             check->current_step->string, step);
3153 					}
3154 					else {
3155 					/* we were looking for a regex */
3156 						chunk_printf(&trash, "TCPCHK matched unwanted content (regex) at step %d", step);
3157 					}
3158 					comment = tcpcheck_get_step_comment(check, step);
3159 					if (comment)
3160 						chunk_appendf(&trash, " comment: '%s'", comment);
3161 					set_server_check_status(check, HCHK_STATUS_L7RSP,
3162 								trash.area);
3163 					goto out_end_tcpcheck;
3164 				}
3165 				/* matched and was supposed to => OK, next step */
3166 				else {
3167 					/* allow next rule */
3168 					check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3169 
3170 					/* bypass all comment rules */
3171 					while (&check->current_step->list != head &&
3172 					       check->current_step->action == TCPCHK_ACT_COMMENT)
3173 						check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3174 
3175 					if (&check->current_step->list == head)
3176 						break;
3177 
3178 					if (check->current_step->action == TCPCHK_ACT_EXPECT)
3179 						goto tcpcheck_expect;
3180 				}
3181 			}
3182 			else {
3183 			/* not matched */
3184 				/* not matched and was not supposed to => OK, next step */
3185 				if (check->current_step->inverse) {
3186 					/* allow next rule */
3187 					check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3188 
3189 					/* bypass all comment rules */
3190 					while (&check->current_step->list != head &&
3191 					       check->current_step->action == TCPCHK_ACT_COMMENT)
3192 						check->current_step = LIST_NEXT(&check->current_step->list, struct tcpcheck_rule *, list);
3193 
3194 					if (&check->current_step->list == head)
3195 						break;
3196 
3197 					if (check->current_step->action == TCPCHK_ACT_EXPECT)
3198 						goto tcpcheck_expect;
3199 				}
3200 				/* not matched but was supposed to => ERROR */
3201 				else {
3202 					/* we were looking for a string */
3203 					if (check->current_step->string != NULL) {
3204 						chunk_printf(&trash, "TCPCHK did not match content '%s' at step %d",
3205 						             check->current_step->string, step);
3206 					}
3207 					else {
3208 					/* we were looking for a regex */
3209 						chunk_printf(&trash, "TCPCHK did not match content (regex) at step %d",
3210 								step);
3211 					}
3212 					comment = tcpcheck_get_step_comment(check, step);
3213 					if (comment)
3214 						chunk_appendf(&trash, " comment: '%s'", comment);
3215 					set_server_check_status(check, HCHK_STATUS_L7RSP,
3216 								trash.area);
3217 					goto out_end_tcpcheck;
3218 				}
3219 			}
3220 		} /* end expect */
3221 	} /* end loop over double chained step list */
3222 
3223 	/* don't do anything until the connection is established */
3224 	if (!(conn->flags & CO_FL_CONNECTED)) {
3225 		/* update expire time, should be done by process_chk */
3226 		/* we allow up to min(inter, timeout.connect) for a connection
3227 		 * to establish but only when timeout.check is set
3228 		 * as it may be to short for a full check otherwise
3229 		 */
3230 		while (tick_is_expired(t->expire, now_ms)) {
3231 			int t_con;
3232 
3233 			t_con = tick_add(t->expire, proxy->timeout.connect);
3234 			t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
3235 
3236 			if (proxy->timeout.check)
3237 				t->expire = tick_first(t->expire, t_con);
3238 		}
3239 		goto out;
3240 	}
3241 
3242 	/* We're waiting for some I/O to complete, we've reached the end of the
3243 	 * rules, or both. Do what we have to do, otherwise we're done.
3244 	 */
3245 	if (&check->current_step->list == head && !b_data(&check->bo)) {
3246 		set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
3247 		goto out_end_tcpcheck;
3248 	}
3249 
3250 	if (&check->current_step->list != head &&
3251 	    check->current_step->action == TCPCHK_ACT_EXPECT)
3252 		__event_srv_chk_r(cs);
3253 	goto out;
3254 
3255  out_end_tcpcheck:
3256 	/* collect possible new errors */
3257 	if ((conn && conn->flags & CO_FL_ERROR) || (cs && cs->flags & CS_FL_ERROR))
3258 		chk_report_conn_err(check, 0, 0);
3259 
3260 	/* cleanup before leaving */
3261 	check->current_step = NULL;
3262 
3263 	if (check->result == CHK_RES_FAILED)
3264 		conn->flags |= CO_FL_ERROR;
3265 
3266  out:
3267 	return retcode;
3268 }
3269 
init_check(struct check * check,int type)3270 const char *init_check(struct check *check, int type)
3271 {
3272 	check->type = type;
3273 
3274 	b_reset(&check->bi); check->bi.size = global.tune.chksize;
3275 	b_reset(&check->bo); check->bo.size = global.tune.chksize;
3276 
3277 	check->bi.area = calloc(check->bi.size, sizeof(char));
3278 	check->bo.area = calloc(check->bo.size, sizeof(char));
3279 
3280 	if (!check->bi.area || !check->bo.area)
3281 		return "out of memory while allocating check buffer";
3282 
3283 	check->wait_list.task = tasklet_new();
3284 	if (!check->wait_list.task)
3285 		return "out of memroy while allocating check tasklet";
3286 	check->wait_list.events = 0;
3287 	check->wait_list.task->process = event_srv_chk_io;
3288 	check->wait_list.task->context = check;
3289 	return NULL;
3290 }
3291 
free_check(struct check * check)3292 void free_check(struct check *check)
3293 {
3294 	if (check->task) {
3295 		task_delete(check->task);
3296 		task_free(check->task);
3297 	}
3298 	if (check->wait_list.task)
3299 		tasklet_free(check->wait_list.task);
3300 
3301 	free(check->bi.area);
3302 	free(check->bo.area);
3303 	if (check->cs) {
3304 		free(check->cs->conn);
3305 		check->cs->conn = NULL;
3306 		cs_free(check->cs);
3307 		check->cs = NULL;
3308 	}
3309 }
3310 
email_alert_free(struct email_alert * alert)3311 void email_alert_free(struct email_alert *alert)
3312 {
3313 	struct tcpcheck_rule *rule, *back;
3314 
3315 	if (!alert)
3316 		return;
3317 
3318 	list_for_each_entry_safe(rule, back, &alert->tcpcheck_rules, list) {
3319 		LIST_DEL(&rule->list);
3320 		free(rule->comment);
3321 		free(rule->string);
3322 		if (rule->expect_regex)
3323 			regex_free(rule->expect_regex);
3324 		pool_free(pool_head_tcpcheck_rule, rule);
3325 	}
3326 	pool_free(pool_head_email_alert, alert);
3327 }
3328 
process_email_alert(struct task * t,void * context,unsigned short state)3329 static struct task *process_email_alert(struct task *t, void *context, unsigned short state)
3330 {
3331 	struct check        *check = context;
3332 	struct email_alertq *q;
3333 	struct email_alert  *alert;
3334 
3335 	q = container_of(check, typeof(*q), check);
3336 
3337 	HA_SPIN_LOCK(EMAIL_ALERTS_LOCK, &q->lock);
3338 	while (1) {
3339 		if (!(check->state & CHK_ST_ENABLED)) {
3340 			if (LIST_ISEMPTY(&q->email_alerts)) {
3341 				/* All alerts processed, queue the task */
3342 				t->expire = TICK_ETERNITY;
3343 				task_queue(t);
3344 				goto end;
3345 			}
3346 
3347 			alert = LIST_NEXT(&q->email_alerts, typeof(alert), list);
3348 			LIST_DEL(&alert->list);
3349 			t->expire             = now_ms;
3350 			check->tcpcheck_rules = &alert->tcpcheck_rules;
3351 			check->status         = HCHK_STATUS_INI;
3352 			check->state         |= CHK_ST_ENABLED;
3353 		}
3354 
3355 		process_chk(t, context, state);
3356 		if (check->state & CHK_ST_INPROGRESS)
3357 			break;
3358 
3359 		alert = container_of(check->tcpcheck_rules, typeof(*alert), tcpcheck_rules);
3360 		email_alert_free(alert);
3361 		check->tcpcheck_rules = NULL;
3362 		check->server         = NULL;
3363 		check->state         &= ~CHK_ST_ENABLED;
3364 	}
3365   end:
3366 	HA_SPIN_UNLOCK(EMAIL_ALERTS_LOCK, &q->lock);
3367 	return t;
3368 }
3369 
3370 /* Initializes mailer alerts for the proxy <p> using <mls> parameters.
3371  *
3372  * The function returns 1 in success case, otherwise, it returns 0 and err is
3373  * filled.
3374  */
init_email_alert(struct mailers * mls,struct proxy * p,char ** err)3375 int init_email_alert(struct mailers *mls, struct proxy *p, char **err)
3376 {
3377 	struct mailer       *mailer;
3378 	struct email_alertq *queues;
3379 	const char          *err_str;
3380 	int                  i = 0;
3381 
3382 	if ((queues = calloc(mls->count, sizeof(*queues))) == NULL) {
3383 		memprintf(err, "out of memory while allocating mailer alerts queues");
3384 		goto fail_no_queue;
3385 	}
3386 
3387 	for (mailer = mls->mailer_list; mailer; i++, mailer = mailer->next) {
3388 		struct email_alertq *q     = &queues[i];
3389 		struct check        *check = &q->check;
3390 		struct task         *t;
3391 
3392 		LIST_INIT(&q->email_alerts);
3393 		HA_SPIN_INIT(&q->lock);
3394 		check->inter = mls->timeout.mail;
3395 		check->rise = DEF_AGENT_RISETIME;
3396 		check->proxy = p;
3397 		check->fall = DEF_AGENT_FALLTIME;
3398 		if ((err_str = init_check(check, PR_O2_TCPCHK_CHK))) {
3399 			memprintf(err, "%s", err_str);
3400 			goto error;
3401 		}
3402 
3403 		check->xprt = mailer->xprt;
3404 		check->addr = mailer->addr;
3405 		check->port = get_host_port(&mailer->addr);
3406 
3407 		if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
3408 			memprintf(err, "out of memory while allocating mailer alerts task");
3409 			goto error;
3410 		}
3411 
3412 		check->task = t;
3413 		t->process = process_email_alert;
3414 		t->context = check;
3415 
3416 		/* check this in one ms */
3417 		t->expire    = TICK_ETERNITY;
3418 		check->start = now;
3419 		task_queue(t);
3420 	}
3421 
3422 	mls->users++;
3423 	free(p->email_alert.mailers.name);
3424 	p->email_alert.mailers.m = mls;
3425 	p->email_alert.queues    = queues;
3426 	return 0;
3427 
3428   error:
3429 	for (i = 0; i < mls->count; i++) {
3430 		struct email_alertq *q     = &queues[i];
3431 		struct check        *check = &q->check;
3432 
3433 		free_check(check);
3434 	}
3435 	free(queues);
3436   fail_no_queue:
3437 	return 1;
3438 }
3439 
3440 
add_tcpcheck_expect_str(struct list * list,const char * str)3441 static int add_tcpcheck_expect_str(struct list *list, const char *str)
3442 {
3443 	struct tcpcheck_rule *tcpcheck;
3444 
3445 	if ((tcpcheck = pool_alloc(pool_head_tcpcheck_rule)) == NULL)
3446 		return 0;
3447 	memset(tcpcheck, 0, sizeof(*tcpcheck));
3448 	tcpcheck->action       = TCPCHK_ACT_EXPECT;
3449 	tcpcheck->string       = strdup(str);
3450 	tcpcheck->expect_regex = NULL;
3451 	tcpcheck->comment      = NULL;
3452 	if (!tcpcheck->string) {
3453 		pool_free(pool_head_tcpcheck_rule, tcpcheck);
3454 		return 0;
3455 	}
3456 
3457 	LIST_ADDQ(list, &tcpcheck->list);
3458 	return 1;
3459 }
3460 
add_tcpcheck_send_strs(struct list * list,const char * const * strs)3461 static int add_tcpcheck_send_strs(struct list *list, const char * const *strs)
3462 {
3463 	struct tcpcheck_rule *tcpcheck;
3464 	const char *in;
3465 	char *dst;
3466 	int i;
3467 
3468 	if ((tcpcheck = pool_alloc(pool_head_tcpcheck_rule)) == NULL)
3469 		return 0;
3470 	memset(tcpcheck, 0, sizeof(*tcpcheck));
3471 	tcpcheck->action       = TCPCHK_ACT_SEND;
3472 	tcpcheck->expect_regex = NULL;
3473 	tcpcheck->comment      = NULL;
3474 	tcpcheck->string_len = 0;
3475 	for (i = 0; strs[i]; i++)
3476 		tcpcheck->string_len += strlen(strs[i]);
3477 
3478 	tcpcheck->string = malloc(tcpcheck->string_len + 1);
3479 	if (!tcpcheck->string) {
3480 		pool_free(pool_head_tcpcheck_rule, tcpcheck);
3481 		return 0;
3482 	}
3483 
3484 	dst = tcpcheck->string;
3485 	for (i = 0; strs[i]; i++)
3486 		for (in = strs[i]; (*dst = *in++); dst++);
3487 	*dst = 0;
3488 
3489 	LIST_ADDQ(list, &tcpcheck->list);
3490 	return 1;
3491 }
3492 
enqueue_one_email_alert(struct proxy * p,struct server * s,struct email_alertq * q,const char * msg)3493 static int enqueue_one_email_alert(struct proxy *p, struct server *s,
3494 				   struct email_alertq *q, const char *msg)
3495 {
3496 	struct email_alert   *alert;
3497 	struct tcpcheck_rule *tcpcheck;
3498 	struct check *check = &q->check;
3499 
3500 	if ((alert = pool_alloc(pool_head_email_alert)) == NULL)
3501 		goto error;
3502 	LIST_INIT(&alert->list);
3503 	LIST_INIT(&alert->tcpcheck_rules);
3504 	alert->srv = s;
3505 
3506 	if ((tcpcheck = pool_alloc(pool_head_tcpcheck_rule)) == NULL)
3507 		goto error;
3508 	memset(tcpcheck, 0, sizeof(*tcpcheck));
3509 	tcpcheck->action       = TCPCHK_ACT_CONNECT;
3510 	tcpcheck->comment      = NULL;
3511 	tcpcheck->string       = NULL;
3512 	tcpcheck->expect_regex = NULL;
3513 	LIST_ADDQ(&alert->tcpcheck_rules, &tcpcheck->list);
3514 
3515 	if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "220 "))
3516 		goto error;
3517 
3518 	{
3519 		const char * const strs[4] = { "EHLO ", p->email_alert.myhostname, "\r\n" };
3520 		if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3521 			goto error;
3522 	}
3523 
3524 	if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3525 		goto error;
3526 
3527 	{
3528 		const char * const strs[4] = { "MAIL FROM:<", p->email_alert.from, ">\r\n" };
3529 		if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3530 			goto error;
3531 	}
3532 
3533 	if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3534 		goto error;
3535 
3536 	{
3537 		const char * const strs[4] = { "RCPT TO:<", p->email_alert.to, ">\r\n" };
3538 		if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3539 			goto error;
3540 	}
3541 
3542 	if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3543 		goto error;
3544 
3545 	{
3546 		const char * const strs[2] = { "DATA\r\n" };
3547 		if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3548 			goto error;
3549 	}
3550 
3551 	if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "354 "))
3552 		goto error;
3553 
3554 	{
3555 		struct tm tm;
3556 		char datestr[48];
3557 		const char * const strs[18] = {
3558 			"From: ", p->email_alert.from, "\r\n",
3559 			"To: ", p->email_alert.to, "\r\n",
3560 			"Date: ", datestr, "\r\n",
3561 			"Subject: [HAproxy Alert] ", msg, "\r\n",
3562 			"\r\n",
3563 			msg, "\r\n",
3564 			"\r\n",
3565 			".\r\n",
3566 			NULL
3567 		};
3568 
3569 		get_localtime(date.tv_sec, &tm);
3570 
3571 		if (strftime(datestr, sizeof(datestr), "%a, %d %b %Y %T %z (%Z)", &tm) == 0) {
3572 			goto error;
3573 		}
3574 
3575 		if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3576 			goto error;
3577 	}
3578 
3579 	if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3580 		goto error;
3581 
3582 	{
3583 		const char * const strs[2] = { "QUIT\r\n" };
3584 		if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3585 			goto error;
3586 	}
3587 
3588 	if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "221 "))
3589 		goto error;
3590 
3591 	HA_SPIN_LOCK(EMAIL_ALERTS_LOCK, &q->lock);
3592 	task_wakeup(check->task, TASK_WOKEN_MSG);
3593 	LIST_ADDQ(&q->email_alerts, &alert->list);
3594 	HA_SPIN_UNLOCK(EMAIL_ALERTS_LOCK, &q->lock);
3595 	return 1;
3596 
3597 error:
3598 	email_alert_free(alert);
3599 	return 0;
3600 }
3601 
enqueue_email_alert(struct proxy * p,struct server * s,const char * msg)3602 static void enqueue_email_alert(struct proxy *p, struct server *s, const char *msg)
3603 {
3604 	int i;
3605 	struct mailer *mailer;
3606 
3607 	for (i = 0, mailer = p->email_alert.mailers.m->mailer_list;
3608 	     i < p->email_alert.mailers.m->count; i++, mailer = mailer->next) {
3609 		if (!enqueue_one_email_alert(p, s, &p->email_alert.queues[i], msg)) {
3610 			ha_alert("Email alert [%s] could not be enqueued: out of memory\n", p->id);
3611 			return;
3612 		}
3613 	}
3614 
3615 	return;
3616 }
3617 
3618 /*
3619  * Send email alert if configured.
3620  */
send_email_alert(struct server * s,int level,const char * format,...)3621 void send_email_alert(struct server *s, int level, const char *format, ...)
3622 {
3623 	va_list argp;
3624 	char buf[1024];
3625 	int len;
3626 	struct proxy *p = s->proxy;
3627 
3628 	if (!p->email_alert.mailers.m || level > p->email_alert.level || format == NULL)
3629 		return;
3630 
3631 	va_start(argp, format);
3632 	len = vsnprintf(buf, sizeof(buf), format, argp);
3633 	va_end(argp);
3634 
3635 	if (len < 0 || len >= sizeof(buf)) {
3636 		ha_alert("Email alert [%s] could not format message\n", p->id);
3637 		return;
3638 	}
3639 
3640 	enqueue_email_alert(p, s, buf);
3641 }
3642 
3643 /*
3644  * Return value:
3645  *   the port to be used for the health check
3646  *   0 in case no port could be found for the check
3647  */
srv_check_healthcheck_port(struct check * chk)3648 int srv_check_healthcheck_port(struct check *chk)
3649 {
3650 	int i = 0;
3651 	struct server *srv = NULL;
3652 
3653 	srv = chk->server;
3654 
3655 	/* by default, we use the health check port ocnfigured */
3656 	if (chk->port > 0)
3657 		return chk->port;
3658 
3659 	/* try to get the port from check_core.addr if check.port not set */
3660 	i = get_host_port(&chk->addr);
3661 	if (i > 0)
3662 		return i;
3663 
3664 	/* try to get the port from server address */
3665 	/* prevent MAPPORTS from working at this point, since checks could
3666 	 * not be performed in such case (MAPPORTS impose a relative ports
3667 	 * based on live traffic)
3668 	 */
3669 	if (srv->flags & SRV_F_MAPPORTS)
3670 		return 0;
3671 
3672 	i = srv->svc_port; /* by default */
3673 	if (i > 0)
3674 		return i;
3675 
3676 	return 0;
3677 }
3678 
init_srv_check(struct server * srv)3679 static int init_srv_check(struct server *srv)
3680 {
3681 	const char *err;
3682 	struct tcpcheck_rule *r;
3683 	int ret = 0;
3684 
3685 	if (!srv->do_check)
3686 		goto out;
3687 
3688 
3689 	/* If neither a port nor an addr was specified and no check transport
3690 	 * layer is forced, then the transport layer used by the checks is the
3691 	 * same as for the production traffic. Otherwise we use raw_sock by
3692 	 * default, unless one is specified.
3693 	 */
3694 	if (!srv->check.port && !is_addr(&srv->check.addr)) {
3695 		if (!srv->check.use_ssl && srv->use_ssl != -1) {
3696 			srv->check.use_ssl = srv->use_ssl;
3697 			srv->check.xprt    = srv->xprt;
3698 		}
3699 		else if (srv->check.use_ssl == 1)
3700 			srv->check.xprt = xprt_get(XPRT_SSL);
3701 
3702 		srv->check.send_proxy |= (srv->pp_opts);
3703 	}
3704 	else if (srv->check.use_ssl == 1)
3705 		srv->check.xprt = xprt_get(XPRT_SSL);
3706 
3707 	/* validate <srv> server health-check settings */
3708 
3709 	/* We need at least a service port, a check port or the first tcp-check
3710 	 * rule must be a 'connect' one when checking an IPv4/IPv6 server.
3711 	 */
3712 	if ((srv_check_healthcheck_port(&srv->check) != 0) ||
3713 	    (!is_inet_addr(&srv->check.addr) && (is_addr(&srv->check.addr) || !is_inet_addr(&srv->addr))))
3714 		goto init;
3715 
3716 	if (!LIST_ISEMPTY(&srv->proxy->tcpcheck_rules)) {
3717 		ha_alert("config: %s '%s': server '%s' has neither service port nor check port.\n",
3718 			 proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
3719 		ret |= ERR_ALERT | ERR_ABORT;
3720 		goto out;
3721 	}
3722 
3723 	/* search the first action (connect / send / expect) in the list */
3724 	r = get_first_tcpcheck_rule(&srv->proxy->tcpcheck_rules);
3725 	if (!r || (r->action != TCPCHK_ACT_CONNECT) || !r->port) {
3726 		ha_alert("config: %s '%s': server '%s' has neither service port nor check port "
3727 			 "nor tcp_check rule 'connect' with port information.\n",
3728 			 proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
3729 		ret |= ERR_ALERT | ERR_ABORT;
3730 		goto out;
3731 	}
3732 
3733 	/* scan the tcp-check ruleset to ensure a port has been configured */
3734 	list_for_each_entry(r, &srv->proxy->tcpcheck_rules, list) {
3735 		if ((r->action == TCPCHK_ACT_CONNECT) && (!r->port)) {
3736 			ha_alert("config: %s '%s': server '%s' has neither service port nor check port, "
3737 				 "and a tcp_check rule 'connect' with no port information.\n",
3738 				 proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
3739 			ret |= ERR_ALERT | ERR_ABORT;
3740 			goto out;
3741 		}
3742 	}
3743 
3744   init:
3745 	err = init_check(&srv->check, srv->proxy->options2 & PR_O2_CHK_ANY);
3746 	if (err) {
3747 		ha_alert("config: %s '%s': unable to init check for server '%s' (%s).\n",
3748 			 proxy_type_str(srv->proxy), srv->proxy->id, srv->id, err);
3749 		ret |= ERR_ALERT | ERR_ABORT;
3750 		goto out;
3751 	}
3752 	srv->check.state |= CHK_ST_CONFIGURED | CHK_ST_ENABLED;
3753 	global.maxsock++;
3754 
3755   out:
3756 	return ret;
3757 }
3758 
init_srv_agent_check(struct server * srv)3759 static int init_srv_agent_check(struct server *srv)
3760 {
3761 	const char *err;
3762 	int ret = 0;
3763 
3764 	if (!srv->do_agent)
3765 		goto out;
3766 
3767 	err = init_check(&srv->agent, PR_O2_LB_AGENT_CHK);
3768 	if (err) {
3769 		ha_alert("config: %s '%s': unable to init agent-check for server '%s' (%s).\n",
3770 			 proxy_type_str(srv->proxy), srv->proxy->id, srv->id, err);
3771 		ret |= ERR_ALERT | ERR_ABORT;
3772 		goto out;
3773 	}
3774 
3775 	if (!srv->agent.inter)
3776 		srv->agent.inter = srv->check.inter;
3777 
3778 	srv->agent.state |= CHK_ST_CONFIGURED | CHK_ST_ENABLED | CHK_ST_AGENT;
3779 	global.maxsock++;
3780 
3781   out:
3782 	return ret;
3783 }
3784 
deinit_srv_check(struct server * srv)3785 void deinit_srv_check(struct server *srv)
3786 {
3787 	if (srv->do_check)
3788 		free_check(&srv->check);
3789 }
3790 
3791 
deinit_srv_agent_check(struct server * srv)3792 void deinit_srv_agent_check(struct server *srv)
3793 {
3794 	if (srv->do_agent)
3795 		free_check(&srv->agent);
3796 	free(srv->agent.send_string);
3797 }
3798 
init_servers_checks()3799 static int init_servers_checks()
3800 {
3801 	struct proxy *px;
3802 	struct server *s;
3803 	int ret = 0;
3804 
3805 	for (px = proxies_list; px; px = px->next) {
3806 		for (s = px->srv; s; s = s->next) {
3807 			ret |= init_srv_check(s);
3808 			if (ret & (ERR_ABORT|ERR_FATAL))
3809 				goto end;
3810 			ret |= init_srv_agent_check(s);
3811 			if (ret & (ERR_ABORT|ERR_FATAL))
3812 				goto end;
3813 		}
3814 	}
3815 	ret = start_checks();
3816   end:
3817 	return ret;
3818 }
3819 
3820 REGISTER_POST_CHECK(init_servers_checks);
3821 
3822 /*
3823  * Local variables:
3824  *  c-indent-level: 8
3825  *  c-basic-offset: 8
3826  * End:
3827  */
3828