blob: 5bd237ad6f558b4fd94ac09d30aa56b3f02eaa44 [file] [log] [blame]
Willy Tarreau51cd5952020-06-05 12:25:38 +02001/*
2 * Health-checks functions.
3 *
4 * Copyright 2000-2009,2020 Willy Tarreau <w@1wt.eu>
5 * Copyright 2007-2010 Krzysztof Piotr Oledzki <ole@ans.pl>
6 * Copyright 2013 Baptiste Assmann <bedis9@gmail.com>
7 * Copyright 2020 Gaetan Rivet <grive@u256.net>
8 * Copyright 2020 Christopher Faulet <cfaulet@haproxy.com>
9 *
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version
13 * 2 of the License, or (at your option) any later version.
14 *
15 */
16
17#include <sys/resource.h>
18#include <sys/socket.h>
19#include <sys/types.h>
20#include <sys/wait.h>
21#include <netinet/in.h>
22#include <netinet/tcp.h>
23#include <arpa/inet.h>
24
25#include <ctype.h>
26#include <errno.h>
27#include <fcntl.h>
28#include <signal.h>
29#include <stdarg.h>
30#include <stdio.h>
31#include <stdlib.h>
32#include <string.h>
33#include <time.h>
34#include <unistd.h>
35
36#include <haproxy/action.h>
37#include <haproxy/api.h>
38#include <haproxy/cfgparse.h>
39#include <haproxy/check.h>
40#include <haproxy/chunk.h>
41#include <haproxy/connection.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020042#include <haproxy/errors.h>
Willy Tarreau51cd5952020-06-05 12:25:38 +020043#include <haproxy/global.h>
44#include <haproxy/h1.h>
45#include <haproxy/http.h>
46#include <haproxy/http_htx.h>
47#include <haproxy/htx.h>
48#include <haproxy/istbuf.h>
49#include <haproxy/list.h>
50#include <haproxy/log.h>
Willy Tarreau51cd5952020-06-05 12:25:38 +020051#include <haproxy/protocol.h>
52#include <haproxy/proxy-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020053#include <haproxy/regex.h>
54#include <haproxy/sample.h>
Willy Tarreau51cd5952020-06-05 12:25:38 +020055#include <haproxy/server.h>
56#include <haproxy/ssl_sock.h>
Willy Tarreau51cd5952020-06-05 12:25:38 +020057#include <haproxy/task.h>
58#include <haproxy/tcpcheck.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020059#include <haproxy/time.h>
60#include <haproxy/tools.h>
Willy Tarreau51cd5952020-06-05 12:25:38 +020061#include <haproxy/vars.h>
62
63
64/* Global tree to share all tcp-checks */
65struct eb_root shared_tcpchecks = EB_ROOT;
66
67
68DECLARE_POOL(pool_head_tcpcheck_rule, "tcpcheck_rule", sizeof(struct tcpcheck_rule));
69
70/**************************************************************************/
71/*************** Init/deinit tcp-check rules and ruleset ******************/
72/**************************************************************************/
73/* Releases memory allocated for a log-format string */
74static void free_tcpcheck_fmt(struct list *fmt)
75{
76 struct logformat_node *lf, *lfb;
77
78 list_for_each_entry_safe(lf, lfb, fmt, list) {
79 LIST_DEL(&lf->list);
80 release_sample_expr(lf->expr);
81 free(lf->arg);
82 free(lf);
83 }
84}
85
86/* Releases memory allocated for an HTTP header used in a tcp-check send rule */
87void free_tcpcheck_http_hdr(struct tcpcheck_http_hdr *hdr)
88{
89 if (!hdr)
90 return;
91
92 free_tcpcheck_fmt(&hdr->value);
93 istfree(&hdr->name);
94 free(hdr);
95}
96
97/* Releases memory allocated for an HTTP header list used in a tcp-check send
98 * rule
99 */
100static void free_tcpcheck_http_hdrs(struct list *hdrs)
101{
102 struct tcpcheck_http_hdr *hdr, *bhdr;
103
104 list_for_each_entry_safe(hdr, bhdr, hdrs, list) {
105 LIST_DEL(&hdr->list);
106 free_tcpcheck_http_hdr(hdr);
107 }
108}
109
110/* Releases memory allocated for a tcp-check. If in_pool is set, it means the
111 * tcp-check was allocated using a memory pool (it is used to instantiate email
112 * alerts).
113 */
114void free_tcpcheck(struct tcpcheck_rule *rule, int in_pool)
115{
116 if (!rule)
117 return;
118
119 free(rule->comment);
120 switch (rule->action) {
121 case TCPCHK_ACT_SEND:
122 switch (rule->send.type) {
123 case TCPCHK_SEND_STRING:
124 case TCPCHK_SEND_BINARY:
125 istfree(&rule->send.data);
126 break;
127 case TCPCHK_SEND_STRING_LF:
128 case TCPCHK_SEND_BINARY_LF:
129 free_tcpcheck_fmt(&rule->send.fmt);
130 break;
131 case TCPCHK_SEND_HTTP:
132 free(rule->send.http.meth.str.area);
133 if (!(rule->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
134 istfree(&rule->send.http.uri);
135 else
136 free_tcpcheck_fmt(&rule->send.http.uri_fmt);
137 istfree(&rule->send.http.vsn);
138 free_tcpcheck_http_hdrs(&rule->send.http.hdrs);
139 if (!(rule->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
140 istfree(&rule->send.http.body);
141 else
142 free_tcpcheck_fmt(&rule->send.http.body_fmt);
143 break;
144 case TCPCHK_SEND_UNDEF:
145 break;
146 }
147 break;
148 case TCPCHK_ACT_EXPECT:
149 free_tcpcheck_fmt(&rule->expect.onerror_fmt);
150 free_tcpcheck_fmt(&rule->expect.onsuccess_fmt);
151 release_sample_expr(rule->expect.status_expr);
152 switch (rule->expect.type) {
153 case TCPCHK_EXPECT_HTTP_STATUS:
154 free(rule->expect.codes.codes);
155 break;
156 case TCPCHK_EXPECT_STRING:
157 case TCPCHK_EXPECT_BINARY:
158 case TCPCHK_EXPECT_HTTP_BODY:
159 istfree(&rule->expect.data);
160 break;
161 case TCPCHK_EXPECT_STRING_REGEX:
162 case TCPCHK_EXPECT_BINARY_REGEX:
163 case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
164 case TCPCHK_EXPECT_HTTP_BODY_REGEX:
165 regex_free(rule->expect.regex);
166 break;
167 case TCPCHK_EXPECT_STRING_LF:
168 case TCPCHK_EXPECT_BINARY_LF:
169 case TCPCHK_EXPECT_HTTP_BODY_LF:
170 free_tcpcheck_fmt(&rule->expect.fmt);
171 break;
172 case TCPCHK_EXPECT_HTTP_HEADER:
173 if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG)
174 regex_free(rule->expect.hdr.name_re);
175 else if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT)
176 free_tcpcheck_fmt(&rule->expect.hdr.name_fmt);
177 else
178 istfree(&rule->expect.hdr.name);
179
180 if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG)
181 regex_free(rule->expect.hdr.value_re);
182 else if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT)
183 free_tcpcheck_fmt(&rule->expect.hdr.value_fmt);
184 else if (!(rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE))
185 istfree(&rule->expect.hdr.value);
186 break;
187 case TCPCHK_EXPECT_CUSTOM:
188 case TCPCHK_EXPECT_UNDEF:
189 break;
190 }
191 break;
192 case TCPCHK_ACT_CONNECT:
193 free(rule->connect.sni);
194 free(rule->connect.alpn);
195 release_sample_expr(rule->connect.port_expr);
196 break;
197 case TCPCHK_ACT_COMMENT:
198 break;
199 case TCPCHK_ACT_ACTION_KW:
200 free(rule->action_kw.rule);
201 break;
202 }
203
204 if (in_pool)
205 pool_free(pool_head_tcpcheck_rule, rule);
206 else
207 free(rule);
208}
209
210/* Creates a tcp-check variable used in preset variables before executing a
211 * tcp-check ruleset.
212 */
213struct tcpcheck_var *create_tcpcheck_var(const struct ist name)
214{
215 struct tcpcheck_var *var = NULL;
216
217 var = calloc(1, sizeof(*var));
218 if (var == NULL)
219 return NULL;
220
221 var->name = istdup(name);
222 if (!isttest(var->name)) {
223 free(var);
224 return NULL;
225 }
226
227 LIST_INIT(&var->list);
228 return var;
229}
230
231/* Releases memory allocated for a preset tcp-check variable */
232void free_tcpcheck_var(struct tcpcheck_var *var)
233{
234 if (!var)
235 return;
236
237 istfree(&var->name);
238 if (var->data.type == SMP_T_STR || var->data.type == SMP_T_BIN)
239 free(var->data.u.str.area);
240 else if (var->data.type == SMP_T_METH && var->data.u.meth.meth == HTTP_METH_OTHER)
241 free(var->data.u.meth.str.area);
242 free(var);
243}
244
245/* Releases a list of preset tcp-check variables */
246void free_tcpcheck_vars(struct list *vars)
247{
248 struct tcpcheck_var *var, *back;
249
250 list_for_each_entry_safe(var, back, vars, list) {
251 LIST_DEL(&var->list);
252 free_tcpcheck_var(var);
253 }
254}
255
256/* Duplicate a list of preset tcp-check variables */
257int dup_tcpcheck_vars(struct list *dst, struct list *src)
258{
259 struct tcpcheck_var *var, *new = NULL;
260
261 list_for_each_entry(var, src, list) {
262 new = create_tcpcheck_var(var->name);
263 if (!new)
264 goto error;
265 new->data.type = var->data.type;
266 if (var->data.type == SMP_T_STR || var->data.type == SMP_T_BIN) {
267 if (chunk_dup(&new->data.u.str, &var->data.u.str) == NULL)
268 goto error;
269 if (var->data.type == SMP_T_STR)
270 new->data.u.str.area[new->data.u.str.data] = 0;
271 }
272 else if (var->data.type == SMP_T_METH && var->data.u.meth.meth == HTTP_METH_OTHER) {
273 if (chunk_dup(&new->data.u.str, &var->data.u.str) == NULL)
274 goto error;
275 new->data.u.str.area[new->data.u.str.data] = 0;
276 new->data.u.meth.meth = var->data.u.meth.meth;
277 }
278 else
279 new->data.u = var->data.u;
280 LIST_ADDQ(dst, &new->list);
281 }
282 return 1;
283
284 error:
285 free(new);
286 return 0;
287}
288
289/* Looks for a shared tcp-check ruleset given its name. */
290struct tcpcheck_ruleset *find_tcpcheck_ruleset(const char *name)
291{
292 struct tcpcheck_ruleset *rs;
293 struct ebpt_node *node;
294
295 node = ebis_lookup_len(&shared_tcpchecks, name, strlen(name));
296 if (node) {
297 rs = container_of(node, typeof(*rs), node);
298 return rs;
299 }
300 return NULL;
301}
302
303/* Creates a new shared tcp-check ruleset and insert it in shared_tcpchecks
304 * tree.
305 */
306struct tcpcheck_ruleset *create_tcpcheck_ruleset(const char *name)
307{
308 struct tcpcheck_ruleset *rs;
309
310 rs = calloc(1, sizeof(*rs));
311 if (rs == NULL)
312 return NULL;
313
314 rs->node.key = strdup(name);
315 if (rs->node.key == NULL) {
316 free(rs);
317 return NULL;
318 }
319
320 LIST_INIT(&rs->rules);
321 ebis_insert(&shared_tcpchecks, &rs->node);
322 return rs;
323}
324
325/* Releases memory allocated by a tcp-check ruleset. */
326void free_tcpcheck_ruleset(struct tcpcheck_ruleset *rs)
327{
328 struct tcpcheck_rule *r, *rb;
329
330 if (!rs)
331 return;
332
333 ebpt_delete(&rs->node);
334 free(rs->node.key);
335 list_for_each_entry_safe(r, rb, &rs->rules, list) {
336 LIST_DEL(&r->list);
337 free_tcpcheck(r, 0);
338 }
339 free(rs);
340}
341
342
343/**************************************************************************/
344/**************** Everything about tcp-checks execution *******************/
345/**************************************************************************/
346/* Returns the id of a step in a tcp-check ruleset */
347int tcpcheck_get_step_id(struct check *check, struct tcpcheck_rule *rule)
348{
349 if (!rule)
350 rule = check->current_step;
351
352 /* no last started step => first step */
353 if (!rule)
354 return 1;
355
356 /* last step is the first implicit connect */
357 if (rule->index == 0 &&
358 rule->action == TCPCHK_ACT_CONNECT &&
359 (rule->connect.options & TCPCHK_OPT_IMPLICIT))
360 return 0;
361
362 return rule->index + 1;
363}
364
365/* Returns the first non COMMENT/ACTION_KW tcp-check rule from list <list> or
366 * NULL if none was found.
367 */
368struct tcpcheck_rule *get_first_tcpcheck_rule(struct tcpcheck_rules *rules)
369{
370 struct tcpcheck_rule *r;
371
372 list_for_each_entry(r, rules->list, list) {
373 if (r->action != TCPCHK_ACT_COMMENT && r->action != TCPCHK_ACT_ACTION_KW)
374 return r;
375 }
376 return NULL;
377}
378
379/* Returns the last non COMMENT/ACTION_KW tcp-check rule from list <list> or
380 * NULL if none was found.
381 */
382static struct tcpcheck_rule *get_last_tcpcheck_rule(struct tcpcheck_rules *rules)
383{
384 struct tcpcheck_rule *r;
385
386 list_for_each_entry_rev(r, rules->list, list) {
387 if (r->action != TCPCHK_ACT_COMMENT && r->action != TCPCHK_ACT_ACTION_KW)
388 return r;
389 }
390 return NULL;
391}
392
393/* Returns the non COMMENT/ACTION_KW tcp-check rule from list <list> following
394 * <start> or NULL if non was found. If <start> is NULL, it relies on
395 * get_first_tcpcheck_rule().
396 */
397static struct tcpcheck_rule *get_next_tcpcheck_rule(struct tcpcheck_rules *rules, struct tcpcheck_rule *start)
398{
399 struct tcpcheck_rule *r;
400
401 if (!start)
402 return get_first_tcpcheck_rule(rules);
403
404 r = LIST_NEXT(&start->list, typeof(r), list);
405 list_for_each_entry_from(r, rules->list, list) {
406 if (r->action != TCPCHK_ACT_COMMENT && r->action != TCPCHK_ACT_ACTION_KW)
407 return r;
408 }
409 return NULL;
410}
411
412
413/* Creates info message when a tcp-check healthcheck fails on an expect rule */
414static void tcpcheck_expect_onerror_message(struct buffer *msg, struct check *check, struct tcpcheck_rule *rule,
415 int match, struct ist info)
416{
417 struct sample *smp;
418
419 /* Follows these step to produce the info message:
420 * 1. if info field is already provided, copy it
421 * 2. if the expect rule provides an onerror log-format string,
422 * use it to produce the message
423 * 3. the expect rule is part of a protocol check (http, redis, mysql...), do nothing
424 * 4. Otherwise produce the generic tcp-check info message
425 */
426 if (istlen(info)) {
427 chunk_strncat(msg, istptr(info), istlen(info));
428 goto comment;
429 }
430 else if (!LIST_ISEMPTY(&rule->expect.onerror_fmt)) {
431 msg->data += sess_build_logline(check->sess, NULL, b_tail(msg), b_room(msg), &rule->expect.onerror_fmt);
432 goto comment;
433 }
434
435 if (check->type == PR_O2_TCPCHK_CHK &&
436 (check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) != TCPCHK_RULES_TCP_CHK)
437 goto comment;
438
439 chunk_strcat(msg, (match ? "TCPCHK matched unwanted content" : "TCPCHK did not match content"));
440 switch (rule->expect.type) {
441 case TCPCHK_EXPECT_HTTP_STATUS:
442 chunk_appendf(msg, "(status codes) at step %d", tcpcheck_get_step_id(check, rule));
443 break;
444 case TCPCHK_EXPECT_STRING:
445 case TCPCHK_EXPECT_HTTP_BODY:
446 chunk_appendf(msg, " '%.*s' at step %d", (unsigned int)istlen(rule->expect.data), istptr(rule->expect.data),
447 tcpcheck_get_step_id(check, rule));
448 break;
449 case TCPCHK_EXPECT_BINARY:
450 chunk_appendf(msg, " (binary) at step %d", tcpcheck_get_step_id(check, rule));
451 break;
452 case TCPCHK_EXPECT_STRING_REGEX:
453 case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
454 case TCPCHK_EXPECT_HTTP_BODY_REGEX:
455 chunk_appendf(msg, " (regex) at step %d", tcpcheck_get_step_id(check, rule));
456 break;
457 case TCPCHK_EXPECT_BINARY_REGEX:
458 chunk_appendf(msg, " (binary regex) at step %d", tcpcheck_get_step_id(check, rule));
459 break;
460 case TCPCHK_EXPECT_STRING_LF:
461 case TCPCHK_EXPECT_HTTP_BODY_LF:
462 chunk_appendf(msg, " (log-format string) at step %d", tcpcheck_get_step_id(check, rule));
463 break;
464 case TCPCHK_EXPECT_BINARY_LF:
465 chunk_appendf(msg, " (log-format binary) at step %d", tcpcheck_get_step_id(check, rule));
466 break;
467 case TCPCHK_EXPECT_CUSTOM:
468 chunk_appendf(msg, " (custom function) at step %d", tcpcheck_get_step_id(check, rule));
469 break;
470 case TCPCHK_EXPECT_HTTP_HEADER:
471 chunk_appendf(msg, " (header pattern) at step %d", tcpcheck_get_step_id(check, rule));
472 case TCPCHK_EXPECT_UNDEF:
473 /* Should never happen. */
474 return;
475 }
476
477 comment:
478 /* If the failing expect rule provides a comment, it is concatenated to
479 * the info message.
480 */
481 if (rule->comment) {
482 chunk_strcat(msg, " comment: ");
483 chunk_strcat(msg, rule->comment);
484 }
485
486 /* Finally, the check status code is set if the failing expect rule
487 * defines a status expression.
488 */
489 if (rule->expect.status_expr) {
490 smp = sample_fetch_as_type(check->proxy, check->sess, NULL, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
491 rule->expect.status_expr, SMP_T_STR);
492
493 if (smp && sample_casts[smp->data.type][SMP_T_SINT] &&
494 sample_casts[smp->data.type][SMP_T_SINT](smp))
495 check->code = smp->data.u.sint;
496 }
497
498 *(b_tail(msg)) = '\0';
499}
500
501/* Creates info message when a tcp-check healthcheck succeeds on an expect rule */
502static void tcpcheck_expect_onsuccess_message(struct buffer *msg, struct check *check, struct tcpcheck_rule *rule,
503 struct ist info)
504{
505 struct sample *smp;
506
507 /* Follows these step to produce the info message:
508 * 1. if info field is already provided, copy it
509 * 2. if the expect rule provides an onsucces log-format string,
510 * use it to produce the message
511 * 3. the expect rule is part of a protocol check (http, redis, mysql...), do nothing
512 * 4. Otherwise produce the generic tcp-check info message
513 */
514 if (istlen(info))
515 chunk_strncat(msg, istptr(info), istlen(info));
516 if (!LIST_ISEMPTY(&rule->expect.onsuccess_fmt))
517 msg->data += sess_build_logline(check->sess, NULL, b_tail(msg), b_room(msg),
518 &rule->expect.onsuccess_fmt);
519 else if (check->type == PR_O2_TCPCHK_CHK &&
520 (check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_TCP_CHK)
521 chunk_strcat(msg, "(tcp-check)");
522
523 /* Finally, the check status code is set if the expect rule defines a
524 * status expression.
525 */
526 if (rule->expect.status_expr) {
527 smp = sample_fetch_as_type(check->proxy, check->sess, NULL, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
528 rule->expect.status_expr, SMP_T_STR);
529
530 if (smp && sample_casts[smp->data.type][SMP_T_SINT] &&
531 sample_casts[smp->data.type][SMP_T_SINT](smp))
532 check->code = smp->data.u.sint;
533 }
534
535 *(b_tail(msg)) = '\0';
536}
537
538/* Internal functions to parse and validate a MySQL packet in the context of an
539 * expect rule. It start to parse the input buffer at the offset <offset>. If
540 * <last_read> is set, no more data are expected.
541 */
542static enum tcpcheck_eval_ret tcpcheck_mysql_expect_packet(struct check *check, struct tcpcheck_rule *rule,
543 unsigned int offset, int last_read)
544{
545 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
546 enum healthcheck_status status;
547 struct buffer *msg = NULL;
548 struct ist desc = IST_NULL;
549 unsigned int err = 0, plen = 0;
550
551
552 /* 3 Bytes for the packet length and 1 byte for the sequence id */
553 if (b_data(&check->bi) < offset+4) {
554 if (!last_read)
555 goto wait_more_data;
556
557 /* invalid length or truncated response */
558 status = HCHK_STATUS_L7RSP;
559 goto error;
560 }
561
562 plen = ((unsigned char) *b_peek(&check->bi, offset)) +
563 (((unsigned char) *(b_peek(&check->bi, offset+1))) << 8) +
564 (((unsigned char) *(b_peek(&check->bi, offset+2))) << 16);
565
566 if (b_data(&check->bi) < offset+plen+4) {
567 if (!last_read)
568 goto wait_more_data;
569
570 /* invalid length or truncated response */
571 status = HCHK_STATUS_L7RSP;
572 goto error;
573 }
574
575 if (*b_peek(&check->bi, offset+4) == '\xff') {
576 /* MySQL Error packet always begin with field_count = 0xff */
577 status = HCHK_STATUS_L7STS;
578 err = ((unsigned char) *b_peek(&check->bi, offset+5)) +
579 (((unsigned char) *(b_peek(&check->bi, offset+6))) << 8);
580 desc = ist2(b_peek(&check->bi, offset+7), b_data(&check->bi) - offset - 7);
581 goto error;
582 }
583
584 if (get_next_tcpcheck_rule(check->tcpcheck_rules, rule) != NULL) {
585 /* Not the last rule, continue */
586 goto out;
587 }
588
589 /* We set the MySQL Version in description for information purpose
590 * FIXME : it can be cool to use MySQL Version for other purpose,
591 * like mark as down old MySQL server.
592 */
593 status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
594 set_server_check_status(check, status, b_peek(&check->bi, 5));
595
596 out:
597 free_trash_chunk(msg);
598 return ret;
599
600 error:
601 ret = TCPCHK_EVAL_STOP;
602 check->code = err;
603 msg = alloc_trash_chunk();
604 if (msg)
605 tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
606 set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
607 goto out;
608
609 wait_more_data:
610 ret = TCPCHK_EVAL_WAIT;
611 goto out;
612}
613
614/* Custom tcp-check expect function to parse and validate the MySQL initial
615 * handshake packet. Returns TCPCHK_EVAL_WAIT to wait for more data,
616 * TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if an
617 * error occurred.
618 */
619enum tcpcheck_eval_ret tcpcheck_mysql_expect_iniths(struct check *check, struct tcpcheck_rule *rule, int last_read)
620{
621 return tcpcheck_mysql_expect_packet(check, rule, 0, last_read);
622}
623
624/* Custom tcp-check expect function to parse and validate the MySQL OK packet
625 * following the initial handshake. Returns TCPCHK_EVAL_WAIT to wait for more
626 * data, TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if
627 * an error occurred.
628 */
629enum tcpcheck_eval_ret tcpcheck_mysql_expect_ok(struct check *check, struct tcpcheck_rule *rule, int last_read)
630{
631 unsigned int hslen = 0;
632
633 hslen = 4 + ((unsigned char) *b_head(&check->bi)) +
634 (((unsigned char) *(b_peek(&check->bi, 1))) << 8) +
635 (((unsigned char) *(b_peek(&check->bi, 2))) << 16);
636
637 return tcpcheck_mysql_expect_packet(check, rule, hslen, last_read);
638}
639
640/* Custom tcp-check expect function to parse and validate the LDAP bind response
641 * package packet. Returns TCPCHK_EVAL_WAIT to wait for more data,
642 * TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if an
643 * error occurred.
644 */
645enum tcpcheck_eval_ret tcpcheck_ldap_expect_bindrsp(struct check *check, struct tcpcheck_rule *rule, int last_read)
646{
647 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
648 enum healthcheck_status status;
649 struct buffer *msg = NULL;
650 struct ist desc = IST_NULL;
651 unsigned short msglen = 0;
652
653 /* Check if the server speaks LDAP (ASN.1/BER)
654 * http://en.wikipedia.org/wiki/Basic_Encoding_Rules
655 * http://tools.ietf.org/html/rfc4511
656 */
657 /* size of LDAPMessage */
658 msglen = (*(b_head(&check->bi) + 1) & 0x80) ? (*(b_head(&check->bi) + 1) & 0x7f) : 0;
659
660 /* http://tools.ietf.org/html/rfc4511#section-4.2.2
661 * messageID: 0x02 0x01 0x01: INTEGER 1
662 * protocolOp: 0x61: bindResponse
663 */
664 if ((msglen > 2) || (memcmp(b_head(&check->bi) + 2 + msglen, "\x02\x01\x01\x61", 4) != 0)) {
665 status = HCHK_STATUS_L7RSP;
666 desc = ist("Not LDAPv3 protocol");
667 goto error;
668 }
669
670 /* size of bindResponse */
671 msglen += (*(b_head(&check->bi) + msglen + 6) & 0x80) ? (*(b_head(&check->bi) + msglen + 6) & 0x7f) : 0;
672
673 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
674 * ldapResult: 0x0a 0x01: ENUMERATION
675 */
676 if ((msglen > 4) || (memcmp(b_head(&check->bi) + 7 + msglen, "\x0a\x01", 2) != 0)) {
677 status = HCHK_STATUS_L7RSP;
678 desc = ist("Not LDAPv3 protocol");
679 goto error;
680 }
681
682 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
683 * resultCode
684 */
685 check->code = *(b_head(&check->bi) + msglen + 9);
686 if (check->code) {
687 status = HCHK_STATUS_L7STS;
688 desc = ist("See RFC: http://tools.ietf.org/html/rfc4511#section-4.1.9");
689 goto error;
690 }
691
692 status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
693 set_server_check_status(check, status, "Success");
694
695 out:
696 free_trash_chunk(msg);
697 return ret;
698
699 error:
700 ret = TCPCHK_EVAL_STOP;
701 msg = alloc_trash_chunk();
702 if (msg)
703 tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
704 set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
705 goto out;
706}
707
708/* Custom tcp-check expect function to parse and validate the SPOP hello agent
709 * frame. Returns TCPCHK_EVAL_WAIT to wait for more data, TCPCHK_EVAL_CONTINUE
710 * to evaluate the next rule or TCPCHK_EVAL_STOP if an error occurred.
711 */
712enum tcpcheck_eval_ret tcpcheck_spop_expect_agenthello(struct check *check, struct tcpcheck_rule *rule, int last_read)
713{
714 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
715 enum healthcheck_status status;
716 struct buffer *msg = NULL;
717 struct ist desc = IST_NULL;
718 unsigned int framesz;
719
720
721 memcpy(&framesz, b_head(&check->bi), 4);
722 framesz = ntohl(framesz);
723
724 if (!last_read && b_data(&check->bi) < (4+framesz))
725 goto wait_more_data;
726
727 memset(b_orig(&trash), 0, b_size(&trash));
728 if (spoe_handle_healthcheck_response(b_peek(&check->bi, 4), framesz, b_orig(&trash), HCHK_DESC_LEN) == -1) {
729 status = HCHK_STATUS_L7RSP;
730 desc = ist2(b_orig(&trash), strlen(b_orig(&trash)));
731 goto error;
732 }
733
734 status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
735 set_server_check_status(check, status, "SPOA server is ok");
736
737 out:
738 free_trash_chunk(msg);
739 return ret;
740
741 error:
742 ret = TCPCHK_EVAL_STOP;
743 msg = alloc_trash_chunk();
744 if (msg)
745 tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
746 set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
747 goto out;
748
749 wait_more_data:
750 ret = TCPCHK_EVAL_WAIT;
751 goto out;
752}
753
754/* Custom tcp-check expect function to parse and validate the agent-check
755 * reply. Returns TCPCHK_EVAL_WAIT to wait for more data, TCPCHK_EVAL_CONTINUE
756 * to evaluate the next rule or TCPCHK_EVAL_STOP if an error occurred.
757 */
758enum tcpcheck_eval_ret tcpcheck_agent_expect_reply(struct check *check, struct tcpcheck_rule *rule, int last_read)
759{
760 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_STOP;
761 enum healthcheck_status status = HCHK_STATUS_CHECKED;
762 const char *hs = NULL; /* health status */
763 const char *as = NULL; /* admin status */
764 const char *ps = NULL; /* performance status */
765 const char *cs = NULL; /* maxconn */
766 const char *err = NULL; /* first error to report */
767 const char *wrn = NULL; /* first warning to report */
768 char *cmd, *p;
769
770 /* We're getting an agent check response. The agent could
771 * have been disabled in the mean time with a long check
772 * still pending. It is important that we ignore the whole
773 * response.
774 */
775 if (!(check->state & CHK_ST_ENABLED))
776 goto out;
777
778 /* The agent supports strings made of a single line ended by the
779 * first CR ('\r') or LF ('\n'). This line is composed of words
780 * delimited by spaces (' '), tabs ('\t'), or commas (','). The
781 * line may optionally contained a description of a state change
782 * after a sharp ('#'), which is only considered if a health state
783 * is announced.
784 *
785 * Words may be composed of :
786 * - a numeric weight suffixed by the percent character ('%').
787 * - a health status among "up", "down", "stopped", and "fail".
788 * - an admin status among "ready", "drain", "maint".
789 *
790 * These words may appear in any order. If multiple words of the
791 * same category appear, the last one wins.
792 */
793
794 p = b_head(&check->bi);
795 while (*p && *p != '\n' && *p != '\r')
796 p++;
797
798 if (!*p) {
799 if (!last_read)
800 goto wait_more_data;
801
802 /* at least inform the admin that the agent is mis-behaving */
803 set_server_check_status(check, check->status, "Ignoring incomplete line from agent");
804 goto out;
805 }
806
807 *p = 0;
808 cmd = b_head(&check->bi);
809
810 while (*cmd) {
811 /* look for next word */
812 if (*cmd == ' ' || *cmd == '\t' || *cmd == ',') {
813 cmd++;
814 continue;
815 }
816
817 if (*cmd == '#') {
818 /* this is the beginning of a health status description,
819 * skip the sharp and blanks.
820 */
821 cmd++;
822 while (*cmd == '\t' || *cmd == ' ')
823 cmd++;
824 break;
825 }
826
827 /* find the end of the word so that we have a null-terminated
828 * word between <cmd> and <p>.
829 */
830 p = cmd + 1;
831 while (*p && *p != '\t' && *p != ' ' && *p != '\n' && *p != ',')
832 p++;
833 if (*p)
834 *p++ = 0;
835
836 /* first, health statuses */
837 if (strcasecmp(cmd, "up") == 0) {
838 check->server->check.health = check->server->check.rise + check->server->check.fall - 1;
839 status = HCHK_STATUS_L7OKD;
840 hs = cmd;
841 }
842 else if (strcasecmp(cmd, "down") == 0) {
843 check->server->check.health = 0;
844 status = HCHK_STATUS_L7STS;
845 hs = cmd;
846 }
847 else if (strcasecmp(cmd, "stopped") == 0) {
848 check->server->check.health = 0;
849 status = HCHK_STATUS_L7STS;
850 hs = cmd;
851 }
852 else if (strcasecmp(cmd, "fail") == 0) {
853 check->server->check.health = 0;
854 status = HCHK_STATUS_L7STS;
855 hs = cmd;
856 }
857 /* admin statuses */
858 else if (strcasecmp(cmd, "ready") == 0) {
859 as = cmd;
860 }
861 else if (strcasecmp(cmd, "drain") == 0) {
862 as = cmd;
863 }
864 else if (strcasecmp(cmd, "maint") == 0) {
865 as = cmd;
866 }
867 /* try to parse a weight here and keep the last one */
868 else if (isdigit((unsigned char)*cmd) && strchr(cmd, '%') != NULL) {
869 ps = cmd;
870 }
871 /* try to parse a maxconn here */
872 else if (strncasecmp(cmd, "maxconn:", strlen("maxconn:")) == 0) {
873 cs = cmd;
874 }
875 else {
876 /* keep a copy of the first error */
877 if (!err)
878 err = cmd;
879 }
880 /* skip to next word */
881 cmd = p;
882 }
883 /* here, cmd points either to \0 or to the beginning of a
884 * description. Skip possible leading spaces.
885 */
886 while (*cmd == ' ' || *cmd == '\n')
887 cmd++;
888
889 /* First, update the admin status so that we avoid sending other
890 * possibly useless warnings and can also update the health if
891 * present after going back up.
892 */
893 if (as) {
894 if (strcasecmp(as, "drain") == 0)
895 srv_adm_set_drain(check->server);
896 else if (strcasecmp(as, "maint") == 0)
897 srv_adm_set_maint(check->server);
898 else
899 srv_adm_set_ready(check->server);
900 }
901
902 /* now change weights */
903 if (ps) {
904 const char *msg;
905
906 msg = server_parse_weight_change_request(check->server, ps);
907 if (!wrn || !*wrn)
908 wrn = msg;
909 }
910
911 if (cs) {
912 const char *msg;
913
914 cs += strlen("maxconn:");
915
916 msg = server_parse_maxconn_change_request(check->server, cs);
917 if (!wrn || !*wrn)
918 wrn = msg;
919 }
920
921 /* and finally health status */
922 if (hs) {
923 /* We'll report some of the warnings and errors we have
924 * here. Down reports are critical, we leave them untouched.
925 * Lack of report, or report of 'UP' leaves the room for
926 * ERR first, then WARN.
927 */
928 const char *msg = cmd;
929 struct buffer *t;
930
931 if (!*msg || status == HCHK_STATUS_L7OKD) {
932 if (err && *err)
933 msg = err;
934 else if (wrn && *wrn)
935 msg = wrn;
936 }
937
938 t = get_trash_chunk();
939 chunk_printf(t, "via agent : %s%s%s%s",
940 hs, *msg ? " (" : "",
941 msg, *msg ? ")" : "");
942 set_server_check_status(check, status, t->area);
943 }
944 else if (err && *err) {
945 /* No status change but we'd like to report something odd.
946 * Just report the current state and copy the message.
947 */
948 chunk_printf(&trash, "agent reports an error : %s", err);
949 set_server_check_status(check, status/*check->status*/, trash.area);
950 }
951 else if (wrn && *wrn) {
952 /* No status change but we'd like to report something odd.
953 * Just report the current state and copy the message.
954 */
955 chunk_printf(&trash, "agent warns : %s", wrn);
956 set_server_check_status(check, status/*check->status*/, trash.area);
957 }
958 else
959 set_server_check_status(check, status, NULL);
960
961 out:
962 return ret;
963
964 wait_more_data:
965 ret = TCPCHK_EVAL_WAIT;
966 goto out;
967}
968
969/* Evaluates a TCPCHK_ACT_CONNECT rule. Returns TCPCHK_EVAL_WAIT to wait the
970 * connection establishment, TCPCHK_EVAL_CONTINUE to evaluate the next rule or
971 * TCPCHK_EVAL_STOP if an error occurred.
972 */
973enum tcpcheck_eval_ret tcpcheck_eval_connect(struct check *check, struct tcpcheck_rule *rule)
974{
975 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
976 struct tcpcheck_connect *connect = &rule->connect;
977 struct proxy *proxy = check->proxy;
978 struct server *s = check->server;
979 struct task *t = check->task;
980 struct conn_stream *cs;
981 struct connection *conn = NULL;
982 struct protocol *proto;
983 struct xprt_ops *xprt;
984 struct tcpcheck_rule *next;
985 int status, port;
986
987 /* For a connect action we'll create a new connection. We may also have
988 * to kill a previous one. But we don't want to leave *without* a
989 * connection if we came here from the connection layer, hence with a
990 * connection. Thus we'll proceed in the following order :
991 * 1: close but not release previous connection (handled by the caller)
992 * 2: try to get a new connection
993 * 3: release and replace the old one on success
994 */
995
996 /* 2- prepare new connection */
Christopher Faulet236c93b2020-07-02 09:19:54 +0200997 cs = cs_new(NULL, (s ? &s->obj_type : &proxy->obj_type));
Willy Tarreau51cd5952020-06-05 12:25:38 +0200998 if (!cs) {
999 chunk_printf(&trash, "TCPCHK error allocating connection at step %d",
1000 tcpcheck_get_step_id(check, rule));
1001 if (rule->comment)
1002 chunk_appendf(&trash, " comment: '%s'", rule->comment);
1003 set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.area);
1004 ret = TCPCHK_EVAL_STOP;
1005 goto out;
1006 }
1007
1008 /* 3- release and replace the old one on success */
1009 if (check->cs) {
1010 if (check->wait_list.events)
1011 check->cs->conn->mux->unsubscribe(check->cs, check->wait_list.events,
1012 &check->wait_list);
1013
1014 /* We may have been scheduled to run, and the I/O handler
1015 * expects to have a cs, so remove the tasklet
1016 */
1017 tasklet_remove_from_tasklet_list(check->wait_list.tasklet);
1018 cs_destroy(check->cs);
1019 }
1020
1021 tasklet_set_tid(check->wait_list.tasklet, tid);
1022
1023 check->cs = cs;
1024 conn = cs->conn;
1025 conn_set_owner(conn, check->sess, NULL);
1026
1027 /* Maybe there were an older connection we were waiting on */
1028 check->wait_list.events = 0;
Willy Tarreau51cd5952020-06-05 12:25:38 +02001029
1030 /* no client address */
1031 if (!sockaddr_alloc(&conn->dst)) {
1032 status = SF_ERR_RESOURCE;
1033 goto fail_check;
1034 }
1035
1036 /* connect to the connect rule addr if specified, otherwise the check
1037 * addr if specified on the server. otherwise, use the server addr (it
1038 * MUST exist at this step).
1039 */
1040 *conn->dst = (is_addr(&connect->addr)
1041 ? connect->addr
1042 : (is_addr(&check->addr) ? check->addr : s->addr));
1043 proto = protocol_by_family(conn->dst->ss_family);
1044
1045 port = 0;
1046 if (!port && connect->port)
1047 port = connect->port;
1048 if (!port && connect->port_expr) {
1049 struct sample *smp;
1050
1051 smp = sample_fetch_as_type(check->proxy, check->sess, NULL,
1052 SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
1053 connect->port_expr, SMP_T_SINT);
1054 if (smp)
1055 port = smp->data.u.sint;
1056 }
1057 if (!port && is_inet_addr(&connect->addr))
1058 port = get_host_port(&connect->addr);
1059 if (!port && check->port)
1060 port = check->port;
1061 if (!port && is_inet_addr(&check->addr))
1062 port = get_host_port(&check->addr);
1063 if (!port) {
1064 /* The server MUST exist here */
1065 port = s->svc_port;
1066 }
1067 set_host_port(conn->dst, port);
1068
1069 xprt = ((connect->options & TCPCHK_OPT_SSL)
1070 ? xprt_get(XPRT_SSL)
1071 : ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) ? check->xprt : xprt_get(XPRT_RAW)));
1072
1073 conn_prepare(conn, proto, xprt);
1074 cs_attach(cs, check, &check_conn_cb);
1075
1076 status = SF_ERR_INTERNAL;
1077 next = get_next_tcpcheck_rule(check->tcpcheck_rules, rule);
1078 if (proto && proto->connect) {
1079 int flags = 0;
1080
1081 if (check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK)
1082 flags |= CONNECT_HAS_DATA;
1083 if (!next || next->action != TCPCHK_ACT_EXPECT)
1084 flags |= CONNECT_DELACK_ALWAYS;
1085 status = proto->connect(conn, flags);
1086 }
1087
1088 if (status != SF_ERR_NONE)
1089 goto fail_check;
1090
Christopher Faulet21ddc742020-07-01 15:26:14 +02001091 conn_set_private(conn);
Willy Tarreau51cd5952020-06-05 12:25:38 +02001092 conn->ctx = cs;
1093
Willy Tarreau51cd5952020-06-05 12:25:38 +02001094#ifdef USE_OPENSSL
1095 if (connect->sni)
1096 ssl_sock_set_servername(conn, connect->sni);
1097 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.sni)
1098 ssl_sock_set_servername(conn, s->check.sni);
1099
1100 if (connect->alpn)
1101 ssl_sock_set_alpn(conn, (unsigned char *)connect->alpn, connect->alpn_len);
1102 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.alpn_str)
1103 ssl_sock_set_alpn(conn, (unsigned char *)s->check.alpn_str, s->check.alpn_len);
1104#endif
1105 if ((connect->options & TCPCHK_OPT_SOCKS4) && s && (s->flags & SRV_F_SOCKS4_PROXY)) {
1106 conn->send_proxy_ofs = 1;
1107 conn->flags |= CO_FL_SOCKS4;
1108 }
1109 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.via_socks4 && (s->flags & SRV_F_SOCKS4_PROXY)) {
1110 conn->send_proxy_ofs = 1;
1111 conn->flags |= CO_FL_SOCKS4;
1112 }
1113
1114 if (connect->options & TCPCHK_OPT_SEND_PROXY) {
1115 conn->send_proxy_ofs = 1;
1116 conn->flags |= CO_FL_SEND_PROXY;
1117 }
1118 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.send_proxy && !(check->state & CHK_ST_AGENT)) {
1119 conn->send_proxy_ofs = 1;
1120 conn->flags |= CO_FL_SEND_PROXY;
1121 }
1122
1123 if (conn_ctrl_ready(conn) && (connect->options & TCPCHK_OPT_LINGER)) {
1124 /* Some servers don't like reset on close */
1125 fdtab[cs->conn->handle.fd].linger_risk = 0;
1126 }
1127
1128 if (conn_ctrl_ready(conn) && (conn->flags & (CO_FL_SEND_PROXY | CO_FL_SOCKS4))) {
1129 if (xprt_add_hs(conn) < 0)
1130 status = SF_ERR_RESOURCE;
1131 }
1132
Willy Tarreau8e979fa2020-07-31 08:49:31 +02001133 /* The mux may be initialized now if there isn't server attached to the
1134 * check (email alerts) or if there is a mux proto specified or if there
1135 * is no alpn.
1136 */
1137 if (!s || ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && check->mux_proto) ||
1138 connect->mux_proto || (!connect->alpn && !check->alpn_str)) {
1139 const struct mux_ops *mux_ops;
1140
1141 if (connect->mux_proto)
1142 mux_ops = connect->mux_proto->mux;
1143 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && check->mux_proto)
1144 mux_ops = check->mux_proto->mux;
1145 else {
1146 int mode = ((check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK
1147 ? PROTO_MODE_HTTP
1148 : PROTO_MODE_TCP);
1149
1150 mux_ops = conn_get_best_mux(conn, IST_NULL, PROTO_SIDE_BE, mode);
1151 }
1152 if (mux_ops && conn_install_mux(conn, mux_ops, cs, proxy, check->sess) < 0) {
1153 status = SF_ERR_INTERNAL;
1154 goto fail_check;
1155 }
1156 }
1157
Willy Tarreau51cd5952020-06-05 12:25:38 +02001158 fail_check:
1159 /* It can return one of :
1160 * - SF_ERR_NONE if everything's OK
1161 * - SF_ERR_SRVTO if there are no more servers
1162 * - SF_ERR_SRVCL if the connection was refused by the server
1163 * - SF_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1164 * - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1165 * - SF_ERR_INTERNAL for any other purely internal errors
1166 * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
1167 * Note that we try to prevent the network stack from sending the ACK during the
1168 * connect() when a pure TCP check is used (without PROXY protocol).
1169 */
1170 switch (status) {
1171 case SF_ERR_NONE:
1172 /* we allow up to min(inter, timeout.connect) for a connection
1173 * to establish but only when timeout.check is set as it may be
1174 * to short for a full check otherwise
1175 */
1176 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1177
1178 if (proxy->timeout.check && proxy->timeout.connect) {
1179 int t_con = tick_add(now_ms, proxy->timeout.connect);
1180 t->expire = tick_first(t->expire, t_con);
1181 }
1182 break;
1183 case SF_ERR_SRVTO: /* ETIMEDOUT */
1184 case SF_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
1185 case SF_ERR_PRXCOND:
1186 case SF_ERR_RESOURCE:
1187 case SF_ERR_INTERNAL:
1188 chk_report_conn_err(check, errno, 0);
1189 ret = TCPCHK_EVAL_STOP;
1190 goto out;
1191 }
1192
1193 /* don't do anything until the connection is established */
1194 if (conn->flags & CO_FL_WAIT_XPRT) {
1195 if (conn->mux) {
1196 if (next && next->action == TCPCHK_ACT_SEND)
1197 conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
1198 else
1199 conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
1200 }
1201 ret = TCPCHK_EVAL_WAIT;
1202 goto out;
1203 }
1204
1205 out:
1206 if (conn && check->result == CHK_RES_FAILED)
1207 conn->flags |= CO_FL_ERROR;
1208 return ret;
1209}
1210
1211/* Evaluates a TCPCHK_ACT_SEND rule. Returns TCPCHK_EVAL_WAIT if outgoing data
1212 * were not fully sent, TCPCHK_EVAL_CONTINUE to evaluate the next rule or
1213 * TCPCHK_EVAL_STOP if an error occurred.
1214 */
1215enum tcpcheck_eval_ret tcpcheck_eval_send(struct check *check, struct tcpcheck_rule *rule)
1216{
1217 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1218 struct tcpcheck_send *send = &rule->send;
1219 struct conn_stream *cs = check->cs;
1220 struct connection *conn = cs_conn(cs);
1221 struct buffer *tmp = NULL;
1222 struct htx *htx = NULL;
1223
1224 /* reset the read & write buffer */
1225 b_reset(&check->bi);
1226 b_reset(&check->bo);
1227
1228 switch (send->type) {
1229 case TCPCHK_SEND_STRING:
1230 case TCPCHK_SEND_BINARY:
1231 if (istlen(send->data) >= b_size(&check->bo)) {
1232 chunk_printf(&trash, "tcp-check send : string too large (%u) for buffer size (%u) at step %d",
1233 (unsigned int)istlen(send->data), (unsigned int)b_size(&check->bo),
1234 tcpcheck_get_step_id(check, rule));
1235 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1236 ret = TCPCHK_EVAL_STOP;
1237 goto out;
1238 }
1239 b_putist(&check->bo, send->data);
1240 break;
1241 case TCPCHK_SEND_STRING_LF:
1242 check->bo.data = sess_build_logline(check->sess, NULL, b_orig(&check->bo), b_size(&check->bo), &rule->send.fmt);
1243 if (!b_data(&check->bo))
1244 goto out;
1245 break;
1246 case TCPCHK_SEND_BINARY_LF: {
1247 int len = b_size(&check->bo);
1248
1249 tmp = alloc_trash_chunk();
1250 if (!tmp)
1251 goto error_lf;
1252 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &rule->send.fmt);
1253 if (!b_data(tmp))
1254 goto out;
1255 tmp->area[tmp->data] = '\0';
1256 if (parse_binary(b_orig(tmp), &check->bo.area, &len, NULL) == 0)
1257 goto error_lf;
1258 check->bo.data = len;
1259 break;
1260 }
1261 case TCPCHK_SEND_HTTP: {
1262 struct htx_sl *sl;
1263 struct ist meth, uri, vsn, clen, body;
1264 unsigned int slflags = 0;
1265
1266 tmp = alloc_trash_chunk();
1267 if (!tmp)
1268 goto error_htx;
1269
1270 meth = ((send->http.meth.meth == HTTP_METH_OTHER)
1271 ? ist2(send->http.meth.str.area, send->http.meth.str.data)
1272 : http_known_methods[send->http.meth.meth]);
1273 if (send->http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) {
1274 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &send->http.uri_fmt);
1275 uri = (b_data(tmp) ? ist2(b_orig(tmp), b_data(tmp)) : ist("/"));
1276 }
1277 else
1278 uri = (isttest(send->http.uri) ? send->http.uri : ist("/"));
1279 vsn = (isttest(send->http.vsn) ? send->http.vsn : ist("HTTP/1.0"));
1280
1281 if ((istlen(vsn) == 6 && *(vsn.ptr+5) == '2') ||
1282 (istlen(vsn) == 8 && (*(vsn.ptr+5) > '1' || (*(vsn.ptr+5) == '1' && *(vsn.ptr+7) >= '1'))))
1283 slflags |= HTX_SL_F_VER_11;
1284 slflags |= (HTX_SL_F_XFER_LEN|HTX_SL_F_CLEN);
1285 if (!isttest(send->http.body))
1286 slflags |= HTX_SL_F_BODYLESS;
1287
1288 htx = htx_from_buf(&check->bo);
1289 sl = htx_add_stline(htx, HTX_BLK_REQ_SL, slflags, meth, uri, vsn);
1290 if (!sl)
1291 goto error_htx;
1292 sl->info.req.meth = send->http.meth.meth;
1293 if (!http_update_host(htx, sl, uri))
1294 goto error_htx;
1295
1296 if (!LIST_ISEMPTY(&send->http.hdrs)) {
1297 struct tcpcheck_http_hdr *hdr;
1298 struct ist hdr_value;
1299
1300 list_for_each_entry(hdr, &send->http.hdrs, list) {
1301 chunk_reset(tmp);
1302 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &hdr->value);
1303 if (!b_data(tmp))
1304 continue;
1305 hdr_value = ist2(b_orig(tmp), b_data(tmp));
1306 if (!htx_add_header(htx, hdr->name, hdr_value))
1307 goto error_htx;
1308 if ((sl->flags & HTX_SL_F_HAS_AUTHORITY) && isteqi(hdr->name, ist("host"))) {
1309 if (!http_update_authority(htx, sl, hdr_value))
1310 goto error_htx;
1311 }
1312 }
1313
1314 }
1315 if (check->proxy->options2 & PR_O2_CHK_SNDST) {
1316 chunk_reset(tmp);
1317 httpchk_build_status_header(check->server, tmp);
1318 if (!htx_add_header(htx, ist("X-Haproxy-Server-State"), ist2(b_orig(tmp), b_data(tmp))))
1319 goto error_htx;
1320 }
1321
1322
1323 if (send->http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) {
1324 chunk_reset(tmp);
1325 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &send->http.body_fmt);
1326 body = ist2(b_orig(tmp), b_data(tmp));
1327 }
1328 else
1329 body = send->http.body;
1330 clen = ist((!istlen(body) ? "0" : ultoa(istlen(body))));
1331
1332 if (!htx_add_header(htx, ist("Connection"), ist("close")) ||
1333 !htx_add_header(htx, ist("Content-length"), clen))
1334 goto error_htx;
1335
1336
1337 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Faulet810df062020-07-22 16:20:34 +02001338 (istlen(body) && !htx_add_data_atonce(htx, body)))
1339 goto error_htx;
1340
1341 htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
1342 if (!htx_add_endof(htx, HTX_BLK_EOM))
Willy Tarreau51cd5952020-06-05 12:25:38 +02001343 goto error_htx;
1344
1345 htx_to_buf(htx, &check->bo);
1346 break;
1347 }
1348 case TCPCHK_SEND_UNDEF:
1349 /* Should never happen. */
1350 ret = TCPCHK_EVAL_STOP;
1351 goto out;
1352 };
1353
1354
1355 if (conn->mux->snd_buf(cs, &check->bo,
1356 (IS_HTX_CONN(conn) ? (htxbuf(&check->bo))->data: b_data(&check->bo)), 0) <= 0) {
1357 if ((conn->flags & CO_FL_ERROR) || (cs->flags & CS_FL_ERROR)) {
1358 ret = TCPCHK_EVAL_STOP;
1359 goto out;
1360 }
1361 }
1362 if ((IS_HTX_CONN(conn) && !htx_is_empty(htxbuf(&check->bo))) || b_data(&check->bo)) {
1363 cs->conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
1364 ret = TCPCHK_EVAL_WAIT;
1365 goto out;
1366 }
1367
1368 out:
1369 free_trash_chunk(tmp);
1370 return ret;
1371
1372 error_htx:
1373 if (htx) {
1374 htx_reset(htx);
1375 htx_to_buf(htx, &check->bo);
1376 }
1377 chunk_printf(&trash, "tcp-check send : failed to build HTTP request at step %d",
1378 tcpcheck_get_step_id(check, rule));
1379 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1380 ret = TCPCHK_EVAL_STOP;
1381 goto out;
1382
1383 error_lf:
1384 chunk_printf(&trash, "tcp-check send : failed to build log-format string at step %d",
1385 tcpcheck_get_step_id(check, rule));
1386 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1387 ret = TCPCHK_EVAL_STOP;
1388 goto out;
1389
1390}
1391
1392/* Try to receive data before evaluating a tcp-check expect rule. Returns
1393 * TCPCHK_EVAL_WAIT if it is already subscribed on receive events or if nothing
1394 * was received, TCPCHK_EVAL_CONTINUE to evaluate the expect rule or
1395 * TCPCHK_EVAL_STOP if an error occurred.
1396 */
1397enum tcpcheck_eval_ret tcpcheck_eval_recv(struct check *check, struct tcpcheck_rule *rule)
1398{
1399 struct conn_stream *cs = check->cs;
1400 struct connection *conn = cs_conn(cs);
1401 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1402 size_t max, read, cur_read = 0;
1403 int is_empty;
1404 int read_poll = MAX_READ_POLL_LOOPS;
1405
1406 if (check->wait_list.events & SUB_RETRY_RECV)
1407 goto wait_more_data;
1408
1409 if (cs->flags & CS_FL_EOS)
1410 goto end_recv;
1411
1412 /* errors on the connection and the conn-stream were already checked */
1413
1414 /* prepare to detect if the mux needs more room */
1415 cs->flags &= ~CS_FL_WANT_ROOM;
1416
1417 while ((cs->flags & CS_FL_RCV_MORE) ||
1418 (!(conn->flags & CO_FL_ERROR) && !(cs->flags & (CS_FL_ERROR|CS_FL_EOS)))) {
1419 max = (IS_HTX_CS(cs) ? htx_free_space(htxbuf(&check->bi)) : b_room(&check->bi));
1420 read = conn->mux->rcv_buf(cs, &check->bi, max, 0);
1421 cur_read += read;
1422 if (!read ||
1423 (cs->flags & CS_FL_WANT_ROOM) ||
1424 (--read_poll <= 0) ||
1425 (read < max && read >= global.tune.recv_enough))
1426 break;
1427 }
1428
1429 end_recv:
1430 is_empty = (IS_HTX_CS(cs) ? htx_is_empty(htxbuf(&check->bi)) : !b_data(&check->bi));
1431 if (is_empty && ((conn->flags & CO_FL_ERROR) || (cs->flags & CS_FL_ERROR))) {
1432 /* Report network errors only if we got no other data. Otherwise
1433 * we'll let the upper layers decide whether the response is OK
1434 * or not. It is very common that an RST sent by the server is
1435 * reported as an error just after the last data chunk.
1436 */
1437 goto stop;
1438 }
1439 if (!cur_read) {
1440 if (!(cs->flags & (CS_FL_WANT_ROOM|CS_FL_ERROR|CS_FL_EOS))) {
1441 conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
1442 goto wait_more_data;
1443 }
1444 if (is_empty) {
1445 int status;
1446
1447 chunk_printf(&trash, "TCPCHK got an empty response at step %d",
1448 tcpcheck_get_step_id(check, rule));
1449 if (rule->comment)
1450 chunk_appendf(&trash, " comment: '%s'", rule->comment);
1451
1452 status = ((rule->expect.err_status != HCHK_STATUS_UNKNOWN) ? rule->expect.err_status : HCHK_STATUS_L7RSP);
1453 set_server_check_status(check, status, trash.area);
1454 goto stop;
1455 }
1456 }
1457
1458 out:
1459 return ret;
1460
1461 stop:
1462 ret = TCPCHK_EVAL_STOP;
1463 goto out;
1464
1465 wait_more_data:
1466 ret = TCPCHK_EVAL_WAIT;
1467 goto out;
1468}
1469
1470/* Evaluates an HTTP TCPCHK_ACT_EXPECT rule. If <last_read> is set , no more data
1471 * are expected. Returns TCPCHK_EVAL_WAIT to wait for more data,
1472 * TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if an
1473 * error occurred.
1474 */
1475enum tcpcheck_eval_ret tcpcheck_eval_expect_http(struct check *check, struct tcpcheck_rule *rule, int last_read)
1476{
1477 struct htx *htx = htxbuf(&check->bi);
1478 struct htx_sl *sl;
1479 struct htx_blk *blk;
1480 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1481 struct tcpcheck_expect *expect = &rule->expect;
1482 struct buffer *msg = NULL, *tmp = NULL, *nbuf = NULL, *vbuf = NULL;
1483 enum healthcheck_status status = HCHK_STATUS_L7RSP;
1484 struct ist desc = IST_NULL;
1485 int i, match, inverse;
1486
1487 last_read |= (!htx_free_space(htx) || (htx_get_tail_type(htx) == HTX_BLK_EOM));
1488
1489 if (htx->flags & HTX_FL_PARSING_ERROR) {
1490 status = HCHK_STATUS_L7RSP;
1491 goto error;
1492 }
1493
1494 if (htx_is_empty(htx)) {
1495 if (last_read) {
1496 status = HCHK_STATUS_L7RSP;
1497 goto error;
1498 }
1499 goto wait_more_data;
1500 }
1501
1502 sl = http_get_stline(htx);
1503 check->code = sl->info.res.status;
1504
1505 if (check->server &&
1506 (check->server->proxy->options & PR_O_DISABLE404) &&
1507 (check->server->next_state != SRV_ST_STOPPED) &&
1508 (check->code == 404)) {
1509 /* 404 may be accepted as "stopping" only if the server was up */
1510 goto out;
1511 }
1512
1513 inverse = !!(expect->flags & TCPCHK_EXPT_FL_INV);
1514 /* Make GCC happy ; initialize match to a failure state. */
1515 match = inverse;
1516 status = expect->err_status;
1517
1518 switch (expect->type) {
1519 case TCPCHK_EXPECT_HTTP_STATUS:
1520 match = 0;
1521 for (i = 0; i < expect->codes.num; i++) {
1522 if (sl->info.res.status >= expect->codes.codes[i][0] &&
1523 sl->info.res.status <= expect->codes.codes[i][1]) {
1524 match = 1;
1525 break;
1526 }
1527 }
1528
1529 /* Set status and description in case of error */
1530 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
1531 if (LIST_ISEMPTY(&expect->onerror_fmt))
1532 desc = htx_sl_res_reason(sl);
1533 break;
1534 case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
1535 match = regex_exec2(expect->regex, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
1536
1537 /* Set status and description in case of error */
1538 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
1539 if (LIST_ISEMPTY(&expect->onerror_fmt))
1540 desc = htx_sl_res_reason(sl);
1541 break;
1542
1543 case TCPCHK_EXPECT_HTTP_HEADER: {
1544 struct http_hdr_ctx ctx;
1545 struct ist npat, vpat, value;
1546 int full = (expect->flags & (TCPCHK_EXPT_FL_HTTP_HVAL_NONE|TCPCHK_EXPT_FL_HTTP_HVAL_FULL));
1547
1548 if (expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
1549 nbuf = alloc_trash_chunk();
1550 if (!nbuf) {
1551 status = HCHK_STATUS_L7RSP;
1552 desc = ist("Failed to allocate buffer to eval log-format string");
1553 goto error;
1554 }
1555 nbuf->data = sess_build_logline(check->sess, NULL, b_orig(nbuf), b_size(nbuf), &expect->hdr.name_fmt);
1556 if (!b_data(nbuf)) {
1557 status = HCHK_STATUS_L7RSP;
1558 desc = ist("log-format string evaluated to an empty string");
1559 goto error;
1560 }
1561 npat = ist2(b_orig(nbuf), b_data(nbuf));
1562 }
1563 else if (!(expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG))
1564 npat = expect->hdr.name;
1565
1566 if (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
1567 vbuf = alloc_trash_chunk();
1568 if (!vbuf) {
1569 status = HCHK_STATUS_L7RSP;
1570 desc = ist("Failed to allocate buffer to eval log-format string");
1571 goto error;
1572 }
1573 vbuf->data = sess_build_logline(check->sess, NULL, b_orig(vbuf), b_size(vbuf), &expect->hdr.value_fmt);
1574 if (!b_data(vbuf)) {
1575 status = HCHK_STATUS_L7RSP;
1576 desc = ist("log-format string evaluated to an empty string");
1577 goto error;
1578 }
1579 vpat = ist2(b_orig(vbuf), b_data(vbuf));
1580 }
1581 else if (!(expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG))
1582 vpat = expect->hdr.value;
1583
1584 match = 0;
1585 ctx.blk = NULL;
1586 while (1) {
1587 switch (expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_TYPE) {
1588 case TCPCHK_EXPT_FL_HTTP_HNAME_STR:
1589 if (!http_find_str_header(htx, npat, &ctx, full))
1590 goto end_of_match;
1591 break;
1592 case TCPCHK_EXPT_FL_HTTP_HNAME_BEG:
1593 if (!http_find_pfx_header(htx, npat, &ctx, full))
1594 goto end_of_match;
1595 break;
1596 case TCPCHK_EXPT_FL_HTTP_HNAME_END:
1597 if (!http_find_sfx_header(htx, npat, &ctx, full))
1598 goto end_of_match;
1599 break;
1600 case TCPCHK_EXPT_FL_HTTP_HNAME_SUB:
1601 if (!http_find_sub_header(htx, npat, &ctx, full))
1602 goto end_of_match;
1603 break;
1604 case TCPCHK_EXPT_FL_HTTP_HNAME_REG:
1605 if (!http_match_header(htx, expect->hdr.name_re, &ctx, full))
1606 goto end_of_match;
1607 break;
1608 default:
1609 /* should never happen */
1610 goto end_of_match;
1611 }
1612
1613 /* A header has matched the name pattern, let's test its
1614 * value now (always defined from there). If there is no
1615 * value pattern, it is a good match.
1616 */
1617
1618 if (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE) {
1619 match = 1;
1620 goto end_of_match;
1621 }
1622
1623 value = ctx.value;
1624 switch (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_TYPE) {
1625 case TCPCHK_EXPT_FL_HTTP_HVAL_STR:
1626 if (isteq(value, vpat)) {
1627 match = 1;
1628 goto end_of_match;
1629 }
1630 break;
1631 case TCPCHK_EXPT_FL_HTTP_HVAL_BEG:
1632 if (istlen(value) < istlen(vpat))
1633 break;
1634 value = ist2(istptr(value), istlen(vpat));
1635 if (isteq(value, vpat)) {
1636 match = 1;
1637 goto end_of_match;
1638 }
1639 break;
1640 case TCPCHK_EXPT_FL_HTTP_HVAL_END:
1641 if (istlen(value) < istlen(vpat))
1642 break;
1643 value = ist2(istptr(value) + istlen(value) - istlen(vpat), istlen(vpat));
1644 if (isteq(value, vpat)) {
1645 match = 1;
1646 goto end_of_match;
1647 }
1648 break;
1649 case TCPCHK_EXPT_FL_HTTP_HVAL_SUB:
1650 if (isttest(istist(value, vpat))) {
1651 match = 1;
1652 goto end_of_match;
1653 }
1654 break;
1655 case TCPCHK_EXPT_FL_HTTP_HVAL_REG:
1656 if (regex_exec2(expect->hdr.value_re, istptr(value), istlen(value))) {
1657 match = 1;
1658 goto end_of_match;
1659 }
1660 break;
1661 }
1662 }
1663
1664 end_of_match:
1665 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
1666 if (LIST_ISEMPTY(&expect->onerror_fmt))
1667 desc = htx_sl_res_reason(sl);
1668 break;
1669 }
1670
1671 case TCPCHK_EXPECT_HTTP_BODY:
1672 case TCPCHK_EXPECT_HTTP_BODY_REGEX:
1673 case TCPCHK_EXPECT_HTTP_BODY_LF:
1674 match = 0;
1675 chunk_reset(&trash);
1676 for (blk = htx_get_head_blk(htx); blk; blk = htx_get_next_blk(htx, blk)) {
1677 enum htx_blk_type type = htx_get_blk_type(blk);
1678
1679 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
1680 break;
1681 if (type == HTX_BLK_DATA) {
1682 if (!chunk_istcat(&trash, htx_get_blk_value(htx, blk)))
1683 break;
1684 }
1685 }
1686
1687 if (!b_data(&trash)) {
1688 if (!last_read)
1689 goto wait_more_data;
1690 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
1691 if (LIST_ISEMPTY(&expect->onerror_fmt))
1692 desc = ist("HTTP content check could not find a response body");
1693 goto error;
1694 }
1695
1696 if (expect->type == TCPCHK_EXPECT_HTTP_BODY_LF) {
1697 tmp = alloc_trash_chunk();
1698 if (!tmp) {
1699 status = HCHK_STATUS_L7RSP;
1700 desc = ist("Failed to allocate buffer to eval log-format string");
1701 goto error;
1702 }
1703 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &expect->fmt);
1704 if (!b_data(tmp)) {
1705 status = HCHK_STATUS_L7RSP;
1706 desc = ist("log-format string evaluated to an empty string");
1707 goto error;
1708 }
1709 }
1710
1711 if (!last_read &&
1712 ((expect->type == TCPCHK_EXPECT_HTTP_BODY && b_data(&trash) < istlen(expect->data)) ||
1713 ((expect->type == TCPCHK_EXPECT_HTTP_BODY_LF && b_data(&trash) < b_data(tmp))) ||
1714 (expect->min_recv > 0 && b_data(&trash) < expect->min_recv))) {
1715 ret = TCPCHK_EVAL_WAIT;
1716 goto out;
1717 }
1718
1719 if (expect->type ==TCPCHK_EXPECT_HTTP_BODY)
1720 match = my_memmem(b_orig(&trash), b_data(&trash), istptr(expect->data), istlen(expect->data)) != NULL;
1721 else if (expect->type ==TCPCHK_EXPECT_HTTP_BODY_LF)
1722 match = my_memmem(b_orig(&trash), b_data(&trash), b_orig(tmp), b_data(tmp)) != NULL;
1723 else
1724 match = regex_exec2(expect->regex, b_orig(&trash), b_data(&trash));
1725
1726 /* Set status and description in case of error */
1727 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
1728 if (LIST_ISEMPTY(&expect->onerror_fmt))
1729 desc = (inverse
1730 ? ist("HTTP check matched unwanted content")
1731 : ist("HTTP content check did not match"));
1732 break;
1733
1734
1735 default:
1736 /* should never happen */
1737 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
1738 goto error;
1739 }
1740
1741 /* Wait for more data on mismatch only if no minimum is defined (-1),
1742 * otherwise the absence of match is already conclusive.
1743 */
1744 if (!match && !last_read && (expect->min_recv == -1)) {
1745 ret = TCPCHK_EVAL_WAIT;
1746 goto out;
1747 }
1748
1749 if (!(match ^ inverse))
1750 goto error;
1751
1752 out:
1753 free_trash_chunk(tmp);
1754 free_trash_chunk(nbuf);
1755 free_trash_chunk(vbuf);
1756 free_trash_chunk(msg);
1757 return ret;
1758
1759 error:
1760 ret = TCPCHK_EVAL_STOP;
1761 msg = alloc_trash_chunk();
1762 if (msg)
1763 tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
1764 set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
1765 goto out;
1766
1767 wait_more_data:
1768 ret = TCPCHK_EVAL_WAIT;
1769 goto out;
1770}
1771
1772/* Evaluates a TCP TCPCHK_ACT_EXPECT rule. Returns TCPCHK_EVAL_WAIT to wait for
1773 * more data, TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP
1774 * if an error occurred.
1775 */
1776enum tcpcheck_eval_ret tcpcheck_eval_expect(struct check *check, struct tcpcheck_rule *rule, int last_read)
1777{
1778 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1779 struct tcpcheck_expect *expect = &rule->expect;
1780 struct buffer *msg = NULL, *tmp = NULL;
1781 struct ist desc = IST_NULL;
1782 enum healthcheck_status status;
1783 int match, inverse;
1784
1785 last_read |= b_full(&check->bi);
1786
1787 /* The current expect might need more data than the previous one, check again
1788 * that the minimum amount data required to match is respected.
1789 */
1790 if (!last_read) {
1791 if ((expect->type == TCPCHK_EXPECT_STRING || expect->type == TCPCHK_EXPECT_BINARY) &&
1792 (b_data(&check->bi) < istlen(expect->data))) {
1793 ret = TCPCHK_EVAL_WAIT;
1794 goto out;
1795 }
1796 if (expect->min_recv > 0 && (b_data(&check->bi) < expect->min_recv)) {
1797 ret = TCPCHK_EVAL_WAIT;
1798 goto out;
1799 }
1800 }
1801
1802 inverse = !!(expect->flags & TCPCHK_EXPT_FL_INV);
1803 /* Make GCC happy ; initialize match to a failure state. */
1804 match = inverse;
1805 status = ((expect->err_status != HCHK_STATUS_UNKNOWN) ? expect->err_status : HCHK_STATUS_L7RSP);
1806
1807 switch (expect->type) {
1808 case TCPCHK_EXPECT_STRING:
1809 case TCPCHK_EXPECT_BINARY:
1810 match = my_memmem(b_head(&check->bi), b_data(&check->bi), istptr(expect->data), istlen(expect->data)) != NULL;
1811 break;
1812 case TCPCHK_EXPECT_STRING_REGEX:
1813 match = regex_exec2(expect->regex, b_head(&check->bi), MIN(b_data(&check->bi), b_size(&check->bi)-1));
1814 break;
1815
1816 case TCPCHK_EXPECT_BINARY_REGEX:
1817 chunk_reset(&trash);
1818 dump_binary(&trash, b_head(&check->bi), b_data(&check->bi));
1819 match = regex_exec2(expect->regex, b_head(&trash), MIN(b_data(&trash), b_size(&trash)-1));
1820 break;
1821
1822 case TCPCHK_EXPECT_STRING_LF:
1823 case TCPCHK_EXPECT_BINARY_LF:
1824 match = 0;
1825 tmp = alloc_trash_chunk();
1826 if (!tmp) {
1827 status = HCHK_STATUS_L7RSP;
1828 desc = ist("Failed to allocate buffer to eval format string");
1829 goto error;
1830 }
1831 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &expect->fmt);
1832 if (!b_data(tmp)) {
1833 status = HCHK_STATUS_L7RSP;
1834 desc = ist("log-format string evaluated to an empty string");
1835 goto error;
1836 }
1837 if (expect->type == TCPCHK_EXPECT_BINARY_LF) {
1838 int len = tmp->data;
1839 if (parse_binary(b_orig(tmp), &tmp->area, &len, NULL) == 0) {
1840 status = HCHK_STATUS_L7RSP;
1841 desc = ist("Failed to parse hexastring resulting of eval of a log-format string");
1842 goto error;
1843 }
1844 tmp->data = len;
1845 }
1846 if (b_data(&check->bi) < tmp->data) {
1847 if (!last_read) {
1848 ret = TCPCHK_EVAL_WAIT;
1849 goto out;
1850 }
1851 break;
1852 }
1853 match = my_memmem(b_head(&check->bi), b_data(&check->bi), b_orig(tmp), b_data(tmp)) != NULL;
1854 break;
1855
1856 case TCPCHK_EXPECT_CUSTOM:
1857 if (expect->custom)
1858 ret = expect->custom(check, rule, last_read);
1859 goto out;
1860 default:
1861 /* Should never happen. */
1862 ret = TCPCHK_EVAL_STOP;
1863 goto out;
1864 }
1865
1866
1867 /* Wait for more data on mismatch only if no minimum is defined (-1),
1868 * otherwise the absence of match is already conclusive.
1869 */
1870 if (!match && !last_read && (expect->min_recv == -1)) {
1871 ret = TCPCHK_EVAL_WAIT;
1872 goto out;
1873 }
1874
1875 /* Result as expected, next rule. */
1876 if (match ^ inverse)
1877 goto out;
1878
1879 error:
1880 /* From this point on, we matched something we did not want, this is an error state. */
1881 ret = TCPCHK_EVAL_STOP;
1882 msg = alloc_trash_chunk();
1883 if (msg)
1884 tcpcheck_expect_onerror_message(msg, check, rule, match, desc);
1885 set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
1886 free_trash_chunk(msg);
1887
1888 out:
1889 free_trash_chunk(tmp);
1890 return ret;
1891}
1892
1893/* Evaluates a TCPCHK_ACT_ACTION_KW rule. Returns TCPCHK_EVAL_CONTINUE to
1894 * evaluate the next rule or TCPCHK_EVAL_STOP if an error occurred. It never
1895 * waits.
1896 */
1897enum tcpcheck_eval_ret tcpcheck_eval_action_kw(struct check *check, struct tcpcheck_rule *rule)
1898{
1899 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1900 struct act_rule *act_rule;
1901 enum act_return act_ret;
1902
1903 act_rule =rule->action_kw.rule;
1904 act_ret = act_rule->action_ptr(act_rule, check->proxy, check->sess, NULL, 0);
1905 if (act_ret != ACT_RET_CONT) {
1906 chunk_printf(&trash, "TCPCHK ACTION unexpected result at step %d\n",
1907 tcpcheck_get_step_id(check, rule));
1908 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1909 ret = TCPCHK_EVAL_STOP;
1910 }
1911
1912 return ret;
1913}
1914
1915/* Executes a tcp-check ruleset. Note that this is called both from the
1916 * connection's wake() callback and from the check scheduling task. It returns
1917 * 0 on normal cases, or <0 if a close() has happened on an existing connection,
1918 * presenting the risk of an fd replacement.
1919 *
1920 * Please do NOT place any return statement in this function and only leave
1921 * via the out_end_tcpcheck label after setting retcode.
1922 */
1923int tcpcheck_main(struct check *check)
1924{
1925 struct tcpcheck_rule *rule;
1926 struct conn_stream *cs = check->cs;
1927 struct connection *conn = cs_conn(cs);
1928 int must_read = 1, last_read = 0;
1929 int ret, retcode = 0;
1930 enum tcpcheck_eval_ret eval_ret;
1931
1932 /* here, we know that the check is complete or that it failed */
1933 if (check->result != CHK_RES_UNKNOWN)
1934 goto out;
1935
1936 /* Note: the conn-stream and the connection may only be undefined before
1937 * the first rule evaluation (it is always a connect rule) or when the
1938 * conn-stream allocation failed on the first connect.
1939 */
1940
1941 /* 1- check for connection error, if any */
1942 if ((conn && conn->flags & CO_FL_ERROR) || (cs && cs->flags & CS_FL_ERROR))
1943 goto out_end_tcpcheck;
1944
1945 /* 2- check if we are waiting for the connection establishment. It only
1946 * happens during TCPCHK_ACT_CONNECT. */
1947 if (check->current_step && check->current_step->action == TCPCHK_ACT_CONNECT) {
1948 if (conn->flags & CO_FL_WAIT_XPRT) {
1949 struct tcpcheck_rule *next;
1950
1951 next = get_next_tcpcheck_rule(check->tcpcheck_rules, check->current_step);
1952 if (next && next->action == TCPCHK_ACT_SEND) {
1953 if (!(check->wait_list.events & SUB_RETRY_SEND))
1954 conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
1955 goto out;
1956 }
1957 else {
1958 eval_ret = tcpcheck_eval_recv(check, check->current_step);
1959 if (eval_ret == TCPCHK_EVAL_STOP)
1960 goto out_end_tcpcheck;
1961 else if (eval_ret == TCPCHK_EVAL_WAIT)
1962 goto out;
1963 last_read = ((conn->flags & CO_FL_ERROR) || (cs->flags & (CS_FL_ERROR|CS_FL_EOS)));
1964 must_read = 0;
1965 }
1966 }
1967 rule = LIST_NEXT(&check->current_step->list, typeof(rule), list);
1968 }
1969
1970 /* 3- check for pending outgoing data. It only happens during
1971 * TCPCHK_ACT_SEND. */
1972 else if (check->current_step && check->current_step->action == TCPCHK_ACT_SEND) {
1973 if (b_data(&check->bo)) {
1974 /* We're already waiting to be able to send, give up */
1975 if (check->wait_list.events & SUB_RETRY_SEND)
1976 goto out;
1977
1978 ret = conn->mux->snd_buf(cs, &check->bo,
1979 (IS_HTX_CONN(conn) ? (htxbuf(&check->bo))->data: b_data(&check->bo)), 0);
1980 if (ret <= 0) {
1981 if ((conn->flags & CO_FL_ERROR) || (cs->flags & CS_FL_ERROR))
1982 goto out_end_tcpcheck;
1983 }
1984 if ((IS_HTX_CONN(conn) && !htx_is_empty(htxbuf(&check->bo))) || b_data(&check->bo)) {
1985 conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
1986 goto out;
1987 }
1988 }
1989 rule = LIST_NEXT(&check->current_step->list, typeof(rule), list);
1990 }
1991
1992 /* 4- check if a rule must be resume. It happens if check->current_step
1993 * is defined. */
1994 else if (check->current_step)
1995 rule = check->current_step;
1996
1997 /* 5- It is the first evaluation. We must create a session and preset
1998 * tcp-check variables */
1999 else {
2000 struct tcpcheck_var *var;
2001
2002 /* First evaluation, create a session */
2003 check->sess = session_new(&checks_fe, NULL, &check->obj_type);
2004 if (!check->sess) {
2005 chunk_printf(&trash, "TCPCHK error allocating check session");
2006 set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.area);
2007 goto out_end_tcpcheck;
2008 }
2009 vars_init(&check->vars, SCOPE_CHECK);
2010 rule = LIST_NEXT(check->tcpcheck_rules->list, typeof(rule), list);
2011
2012 /* Preset tcp-check variables */
2013 list_for_each_entry(var, &check->tcpcheck_rules->preset_vars, list) {
2014 struct sample smp;
2015
2016 memset(&smp, 0, sizeof(smp));
2017 smp_set_owner(&smp, check->proxy, check->sess, NULL, SMP_OPT_FINAL);
2018 smp.data = var->data;
2019 vars_set_by_name_ifexist(istptr(var->name), istlen(var->name), &smp);
2020 }
2021 }
2022
2023 /* Now evaluate the tcp-check rules */
2024
2025 list_for_each_entry_from(rule, check->tcpcheck_rules->list, list) {
2026 check->code = 0;
2027 switch (rule->action) {
2028 case TCPCHK_ACT_CONNECT:
2029 check->current_step = rule;
2030
2031 /* close but not release yet previous connection */
2032 if (check->cs) {
2033 cs_close(check->cs);
2034 retcode = -1; /* do not reuse the fd in the caller! */
2035 }
2036 eval_ret = tcpcheck_eval_connect(check, rule);
2037
2038 /* Refresh conn-stream and connection */
2039 cs = check->cs;
2040 conn = cs_conn(cs);
2041 must_read = 1; last_read = 0;
2042 break;
2043 case TCPCHK_ACT_SEND:
2044 check->current_step = rule;
2045 eval_ret = tcpcheck_eval_send(check, rule);
2046 must_read = 1;
2047 break;
2048 case TCPCHK_ACT_EXPECT:
2049 check->current_step = rule;
2050 if (must_read) {
2051 if (check->proxy->timeout.check)
2052 check->task->expire = tick_add_ifset(now_ms, check->proxy->timeout.check);
2053
2054 eval_ret = tcpcheck_eval_recv(check, rule);
2055 if (eval_ret == TCPCHK_EVAL_STOP)
2056 goto out_end_tcpcheck;
2057 else if (eval_ret == TCPCHK_EVAL_WAIT)
2058 goto out;
2059 last_read = ((conn->flags & CO_FL_ERROR) || (cs->flags & (CS_FL_ERROR|CS_FL_EOS)));
2060 must_read = 0;
2061 }
2062
2063 eval_ret = ((check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK
2064 ? tcpcheck_eval_expect_http(check, rule, last_read)
2065 : tcpcheck_eval_expect(check, rule, last_read));
2066
2067 if (eval_ret == TCPCHK_EVAL_WAIT) {
2068 check->current_step = rule->expect.head;
2069 if (!(check->wait_list.events & SUB_RETRY_RECV))
2070 conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
2071 }
2072 break;
2073 case TCPCHK_ACT_ACTION_KW:
2074 /* Don't update the current step */
2075 eval_ret = tcpcheck_eval_action_kw(check, rule);
2076 break;
2077 default:
2078 /* Otherwise, just go to the next one and don't update
2079 * the current step
2080 */
2081 eval_ret = TCPCHK_EVAL_CONTINUE;
2082 break;
2083 }
2084
2085 switch (eval_ret) {
2086 case TCPCHK_EVAL_CONTINUE:
2087 break;
2088 case TCPCHK_EVAL_WAIT:
2089 goto out;
2090 case TCPCHK_EVAL_STOP:
2091 goto out_end_tcpcheck;
2092 }
2093 }
2094
2095 /* All rules was evaluated */
2096 if (check->current_step) {
2097 rule = check->current_step;
2098
2099 if (rule->action == TCPCHK_ACT_EXPECT) {
2100 struct buffer *msg;
2101 enum healthcheck_status status;
2102
2103 if (check->server &&
2104 (check->server->proxy->options & PR_O_DISABLE404) &&
2105 (check->server->next_state != SRV_ST_STOPPED) &&
2106 (check->code == 404)) {
2107 set_server_check_status(check, HCHK_STATUS_L7OKCD, NULL);
2108 goto out_end_tcpcheck;
2109 }
2110
2111 msg = alloc_trash_chunk();
2112 if (msg)
2113 tcpcheck_expect_onsuccess_message(msg, check, rule, IST_NULL);
2114 status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
2115 set_server_check_status(check, status, (msg ? b_head(msg) : "(tcp-check)"));
2116 free_trash_chunk(msg);
2117 }
2118 else if (rule->action == TCPCHK_ACT_CONNECT) {
2119 const char *msg = ((rule->connect.options & TCPCHK_OPT_IMPLICIT) ? NULL : "(tcp-check)");
2120 enum healthcheck_status status = HCHK_STATUS_L4OK;
2121#ifdef USE_OPENSSL
2122 if (ssl_sock_is_ssl(conn))
2123 status = HCHK_STATUS_L6OK;
2124#endif
2125 set_server_check_status(check, status, msg);
2126 }
2127 }
2128 else
2129 set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
2130
2131 out_end_tcpcheck:
2132 if ((conn && conn->flags & CO_FL_ERROR) || (cs && cs->flags & CS_FL_ERROR))
2133 chk_report_conn_err(check, errno, 0);
2134
2135 out:
2136 return retcode;
2137}
2138
2139
2140/**************************************************************************/
2141/******************* Internals to parse tcp-check rules *******************/
2142/**************************************************************************/
2143struct action_kw_list tcp_check_keywords = {
2144 .list = LIST_HEAD_INIT(tcp_check_keywords.list),
2145};
2146
2147/* Creates a tcp-check rule resulting from parsing a custom keyword. NULL is
2148 * returned on error.
2149 */
2150struct tcpcheck_rule *parse_tcpcheck_action(char **args, int cur_arg, struct proxy *px,
2151 struct list *rules, struct action_kw *kw,
2152 const char *file, int line, char **errmsg)
2153{
2154 struct tcpcheck_rule *chk = NULL;
2155 struct act_rule *actrule = NULL;
2156
2157 actrule = calloc(1, sizeof(*actrule));
2158 if (!actrule) {
2159 memprintf(errmsg, "out of memory");
2160 goto error;
2161 }
2162 actrule->kw = kw;
2163 actrule->from = ACT_F_TCP_CHK;
2164
2165 cur_arg++;
2166 if (kw->parse((const char **)args, &cur_arg, px, actrule, errmsg) == ACT_RET_PRS_ERR) {
2167 memprintf(errmsg, "'%s' : %s", kw->kw, *errmsg);
2168 goto error;
2169 }
2170
2171 chk = calloc(1, sizeof(*chk));
2172 if (!chk) {
2173 memprintf(errmsg, "out of memory");
2174 goto error;
2175 }
2176 chk->action = TCPCHK_ACT_ACTION_KW;
2177 chk->action_kw.rule = actrule;
2178 return chk;
2179
2180 error:
2181 free(actrule);
2182 return NULL;
2183}
2184
2185/* Parses and creates a tcp-check connect or an http-check connect rule. NULL is
2186 * returned on error.
2187 */
2188struct tcpcheck_rule *parse_tcpcheck_connect(char **args, int cur_arg, struct proxy *px, struct list *rules,
2189 const char *file, int line, char **errmsg)
2190{
2191 struct tcpcheck_rule *chk = NULL;
2192 struct sockaddr_storage *sk = NULL;
2193 char *comment = NULL, *sni = NULL, *alpn = NULL;
2194 struct sample_expr *port_expr = NULL;
2195 const struct mux_proto_list *mux_proto = NULL;
2196 unsigned short conn_opts = 0;
2197 long port = 0;
2198 int alpn_len = 0;
2199
2200 list_for_each_entry(chk, rules, list) {
2201 if (chk->action == TCPCHK_ACT_CONNECT)
2202 break;
2203 if (chk->action == TCPCHK_ACT_COMMENT ||
2204 chk->action == TCPCHK_ACT_ACTION_KW ||
2205 (chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)))
2206 continue;
2207
2208 memprintf(errmsg, "first step MUST also be a 'connect', "
2209 "optionally preceded by a 'set-var', an 'unset-var' or a 'comment', "
2210 "when there is a 'connect' step in the tcp-check ruleset");
2211 goto error;
2212 }
2213
2214 cur_arg++;
2215 while (*(args[cur_arg])) {
2216 if (strcmp(args[cur_arg], "default") == 0)
2217 conn_opts |= TCPCHK_OPT_DEFAULT_CONNECT;
2218 else if (strcmp(args[cur_arg], "addr") == 0) {
2219 int port1, port2;
Willy Tarreau51cd5952020-06-05 12:25:38 +02002220
2221 if (!*(args[cur_arg+1])) {
2222 memprintf(errmsg, "'%s' expects <ipv4|ipv6> as argument.", args[cur_arg]);
2223 goto error;
2224 }
2225
Willy Tarreau65ec4e32020-09-16 19:17:08 +02002226 sk = str2sa_range(args[cur_arg+1], NULL, &port1, &port2, NULL, NULL,
2227 errmsg, NULL, NULL, PA_O_RESOLVE | PA_O_PORT_OK | PA_O_STREAM | PA_O_CONNECT);
Willy Tarreau51cd5952020-06-05 12:25:38 +02002228 if (!sk) {
2229 memprintf(errmsg, "'%s' : %s.", args[cur_arg], *errmsg);
2230 goto error;
2231 }
2232
Willy Tarreau51cd5952020-06-05 12:25:38 +02002233 cur_arg++;
2234 }
2235 else if (strcmp(args[cur_arg], "port") == 0) {
2236 const char *p, *end;
2237
2238 if (!*(args[cur_arg+1])) {
2239 memprintf(errmsg, "'%s' expects a port number or a sample expression as argument.", args[cur_arg]);
2240 goto error;
2241 }
2242 cur_arg++;
2243
2244 port = 0;
2245 release_sample_expr(port_expr);
2246 p = args[cur_arg]; end = p + strlen(p);
2247 port = read_uint(&p, end);
2248 if (p != end) {
2249 int idx = 0;
2250
2251 px->conf.args.ctx = ARGC_SRV;
2252 port_expr = sample_parse_expr((char *[]){args[cur_arg], NULL}, &idx,
2253 file, line, errmsg, &px->conf.args, NULL);
2254
2255 if (!port_expr) {
2256 memprintf(errmsg, "error detected while parsing port expression : %s", *errmsg);
2257 goto error;
2258 }
2259 if (!(port_expr->fetch->val & SMP_VAL_BE_CHK_RUL)) {
2260 memprintf(errmsg, "error detected while parsing port expression : "
2261 " fetch method '%s' extracts information from '%s', "
2262 "none of which is available here.\n",
2263 args[cur_arg], sample_src_names(port_expr->fetch->use));
2264 goto error;
2265 }
2266 px->http_needed |= !!(port_expr->fetch->use & SMP_USE_HTTP_ANY);
2267 }
2268 else if (port > 65535 || port < 1) {
2269 memprintf(errmsg, "expects a valid TCP port (from range 1 to 65535) or a sample expression, got %s.",
2270 args[cur_arg]);
2271 goto error;
2272 }
2273 }
2274 else if (strcmp(args[cur_arg], "proto") == 0) {
2275 if (!*(args[cur_arg+1])) {
2276 memprintf(errmsg, "'%s' expects a MUX protocol as argument.", args[cur_arg]);
2277 goto error;
2278 }
2279 mux_proto = get_mux_proto(ist2(args[cur_arg+1], strlen(args[cur_arg+1])));
2280 if (!mux_proto) {
2281 memprintf(errmsg, "'%s' : unknown MUX protocol '%s'.", args[cur_arg], args[cur_arg+1]);
2282 goto error;
2283 }
2284 cur_arg++;
2285 }
2286 else if (strcmp(args[cur_arg], "comment") == 0) {
2287 if (!*(args[cur_arg+1])) {
2288 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2289 goto error;
2290 }
2291 cur_arg++;
2292 free(comment);
2293 comment = strdup(args[cur_arg]);
2294 if (!comment) {
2295 memprintf(errmsg, "out of memory");
2296 goto error;
2297 }
2298 }
2299 else if (strcmp(args[cur_arg], "send-proxy") == 0)
2300 conn_opts |= TCPCHK_OPT_SEND_PROXY;
2301 else if (strcmp(args[cur_arg], "via-socks4") == 0)
2302 conn_opts |= TCPCHK_OPT_SOCKS4;
2303 else if (strcmp(args[cur_arg], "linger") == 0)
2304 conn_opts |= TCPCHK_OPT_LINGER;
2305#ifdef USE_OPENSSL
2306 else if (strcmp(args[cur_arg], "ssl") == 0) {
2307 px->options |= PR_O_TCPCHK_SSL;
2308 conn_opts |= TCPCHK_OPT_SSL;
2309 }
2310 else if (strcmp(args[cur_arg], "sni") == 0) {
2311 if (!*(args[cur_arg+1])) {
2312 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2313 goto error;
2314 }
2315 cur_arg++;
2316 free(sni);
2317 sni = strdup(args[cur_arg]);
2318 if (!sni) {
2319 memprintf(errmsg, "out of memory");
2320 goto error;
2321 }
2322 }
2323 else if (strcmp(args[cur_arg], "alpn") == 0) {
2324#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2325 free(alpn);
2326 if (ssl_sock_parse_alpn(args[cur_arg + 1], &alpn, &alpn_len, errmsg)) {
2327 memprintf(errmsg, "'%s' : %s", args[cur_arg], *errmsg);
2328 goto error;
2329 }
2330 cur_arg++;
2331#else
2332 memprintf(errmsg, "'%s' : library does not support TLS ALPN extension.", args[cur_arg]);
2333 goto error;
2334#endif
2335 }
2336#endif /* USE_OPENSSL */
2337
2338 else {
2339 memprintf(errmsg, "expects 'comment', 'port', 'addr', 'send-proxy'"
2340#ifdef USE_OPENSSL
2341 ", 'ssl', 'sni', 'alpn'"
2342#endif /* USE_OPENSSL */
2343 " or 'via-socks4', 'linger', 'default' but got '%s' as argument.",
2344 args[cur_arg]);
2345 goto error;
2346 }
2347 cur_arg++;
2348 }
2349
2350 chk = calloc(1, sizeof(*chk));
2351 if (!chk) {
2352 memprintf(errmsg, "out of memory");
2353 goto error;
2354 }
2355 chk->action = TCPCHK_ACT_CONNECT;
2356 chk->comment = comment;
2357 chk->connect.port = port;
2358 chk->connect.options = conn_opts;
2359 chk->connect.sni = sni;
2360 chk->connect.alpn = alpn;
2361 chk->connect.alpn_len= alpn_len;
2362 chk->connect.port_expr= port_expr;
2363 chk->connect.mux_proto= mux_proto;
2364 if (sk)
2365 chk->connect.addr = *sk;
2366 return chk;
2367
2368 error:
2369 free(alpn);
2370 free(sni);
2371 free(comment);
2372 release_sample_expr(port_expr);
2373 return NULL;
2374}
2375
2376/* Parses and creates a tcp-check send rule. NULL is returned on error */
2377struct tcpcheck_rule *parse_tcpcheck_send(char **args, int cur_arg, struct proxy *px, struct list *rules,
2378 const char *file, int line, char **errmsg)
2379{
2380 struct tcpcheck_rule *chk = NULL;
2381 char *comment = NULL, *data = NULL;
2382 enum tcpcheck_send_type type = TCPCHK_SEND_UNDEF;
2383
2384 if (strcmp(args[cur_arg], "send-binary-lf") == 0)
2385 type = TCPCHK_SEND_BINARY_LF;
2386 else if (strcmp(args[cur_arg], "send-binary") == 0)
2387 type = TCPCHK_SEND_BINARY;
2388 else if (strcmp(args[cur_arg], "send-lf") == 0)
2389 type = TCPCHK_SEND_STRING_LF;
2390 else if (strcmp(args[cur_arg], "send") == 0)
2391 type = TCPCHK_SEND_STRING;
2392
2393 if (!*(args[cur_arg+1])) {
2394 memprintf(errmsg, "'%s' expects a %s as argument",
2395 (type == TCPCHK_SEND_BINARY ? "binary string": "string"), args[cur_arg]);
2396 goto error;
2397 }
2398
2399 data = args[cur_arg+1];
2400
2401 cur_arg += 2;
2402 while (*(args[cur_arg])) {
2403 if (strcmp(args[cur_arg], "comment") == 0) {
2404 if (!*(args[cur_arg+1])) {
2405 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2406 goto error;
2407 }
2408 cur_arg++;
2409 free(comment);
2410 comment = strdup(args[cur_arg]);
2411 if (!comment) {
2412 memprintf(errmsg, "out of memory");
2413 goto error;
2414 }
2415 }
2416 else {
2417 memprintf(errmsg, "expects 'comment' but got '%s' as argument.",
2418 args[cur_arg]);
2419 goto error;
2420 }
2421 cur_arg++;
2422 }
2423
2424 chk = calloc(1, sizeof(*chk));
2425 if (!chk) {
2426 memprintf(errmsg, "out of memory");
2427 goto error;
2428 }
2429 chk->action = TCPCHK_ACT_SEND;
2430 chk->comment = comment;
2431 chk->send.type = type;
2432
2433 switch (chk->send.type) {
2434 case TCPCHK_SEND_STRING:
2435 chk->send.data = ist2(strdup(data), strlen(data));
2436 if (!isttest(chk->send.data)) {
2437 memprintf(errmsg, "out of memory");
2438 goto error;
2439 }
2440 break;
2441 case TCPCHK_SEND_BINARY: {
2442 int len = chk->send.data.len;
2443 if (parse_binary(data, &chk->send.data.ptr, &len, errmsg) == 0) {
2444 memprintf(errmsg, "'%s' invalid binary string (%s).\n", data, *errmsg);
2445 goto error;
2446 }
2447 chk->send.data.len = len;
2448 break;
2449 }
2450 case TCPCHK_SEND_STRING_LF:
2451 case TCPCHK_SEND_BINARY_LF:
2452 LIST_INIT(&chk->send.fmt);
2453 px->conf.args.ctx = ARGC_SRV;
2454 if (!parse_logformat_string(data, px, &chk->send.fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
2455 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", data, *errmsg);
2456 goto error;
2457 }
2458 break;
2459 case TCPCHK_SEND_HTTP:
2460 case TCPCHK_SEND_UNDEF:
2461 goto error;
2462 }
2463
2464 return chk;
2465
2466 error:
2467 free(chk);
2468 free(comment);
2469 return NULL;
2470}
2471
2472/* Parses and creates a http-check send rule. NULL is returned on error */
2473struct tcpcheck_rule *parse_tcpcheck_send_http(char **args, int cur_arg, struct proxy *px, struct list *rules,
2474 const char *file, int line, char **errmsg)
2475{
2476 struct tcpcheck_rule *chk = NULL;
2477 struct tcpcheck_http_hdr *hdr = NULL;
2478 struct http_hdr hdrs[global.tune.max_http_hdr];
2479 char *meth = NULL, *uri = NULL, *vsn = NULL;
2480 char *body = NULL, *comment = NULL;
2481 unsigned int flags = 0;
2482 int i = 0, host_hdr = -1;
2483
2484 cur_arg++;
2485 while (*(args[cur_arg])) {
2486 if (strcmp(args[cur_arg], "meth") == 0) {
2487 if (!*(args[cur_arg+1])) {
2488 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2489 goto error;
2490 }
2491 cur_arg++;
2492 meth = args[cur_arg];
2493 }
2494 else if (strcmp(args[cur_arg], "uri") == 0 || strcmp(args[cur_arg], "uri-lf") == 0) {
2495 if (!*(args[cur_arg+1])) {
2496 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2497 goto error;
2498 }
2499 flags &= ~TCPCHK_SND_HTTP_FL_URI_FMT;
2500 if (strcmp(args[cur_arg], "uri-lf") == 0)
2501 flags |= TCPCHK_SND_HTTP_FL_URI_FMT;
2502 cur_arg++;
2503 uri = args[cur_arg];
2504 }
2505 else if (strcmp(args[cur_arg], "ver") == 0) {
2506 if (!*(args[cur_arg+1])) {
2507 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2508 goto error;
2509 }
2510 cur_arg++;
2511 vsn = args[cur_arg];
2512 }
2513 else if (strcmp(args[cur_arg], "hdr") == 0) {
2514 if (!*args[cur_arg+1] || !*args[cur_arg+2]) {
2515 memprintf(errmsg, "'%s' expects <name> and <value> as arguments", args[cur_arg]);
2516 goto error;
2517 }
2518
2519 if (strcasecmp(args[cur_arg+1], "host") == 0) {
2520 if (host_hdr >= 0) {
2521 memprintf(errmsg, "'%s' header already defined (previous value is '%s')",
2522 args[cur_arg+1], istptr(hdrs[host_hdr].v));
2523 goto error;
2524 }
2525 host_hdr = i;
2526 }
2527 else if (strcasecmp(args[cur_arg+1], "connection") == 0 ||
2528 strcasecmp(args[cur_arg+1], "content-length") == 0 ||
2529 strcasecmp(args[cur_arg+1], "transfer-encoding") == 0)
2530 goto skip_hdr;
2531
2532 hdrs[i].n = ist2(args[cur_arg+1], strlen(args[cur_arg+1]));
2533 hdrs[i].v = ist2(args[cur_arg+2], strlen(args[cur_arg+2]));
2534 i++;
2535 skip_hdr:
2536 cur_arg += 2;
2537 }
2538 else if (strcmp(args[cur_arg], "body") == 0 || strcmp(args[cur_arg], "body-lf") == 0) {
2539 if (!*(args[cur_arg+1])) {
2540 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2541 goto error;
2542 }
2543 flags &= ~TCPCHK_SND_HTTP_FL_BODY_FMT;
2544 if (strcmp(args[cur_arg], "body-lf") == 0)
2545 flags |= TCPCHK_SND_HTTP_FL_BODY_FMT;
2546 cur_arg++;
2547 body = args[cur_arg];
2548 }
2549 else if (strcmp(args[cur_arg], "comment") == 0) {
2550 if (!*(args[cur_arg+1])) {
2551 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2552 goto error;
2553 }
2554 cur_arg++;
2555 free(comment);
2556 comment = strdup(args[cur_arg]);
2557 if (!comment) {
2558 memprintf(errmsg, "out of memory");
2559 goto error;
2560 }
2561 }
2562 else {
2563 memprintf(errmsg, "expects 'comment', 'meth', 'uri', 'uri-lf', 'ver', 'hdr', 'body' or 'body-lf'"
2564 " but got '%s' as argument.", args[cur_arg]);
2565 goto error;
2566 }
2567 cur_arg++;
2568 }
2569
2570 hdrs[i].n = hdrs[i].v = IST_NULL;
2571
2572 chk = calloc(1, sizeof(*chk));
2573 if (!chk) {
2574 memprintf(errmsg, "out of memory");
2575 goto error;
2576 }
2577 chk->action = TCPCHK_ACT_SEND;
2578 chk->comment = comment; comment = NULL;
2579 chk->send.type = TCPCHK_SEND_HTTP;
2580 chk->send.http.flags = flags;
2581 LIST_INIT(&chk->send.http.hdrs);
2582
2583 if (meth) {
2584 chk->send.http.meth.meth = find_http_meth(meth, strlen(meth));
2585 chk->send.http.meth.str.area = strdup(meth);
2586 chk->send.http.meth.str.data = strlen(meth);
2587 if (!chk->send.http.meth.str.area) {
2588 memprintf(errmsg, "out of memory");
2589 goto error;
2590 }
2591 }
2592 if (uri) {
2593 if (chk->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) {
2594 LIST_INIT(&chk->send.http.uri_fmt);
2595 px->conf.args.ctx = ARGC_SRV;
2596 if (!parse_logformat_string(uri, px, &chk->send.http.uri_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
2597 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", uri, *errmsg);
2598 goto error;
2599 }
2600 }
2601 else {
2602 chk->send.http.uri = ist2(strdup(uri), strlen(uri));
2603 if (!isttest(chk->send.http.uri)) {
2604 memprintf(errmsg, "out of memory");
2605 goto error;
2606 }
2607 }
2608 }
2609 if (vsn) {
2610 chk->send.http.vsn = ist2(strdup(vsn), strlen(vsn));
2611 if (!isttest(chk->send.http.vsn)) {
2612 memprintf(errmsg, "out of memory");
2613 goto error;
2614 }
2615 }
2616 for (i = 0; istlen(hdrs[i].n); i++) {
2617 hdr = calloc(1, sizeof(*hdr));
2618 if (!hdr) {
2619 memprintf(errmsg, "out of memory");
2620 goto error;
2621 }
2622 LIST_INIT(&hdr->value);
2623 hdr->name = istdup(hdrs[i].n);
2624 if (!isttest(hdr->name)) {
2625 memprintf(errmsg, "out of memory");
2626 goto error;
2627 }
2628
2629 ist0(hdrs[i].v);
2630 if (!parse_logformat_string(istptr(hdrs[i].v), px, &hdr->value, 0, SMP_VAL_BE_CHK_RUL, errmsg))
2631 goto error;
2632 LIST_ADDQ(&chk->send.http.hdrs, &hdr->list);
2633 hdr = NULL;
2634 }
2635
2636 if (body) {
2637 if (chk->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) {
2638 LIST_INIT(&chk->send.http.body_fmt);
2639 px->conf.args.ctx = ARGC_SRV;
2640 if (!parse_logformat_string(body, px, &chk->send.http.body_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
2641 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", body, *errmsg);
2642 goto error;
2643 }
2644 }
2645 else {
2646 chk->send.http.body = ist2(strdup(body), strlen(body));
2647 if (!isttest(chk->send.http.body)) {
2648 memprintf(errmsg, "out of memory");
2649 goto error;
2650 }
2651 }
2652 }
2653
2654 return chk;
2655
2656 error:
2657 free_tcpcheck_http_hdr(hdr);
2658 free_tcpcheck(chk, 0);
2659 free(comment);
2660 return NULL;
2661}
2662
2663/* Parses and creates a http-check comment rule. NULL is returned on error */
2664struct tcpcheck_rule *parse_tcpcheck_comment(char **args, int cur_arg, struct proxy *px, struct list *rules,
2665 const char *file, int line, char **errmsg)
2666{
2667 struct tcpcheck_rule *chk = NULL;
2668 char *comment = NULL;
2669
2670 if (!*(args[cur_arg+1])) {
2671 memprintf(errmsg, "expects a string as argument");
2672 goto error;
2673 }
2674 cur_arg++;
2675 comment = strdup(args[cur_arg]);
2676 if (!comment) {
2677 memprintf(errmsg, "out of memory");
2678 goto error;
2679 }
2680
2681 chk = calloc(1, sizeof(*chk));
2682 if (!chk) {
2683 memprintf(errmsg, "out of memory");
2684 goto error;
2685 }
2686 chk->action = TCPCHK_ACT_COMMENT;
2687 chk->comment = comment;
2688 return chk;
2689
2690 error:
2691 free(comment);
2692 return NULL;
2693}
2694
2695/* Parses and creates a tcp-check or an http-check expect rule. NULL is returned
2696 * on error. <proto> is set to the right protocol flags (covered by the
2697 * TCPCHK_RULES_PROTO_CHK mask).
2698 */
2699struct tcpcheck_rule *parse_tcpcheck_expect(char **args, int cur_arg, struct proxy *px,
2700 struct list *rules, unsigned int proto,
2701 const char *file, int line, char **errmsg)
2702{
2703 struct tcpcheck_rule *prev_check, *chk = NULL;
2704 struct sample_expr *status_expr = NULL;
2705 char *on_success_msg, *on_error_msg, *comment, *pattern, *npat, *vpat;
2706 enum tcpcheck_expect_type type = TCPCHK_EXPECT_UNDEF;
2707 enum healthcheck_status ok_st = HCHK_STATUS_UNKNOWN;
2708 enum healthcheck_status err_st = HCHK_STATUS_UNKNOWN;
2709 enum healthcheck_status tout_st = HCHK_STATUS_UNKNOWN;
2710 unsigned int flags = 0;
2711 long min_recv = -1;
2712 int inverse = 0;
2713
2714 on_success_msg = on_error_msg = comment = pattern = npat = vpat = NULL;
2715 if (!*(args[cur_arg+1])) {
2716 memprintf(errmsg, "expects at least a matching pattern as arguments");
2717 goto error;
2718 }
2719
2720 cur_arg++;
2721 while (*(args[cur_arg])) {
2722 int in_pattern = 0;
2723
2724 rescan:
2725 if (strcmp(args[cur_arg], "min-recv") == 0) {
2726 if (in_pattern) {
2727 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2728 goto error;
2729 }
2730 if (!*(args[cur_arg+1])) {
2731 memprintf(errmsg, "'%s' expects a integer as argument", args[cur_arg]);
2732 goto error;
2733 }
2734 /* Use an signed integer here because of chksize */
2735 cur_arg++;
2736 min_recv = atol(args[cur_arg]);
2737 if (min_recv < -1 || min_recv > INT_MAX) {
2738 memprintf(errmsg, "'%s' expects -1 or an integer from 0 to INT_MAX" , args[cur_arg-1]);
2739 goto error;
2740 }
2741 }
2742 else if (*(args[cur_arg]) == '!') {
2743 in_pattern = 1;
2744 while (*(args[cur_arg]) == '!') {
2745 inverse = !inverse;
2746 args[cur_arg]++;
2747 }
2748 if (!*(args[cur_arg]))
2749 cur_arg++;
2750 goto rescan;
2751 }
2752 else if (strcmp(args[cur_arg], "string") == 0 || strcmp(args[cur_arg], "rstring") == 0) {
2753 if (type != TCPCHK_EXPECT_UNDEF) {
2754 memprintf(errmsg, "only on pattern expected");
2755 goto error;
2756 }
2757 if (proto != TCPCHK_RULES_HTTP_CHK)
2758 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_STRING : TCPCHK_EXPECT_STRING_REGEX);
2759 else
2760 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_HTTP_BODY : TCPCHK_EXPECT_HTTP_BODY_REGEX);
2761
2762 if (!*(args[cur_arg+1])) {
2763 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2764 goto error;
2765 }
2766 cur_arg++;
2767 pattern = args[cur_arg];
2768 }
2769 else if (strcmp(args[cur_arg], "binary") == 0 || strcmp(args[cur_arg], "rbinary") == 0) {
2770 if (proto == TCPCHK_RULES_HTTP_CHK)
2771 goto bad_http_kw;
2772 if (type != TCPCHK_EXPECT_UNDEF) {
2773 memprintf(errmsg, "only on pattern expected");
2774 goto error;
2775 }
2776 type = ((*(args[cur_arg]) == 'b') ? TCPCHK_EXPECT_BINARY : TCPCHK_EXPECT_BINARY_REGEX);
2777
2778 if (!*(args[cur_arg+1])) {
2779 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2780 goto error;
2781 }
2782 cur_arg++;
2783 pattern = args[cur_arg];
2784 }
2785 else if (strcmp(args[cur_arg], "string-lf") == 0 || strcmp(args[cur_arg], "binary-lf") == 0) {
2786 if (type != TCPCHK_EXPECT_UNDEF) {
2787 memprintf(errmsg, "only on pattern expected");
2788 goto error;
2789 }
2790 if (proto != TCPCHK_RULES_HTTP_CHK)
2791 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_STRING_LF : TCPCHK_EXPECT_BINARY_LF);
2792 else {
2793 if (*(args[cur_arg]) != 's')
2794 goto bad_http_kw;
2795 type = TCPCHK_EXPECT_HTTP_BODY_LF;
2796 }
2797
2798 if (!*(args[cur_arg+1])) {
2799 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2800 goto error;
2801 }
2802 cur_arg++;
2803 pattern = args[cur_arg];
2804 }
2805 else if (strcmp(args[cur_arg], "status") == 0 || strcmp(args[cur_arg], "rstatus") == 0) {
2806 if (proto != TCPCHK_RULES_HTTP_CHK)
2807 goto bad_tcp_kw;
2808 if (type != TCPCHK_EXPECT_UNDEF) {
2809 memprintf(errmsg, "only on pattern expected");
2810 goto error;
2811 }
2812 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_HTTP_STATUS : TCPCHK_EXPECT_HTTP_STATUS_REGEX);
2813
2814 if (!*(args[cur_arg+1])) {
2815 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2816 goto error;
2817 }
2818 cur_arg++;
2819 pattern = args[cur_arg];
2820 }
2821 else if (strcmp(args[cur_arg], "custom") == 0) {
2822 if (in_pattern) {
2823 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2824 goto error;
2825 }
2826 if (type != TCPCHK_EXPECT_UNDEF) {
2827 memprintf(errmsg, "only on pattern expected");
2828 goto error;
2829 }
2830 type = TCPCHK_EXPECT_CUSTOM;
2831 }
2832 else if (strcmp(args[cur_arg], "hdr") == 0 || strcmp(args[cur_arg], "fhdr") == 0) {
2833 int orig_arg = cur_arg;
2834
2835 if (proto != TCPCHK_RULES_HTTP_CHK)
2836 goto bad_tcp_kw;
2837 if (type != TCPCHK_EXPECT_UNDEF) {
2838 memprintf(errmsg, "only on pattern expected");
2839 goto error;
2840 }
2841 type = TCPCHK_EXPECT_HTTP_HEADER;
2842
2843 if (strcmp(args[cur_arg], "fhdr") == 0)
2844 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_FULL;
2845
2846 /* Parse the name pattern, mandatory */
2847 if (!*(args[cur_arg+1]) || !*(args[cur_arg+2]) ||
2848 (strcmp(args[cur_arg+1], "name") != 0 && strcmp(args[cur_arg+1], "name-lf") != 0)) {
2849 memprintf(errmsg, "'%s' expects at the name keyword as first argument followed by a pattern",
2850 args[orig_arg]);
2851 goto error;
2852 }
2853
2854 if (strcmp(args[cur_arg+1], "name-lf") == 0)
2855 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_FMT;
2856
2857 cur_arg += 2;
2858 if (strcmp(args[cur_arg], "-m") == 0) {
2859 if (!*(args[cur_arg+1])) {
2860 memprintf(errmsg, "'%s' : '%s' expects at a matching pattern ('str', 'beg', 'end', 'sub' or 'reg')",
2861 args[orig_arg], args[cur_arg]);
2862 goto error;
2863 }
2864 if (strcmp(args[cur_arg+1], "str") == 0)
2865 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_STR;
2866 else if (strcmp(args[cur_arg+1], "beg") == 0)
2867 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_BEG;
2868 else if (strcmp(args[cur_arg+1], "end") == 0)
2869 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_END;
2870 else if (strcmp(args[cur_arg+1], "sub") == 0)
2871 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_SUB;
2872 else if (strcmp(args[cur_arg+1], "reg") == 0) {
2873 if (flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
2874 memprintf(errmsg, "'%s': log-format string is not supported with a regex matching method",
2875 args[orig_arg]);
2876 goto error;
2877 }
2878 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_REG;
2879 }
2880 else {
2881 memprintf(errmsg, "'%s' : '%s' only supports 'str', 'beg', 'end', 'sub' or 'reg' (got '%s')",
2882 args[orig_arg], args[cur_arg], args[cur_arg+1]);
2883 goto error;
2884 }
2885 cur_arg += 2;
2886 }
2887 else
2888 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_STR;
2889 npat = args[cur_arg];
2890
2891 if (!*(args[cur_arg+1]) ||
2892 (strcmp(args[cur_arg+1], "value") != 0 && strcmp(args[cur_arg+1], "value-lf") != 0)) {
2893 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_NONE;
2894 goto next;
2895 }
2896 if (strcmp(args[cur_arg+1], "value-lf") == 0)
2897 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_FMT;
2898
2899 /* Parse the value pattern, optional */
2900 if (strcmp(args[cur_arg+2], "-m") == 0) {
2901 cur_arg += 2;
2902 if (!*(args[cur_arg+1])) {
2903 memprintf(errmsg, "'%s' : '%s' expects at a matching pattern ('str', 'beg', 'end', 'sub' or 'reg')",
2904 args[orig_arg], args[cur_arg]);
2905 goto error;
2906 }
2907 if (strcmp(args[cur_arg+1], "str") == 0)
2908 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_STR;
2909 else if (strcmp(args[cur_arg+1], "beg") == 0)
2910 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_BEG;
2911 else if (strcmp(args[cur_arg+1], "end") == 0)
2912 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_END;
2913 else if (strcmp(args[cur_arg+1], "sub") == 0)
2914 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_SUB;
2915 else if (strcmp(args[cur_arg+1], "reg") == 0) {
2916 if (flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
2917 memprintf(errmsg, "'%s': log-format string is not supported with a regex matching method",
2918 args[orig_arg]);
2919 goto error;
2920 }
2921 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_REG;
2922 }
2923 else {
2924 memprintf(errmsg, "'%s' : '%s' only supports 'str', 'beg', 'end', 'sub' or 'reg' (got '%s')",
2925 args[orig_arg], args[cur_arg], args[cur_arg+1]);
2926 goto error;
2927 }
2928 }
2929 else
2930 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_STR;
2931
2932 if (!*(args[cur_arg+2])) {
2933 memprintf(errmsg, "'%s' expect a pattern with the value keyword", args[orig_arg]);
2934 goto error;
2935 }
2936 vpat = args[cur_arg+2];
2937 cur_arg += 2;
2938 }
2939 else if (strcmp(args[cur_arg], "comment") == 0) {
2940 if (in_pattern) {
2941 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2942 goto error;
2943 }
2944 if (!*(args[cur_arg+1])) {
2945 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
2946 goto error;
2947 }
2948 cur_arg++;
2949 free(comment);
2950 comment = strdup(args[cur_arg]);
2951 if (!comment) {
2952 memprintf(errmsg, "out of memory");
2953 goto error;
2954 }
2955 }
2956 else if (strcmp(args[cur_arg], "on-success") == 0) {
2957 if (in_pattern) {
2958 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2959 goto error;
2960 }
2961 if (!*(args[cur_arg+1])) {
2962 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
2963 goto error;
2964 }
2965 cur_arg++;
2966 on_success_msg = args[cur_arg];
2967 }
2968 else if (strcmp(args[cur_arg], "on-error") == 0) {
2969 if (in_pattern) {
2970 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2971 goto error;
2972 }
2973 if (!*(args[cur_arg+1])) {
2974 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
2975 goto error;
2976 }
2977 cur_arg++;
2978 on_error_msg = args[cur_arg];
2979 }
2980 else if (strcmp(args[cur_arg], "ok-status") == 0) {
2981 if (in_pattern) {
2982 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2983 goto error;
2984 }
2985 if (!*(args[cur_arg+1])) {
2986 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
2987 goto error;
2988 }
2989 if (strcasecmp(args[cur_arg+1], "L7OK") == 0)
2990 ok_st = HCHK_STATUS_L7OKD;
2991 else if (strcasecmp(args[cur_arg+1], "L7OKC") == 0)
2992 ok_st = HCHK_STATUS_L7OKCD;
2993 else if (strcasecmp(args[cur_arg+1], "L6OK") == 0)
2994 ok_st = HCHK_STATUS_L6OK;
2995 else if (strcasecmp(args[cur_arg+1], "L4OK") == 0)
2996 ok_st = HCHK_STATUS_L4OK;
2997 else {
2998 memprintf(errmsg, "'%s' only supports 'L4OK', 'L6OK', 'L7OK' or 'L7OKC' status (got '%s').",
2999 args[cur_arg], args[cur_arg+1]);
3000 goto error;
3001 }
3002 cur_arg++;
3003 }
3004 else if (strcmp(args[cur_arg], "error-status") == 0) {
3005 if (in_pattern) {
3006 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3007 goto error;
3008 }
3009 if (!*(args[cur_arg+1])) {
3010 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
3011 goto error;
3012 }
3013 if (strcasecmp(args[cur_arg+1], "L7RSP") == 0)
3014 err_st = HCHK_STATUS_L7RSP;
3015 else if (strcasecmp(args[cur_arg+1], "L7STS") == 0)
3016 err_st = HCHK_STATUS_L7STS;
3017 else if (strcasecmp(args[cur_arg+1], "L6RSP") == 0)
3018 err_st = HCHK_STATUS_L6RSP;
3019 else if (strcasecmp(args[cur_arg+1], "L4CON") == 0)
3020 err_st = HCHK_STATUS_L4CON;
3021 else {
3022 memprintf(errmsg, "'%s' only supports 'L4CON', 'L6RSP', 'L7RSP' or 'L7STS' status (got '%s').",
3023 args[cur_arg], args[cur_arg+1]);
3024 goto error;
3025 }
3026 cur_arg++;
3027 }
3028 else if (strcmp(args[cur_arg], "status-code") == 0) {
3029 int idx = 0;
3030
3031 if (in_pattern) {
3032 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3033 goto error;
3034 }
3035 if (!*(args[cur_arg+1])) {
3036 memprintf(errmsg, "'%s' expects an expression as argument", args[cur_arg]);
3037 goto error;
3038 }
3039
3040 cur_arg++;
3041 release_sample_expr(status_expr);
3042 px->conf.args.ctx = ARGC_SRV;
3043 status_expr = sample_parse_expr((char *[]){args[cur_arg], NULL}, &idx,
3044 file, line, errmsg, &px->conf.args, NULL);
3045 if (!status_expr) {
3046 memprintf(errmsg, "error detected while parsing status-code expression : %s", *errmsg);
3047 goto error;
3048 }
3049 if (!(status_expr->fetch->val & SMP_VAL_BE_CHK_RUL)) {
3050 memprintf(errmsg, "error detected while parsing status-code expression : "
3051 " fetch method '%s' extracts information from '%s', "
3052 "none of which is available here.\n",
3053 args[cur_arg], sample_src_names(status_expr->fetch->use));
3054 goto error;
3055 }
3056 px->http_needed |= !!(status_expr->fetch->use & SMP_USE_HTTP_ANY);
3057 }
3058 else if (strcmp(args[cur_arg], "tout-status") == 0) {
3059 if (in_pattern) {
3060 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3061 goto error;
3062 }
3063 if (!*(args[cur_arg+1])) {
3064 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
3065 goto error;
3066 }
3067 if (strcasecmp(args[cur_arg+1], "L7TOUT") == 0)
3068 tout_st = HCHK_STATUS_L7TOUT;
3069 else if (strcasecmp(args[cur_arg+1], "L6TOUT") == 0)
3070 tout_st = HCHK_STATUS_L6TOUT;
3071 else if (strcasecmp(args[cur_arg+1], "L4TOUT") == 0)
3072 tout_st = HCHK_STATUS_L4TOUT;
3073 else {
3074 memprintf(errmsg, "'%s' only supports 'L4TOUT', 'L6TOUT' or 'L7TOUT' status (got '%s').",
3075 args[cur_arg], args[cur_arg+1]);
3076 goto error;
3077 }
3078 cur_arg++;
3079 }
3080 else {
3081 if (proto == TCPCHK_RULES_HTTP_CHK) {
3082 bad_http_kw:
3083 memprintf(errmsg, "'only supports min-recv, [!]string', '[!]rstring', '[!]string-lf', '[!]status', "
3084 "'[!]rstatus', [!]hdr, [!]fhdr or comment but got '%s' as argument.", args[cur_arg]);
3085 }
3086 else {
3087 bad_tcp_kw:
3088 memprintf(errmsg, "'only supports min-recv, '[!]binary', '[!]string', '[!]rstring', '[!]string-lf'"
3089 "'[!]rbinary', '[!]binary-lf' or comment but got '%s' as argument.", args[cur_arg]);
3090 }
3091 goto error;
3092 }
3093 next:
3094 cur_arg++;
3095 }
3096
3097 chk = calloc(1, sizeof(*chk));
3098 if (!chk) {
3099 memprintf(errmsg, "out of memory");
3100 goto error;
3101 }
3102 chk->action = TCPCHK_ACT_EXPECT;
3103 LIST_INIT(&chk->expect.onerror_fmt);
3104 LIST_INIT(&chk->expect.onsuccess_fmt);
3105 chk->comment = comment; comment = NULL;
3106 chk->expect.type = type;
3107 chk->expect.min_recv = min_recv;
3108 chk->expect.flags = flags | (inverse ? TCPCHK_EXPT_FL_INV : 0);
3109 chk->expect.ok_status = ok_st;
3110 chk->expect.err_status = err_st;
3111 chk->expect.tout_status = tout_st;
3112 chk->expect.status_expr = status_expr; status_expr = NULL;
3113
3114 if (on_success_msg) {
3115 px->conf.args.ctx = ARGC_SRV;
3116 if (!parse_logformat_string(on_success_msg, px, &chk->expect.onsuccess_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3117 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", on_success_msg, *errmsg);
3118 goto error;
3119 }
3120 }
3121 if (on_error_msg) {
3122 px->conf.args.ctx = ARGC_SRV;
3123 if (!parse_logformat_string(on_error_msg, px, &chk->expect.onerror_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3124 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", on_error_msg, *errmsg);
3125 goto error;
3126 }
3127 }
3128
3129 switch (chk->expect.type) {
3130 case TCPCHK_EXPECT_HTTP_STATUS: {
3131 const char *p = pattern;
3132 unsigned int c1,c2;
3133
3134 chk->expect.codes.codes = NULL;
3135 chk->expect.codes.num = 0;
3136 while (1) {
3137 c1 = c2 = read_uint(&p, pattern + strlen(pattern));
3138 if (*p == '-') {
3139 p++;
3140 c2 = read_uint(&p, pattern + strlen(pattern));
3141 }
3142 if (c1 > c2) {
3143 memprintf(errmsg, "invalid range of status codes '%s'", pattern);
3144 goto error;
3145 }
3146
3147 chk->expect.codes.num++;
3148 chk->expect.codes.codes = my_realloc2(chk->expect.codes.codes,
3149 chk->expect.codes.num * sizeof(*chk->expect.codes.codes));
3150 if (!chk->expect.codes.codes) {
3151 memprintf(errmsg, "out of memory");
3152 goto error;
3153 }
3154 chk->expect.codes.codes[chk->expect.codes.num-1][0] = c1;
3155 chk->expect.codes.codes[chk->expect.codes.num-1][1] = c2;
3156
3157 if (*p == '\0')
3158 break;
3159 if (*p != ',') {
3160 memprintf(errmsg, "invalid character '%c' in the list of status codes", *p);
3161 goto error;
3162 }
3163 p++;
3164 }
3165 break;
3166 }
3167 case TCPCHK_EXPECT_STRING:
3168 case TCPCHK_EXPECT_HTTP_BODY:
3169 chk->expect.data = ist2(strdup(pattern), strlen(pattern));
3170 if (!isttest(chk->expect.data)) {
3171 memprintf(errmsg, "out of memory");
3172 goto error;
3173 }
3174 break;
3175 case TCPCHK_EXPECT_BINARY: {
3176 int len = chk->expect.data.len;
3177
3178 if (parse_binary(pattern, &chk->expect.data.ptr, &len, errmsg) == 0) {
3179 memprintf(errmsg, "invalid binary string (%s)", *errmsg);
3180 goto error;
3181 }
3182 chk->expect.data.len = len;
3183 break;
3184 }
3185 case TCPCHK_EXPECT_STRING_REGEX:
3186 case TCPCHK_EXPECT_BINARY_REGEX:
3187 case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
3188 case TCPCHK_EXPECT_HTTP_BODY_REGEX:
3189 chk->expect.regex = regex_comp(pattern, 1, 0, errmsg);
3190 if (!chk->expect.regex)
3191 goto error;
3192 break;
3193
3194 case TCPCHK_EXPECT_STRING_LF:
3195 case TCPCHK_EXPECT_BINARY_LF:
3196 case TCPCHK_EXPECT_HTTP_BODY_LF:
3197 LIST_INIT(&chk->expect.fmt);
3198 px->conf.args.ctx = ARGC_SRV;
3199 if (!parse_logformat_string(pattern, px, &chk->expect.fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3200 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", pattern, *errmsg);
3201 goto error;
3202 }
3203 break;
3204
3205 case TCPCHK_EXPECT_HTTP_HEADER:
3206 if (!npat) {
3207 memprintf(errmsg, "unexpected error, undefined header name pattern");
3208 goto error;
3209 }
3210 if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG) {
3211 chk->expect.hdr.name_re = regex_comp(npat, 0, 0, errmsg);
3212 if (!chk->expect.hdr.name_re)
3213 goto error;
3214 }
3215 else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
3216 px->conf.args.ctx = ARGC_SRV;
3217 LIST_INIT(&chk->expect.hdr.name_fmt);
3218 if (!parse_logformat_string(npat, px, &chk->expect.hdr.name_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3219 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", npat, *errmsg);
3220 goto error;
3221 }
3222 }
3223 else {
3224 chk->expect.hdr.name = ist2(strdup(npat), strlen(npat));
3225 if (!isttest(chk->expect.hdr.name)) {
3226 memprintf(errmsg, "out of memory");
3227 goto error;
3228 }
3229 }
3230
3231 if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE) {
3232 chk->expect.hdr.value = IST_NULL;
3233 break;
3234 }
3235
3236 if (!vpat) {
3237 memprintf(errmsg, "unexpected error, undefined header value pattern");
3238 goto error;
3239 }
3240 else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG) {
3241 chk->expect.hdr.value_re = regex_comp(vpat, 1, 0, errmsg);
3242 if (!chk->expect.hdr.value_re)
3243 goto error;
3244 }
3245 else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
3246 px->conf.args.ctx = ARGC_SRV;
3247 LIST_INIT(&chk->expect.hdr.value_fmt);
3248 if (!parse_logformat_string(vpat, px, &chk->expect.hdr.value_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3249 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", npat, *errmsg);
3250 goto error;
3251 }
3252 }
3253 else {
3254 chk->expect.hdr.value = ist2(strdup(vpat), strlen(vpat));
3255 if (!isttest(chk->expect.hdr.value)) {
3256 memprintf(errmsg, "out of memory");
3257 goto error;
3258 }
3259 }
3260
3261 break;
3262 case TCPCHK_EXPECT_CUSTOM:
3263 chk->expect.custom = NULL; /* Must be defined by the caller ! */
3264 break;
3265 case TCPCHK_EXPECT_UNDEF:
3266 memprintf(errmsg, "pattern not found");
3267 goto error;
3268 }
3269
3270 /* All tcp-check expect points back to the first inverse expect rule in
3271 * a chain of one or more expect rule, potentially itself.
3272 */
3273 chk->expect.head = chk;
3274 list_for_each_entry_rev(prev_check, rules, list) {
3275 if (prev_check->action == TCPCHK_ACT_EXPECT) {
3276 if (prev_check->expect.flags & TCPCHK_EXPT_FL_INV)
3277 chk->expect.head = prev_check;
3278 continue;
3279 }
3280 if (prev_check->action != TCPCHK_ACT_COMMENT && prev_check->action != TCPCHK_ACT_ACTION_KW)
3281 break;
3282 }
3283 return chk;
3284
3285 error:
3286 free_tcpcheck(chk, 0);
3287 free(comment);
3288 release_sample_expr(status_expr);
3289 return NULL;
3290}
3291
3292/* Overwrites fields of the old http send rule with those of the new one. When
3293 * replaced, old values are freed and replaced by the new ones. New values are
3294 * not copied but transferred. At the end <new> should be empty and can be
3295 * safely released. This function never fails.
3296 */
3297void tcpcheck_overwrite_send_http_rule(struct tcpcheck_rule *old, struct tcpcheck_rule *new)
3298{
3299 struct logformat_node *lf, *lfb;
3300 struct tcpcheck_http_hdr *hdr, *bhdr;
3301
3302
3303 if (new->send.http.meth.str.area) {
3304 free(old->send.http.meth.str.area);
3305 old->send.http.meth.meth = new->send.http.meth.meth;
3306 old->send.http.meth.str.area = new->send.http.meth.str.area;
3307 old->send.http.meth.str.data = new->send.http.meth.str.data;
3308 new->send.http.meth.str = BUF_NULL;
3309 }
3310
3311 if (!(new->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) && isttest(new->send.http.uri)) {
3312 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
3313 istfree(&old->send.http.uri);
3314 else
3315 free_tcpcheck_fmt(&old->send.http.uri_fmt);
3316 old->send.http.flags &= ~TCPCHK_SND_HTTP_FL_URI_FMT;
3317 old->send.http.uri = new->send.http.uri;
3318 new->send.http.uri = IST_NULL;
3319 }
3320 else if ((new->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) && !LIST_ISEMPTY(&new->send.http.uri_fmt)) {
3321 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
3322 istfree(&old->send.http.uri);
3323 else
3324 free_tcpcheck_fmt(&old->send.http.uri_fmt);
3325 old->send.http.flags |= TCPCHK_SND_HTTP_FL_URI_FMT;
3326 LIST_INIT(&old->send.http.uri_fmt);
3327 list_for_each_entry_safe(lf, lfb, &new->send.http.uri_fmt, list) {
3328 LIST_DEL(&lf->list);
3329 LIST_ADDQ(&old->send.http.uri_fmt, &lf->list);
3330 }
3331 }
3332
3333 if (isttest(new->send.http.vsn)) {
3334 istfree(&old->send.http.vsn);
3335 old->send.http.vsn = new->send.http.vsn;
3336 new->send.http.vsn = IST_NULL;
3337 }
3338
3339 free_tcpcheck_http_hdrs(&old->send.http.hdrs);
3340 list_for_each_entry_safe(hdr, bhdr, &new->send.http.hdrs, list) {
3341 LIST_DEL(&hdr->list);
3342 LIST_ADDQ(&old->send.http.hdrs, &hdr->list);
3343 }
3344
3345 if (!(new->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) && isttest(new->send.http.body)) {
3346 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
3347 istfree(&old->send.http.body);
3348 else
3349 free_tcpcheck_fmt(&old->send.http.body_fmt);
3350 old->send.http.flags &= ~TCPCHK_SND_HTTP_FL_BODY_FMT;
3351 old->send.http.body = new->send.http.body;
3352 new->send.http.body = IST_NULL;
3353 }
3354 else if ((new->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) && !LIST_ISEMPTY(&new->send.http.body_fmt)) {
3355 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
3356 istfree(&old->send.http.body);
3357 else
3358 free_tcpcheck_fmt(&old->send.http.body_fmt);
3359 old->send.http.flags |= TCPCHK_SND_HTTP_FL_BODY_FMT;
3360 LIST_INIT(&old->send.http.body_fmt);
3361 list_for_each_entry_safe(lf, lfb, &new->send.http.body_fmt, list) {
3362 LIST_DEL(&lf->list);
3363 LIST_ADDQ(&old->send.http.body_fmt, &lf->list);
3364 }
3365 }
3366}
3367
3368/* Internal function used to add an http-check rule in a list during the config
3369 * parsing step. Depending on its type, and the previously inserted rules, a
3370 * specific action may be performed or an error may be reported. This functions
3371 * returns 1 on success and 0 on error and <errmsg> is filled with the error
3372 * message.
3373 */
3374int tcpcheck_add_http_rule(struct tcpcheck_rule *chk, struct tcpcheck_rules *rules, char **errmsg)
3375{
3376 struct tcpcheck_rule *r;
3377
3378 /* the implicit send rule coming from an "option httpchk" line must be
3379 * merged with the first explici http-check send rule, if
Ilya Shipitsin47d17182020-06-21 21:42:57 +05003380 * any. Depending on the declaration order some tests are required.
Willy Tarreau51cd5952020-06-05 12:25:38 +02003381 *
Ilya Shipitsin47d17182020-06-21 21:42:57 +05003382 * Some tests are also required for other kinds of http-check rules to be
Willy Tarreau51cd5952020-06-05 12:25:38 +02003383 * sure the ruleset remains valid.
3384 */
3385
3386 if (chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
3387 /* Tries to add an implicit http-check send rule from an "option httpchk" line.
3388 * First, the first rule is retrieved, skipping the first CONNECT, if any, and
3389 * following tests are performed :
3390 *
3391 * 1- If there is no such rule or if it is not a send rule, the implicit send
3392 * rule is pushed in front of the ruleset
3393 *
3394 * 2- If it is another implicit send rule, it is replaced with the new one.
3395 *
3396 * 3- Otherwise, it means it is an explicit send rule. In this case we merge
3397 * both, overwriting the old send rule (the explicit one) with info of the
3398 * new send rule (the implicit one).
3399 */
3400 r = get_first_tcpcheck_rule(rules);
3401 if (r && r->action == TCPCHK_ACT_CONNECT)
3402 r = get_next_tcpcheck_rule(rules, r);
3403 if (!r || r->action != TCPCHK_ACT_SEND)
3404 LIST_ADD(rules->list, &chk->list);
3405 else if (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT) {
3406 LIST_DEL(&r->list);
3407 free_tcpcheck(r, 0);
3408 LIST_ADD(rules->list, &chk->list);
3409 }
3410 else {
3411 tcpcheck_overwrite_send_http_rule(r, chk);
3412 free_tcpcheck(chk, 0);
3413 }
3414 }
3415 else {
3416 /* Tries to add an explicit http-check rule. First of all we check the typefo the
3417 * last inserted rule to be sure it is valid. Then for send rule, we try to merge it
3418 * with an existing implicit send rule, if any. At the end, if there is no error,
3419 * the rule is appended to the list.
3420 */
3421
3422 r = get_last_tcpcheck_rule(rules);
3423 if (!r || (r->action == TCPCHK_ACT_SEND && (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)))
3424 /* no error */;
3425 else if (r->action != TCPCHK_ACT_CONNECT && chk->action == TCPCHK_ACT_SEND) {
3426 memprintf(errmsg, "unable to add http-check send rule at step %d (missing connect rule).",
3427 chk->index+1);
3428 return 0;
3429 }
3430 else if (r->action != TCPCHK_ACT_SEND && r->action != TCPCHK_ACT_EXPECT && chk->action == TCPCHK_ACT_EXPECT) {
3431 memprintf(errmsg, "unable to add http-check expect rule at step %d (missing send rule).",
3432 chk->index+1);
3433 return 0;
3434 }
3435 else if (r->action != TCPCHK_ACT_EXPECT && chk->action == TCPCHK_ACT_CONNECT) {
3436 memprintf(errmsg, "unable to add http-check connect rule at step %d (missing expect rule).",
3437 chk->index+1);
3438 return 0;
3439 }
3440
3441 if (chk->action == TCPCHK_ACT_SEND) {
3442 r = get_first_tcpcheck_rule(rules);
3443 if (r && r->action == TCPCHK_ACT_SEND && (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
3444 tcpcheck_overwrite_send_http_rule(r, chk);
3445 free_tcpcheck(chk, 0);
3446 LIST_DEL(&r->list);
3447 r->send.http.flags &= ~TCPCHK_SND_HTTP_FROM_OPT;
3448 chk = r;
3449 }
3450 }
3451 LIST_ADDQ(rules->list, &chk->list);
3452 }
3453 return 1;
3454}
3455
3456/* Check tcp-check health-check configuration for the proxy <px>. */
3457static int check_proxy_tcpcheck(struct proxy *px)
3458{
3459 struct tcpcheck_rule *chk, *back;
3460 char *comment = NULL, *errmsg = NULL;
3461 enum tcpcheck_rule_type prev_action = TCPCHK_ACT_COMMENT;
3462 int ret = 0;
3463
3464 if (!(px->cap & PR_CAP_BE) || (px->options2 & PR_O2_CHK_ANY) != PR_O2_TCPCHK_CHK) {
3465 deinit_proxy_tcpcheck(px);
3466 goto out;
3467 }
3468
3469 free(px->check_command);
3470 free(px->check_path);
3471 px->check_command = px->check_path = NULL;
3472
3473 if (!px->tcpcheck_rules.list) {
3474 ha_alert("config : proxy '%s' : tcp-check configured but no ruleset defined.\n", px->id);
3475 ret |= ERR_ALERT | ERR_FATAL;
3476 goto out;
3477 }
3478
3479 /* HTTP ruleset only : */
3480 if ((px->tcpcheck_rules.flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK) {
3481 struct tcpcheck_rule *next;
3482
3483 /* move remaining implicit send rule from "option httpchk" line to the right place.
3484 * If such rule exists, it must be the first one. In this case, the rule is moved
3485 * after the first connect rule, if any. Otherwise, nothing is done.
3486 */
3487 chk = get_first_tcpcheck_rule(&px->tcpcheck_rules);
3488 if (chk && chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
3489 next = get_next_tcpcheck_rule(&px->tcpcheck_rules, chk);
3490 if (next && next->action == TCPCHK_ACT_CONNECT) {
3491 LIST_DEL(&chk->list);
3492 LIST_ADD(&next->list, &chk->list);
3493 chk->index = next->index;
3494 }
3495 }
3496
3497 /* add implicit expect rule if the last one is a send. It is inherited from previous
3498 * versions where the http expect rule was optional. Now it is possible to chained
3499 * send/expect rules but the last expect may still be implicit.
3500 */
3501 chk = get_last_tcpcheck_rule(&px->tcpcheck_rules);
3502 if (chk && chk->action == TCPCHK_ACT_SEND) {
3503 next = parse_tcpcheck_expect((char *[]){"http-check", "expect", "status", "200-399", ""},
3504 1, px, px->tcpcheck_rules.list, TCPCHK_RULES_HTTP_CHK,
3505 px->conf.file, px->conf.line, &errmsg);
3506 if (!next) {
3507 ha_alert("config : proxy '%s': unable to add implicit http-check expect rule "
3508 "(%s).\n", px->id, errmsg);
3509 free(errmsg);
3510 ret |= ERR_ALERT | ERR_FATAL;
3511 goto out;
3512 }
3513 LIST_ADDQ(px->tcpcheck_rules.list, &next->list);
3514 next->index = chk->index;
3515 }
3516 }
3517
3518 /* For all ruleset: */
3519
3520 /* If there is no connect rule preceding all send / expect rules, an
3521 * implicit one is inserted before all others.
3522 */
3523 chk = get_first_tcpcheck_rule(&px->tcpcheck_rules);
3524 if (!chk || chk->action != TCPCHK_ACT_CONNECT) {
3525 chk = calloc(1, sizeof(*chk));
3526 if (!chk) {
3527 ha_alert("config : proxy '%s': unable to add implicit tcp-check connect rule "
3528 "(out of memory).\n", px->id);
3529 ret |= ERR_ALERT | ERR_FATAL;
3530 goto out;
3531 }
3532 chk->action = TCPCHK_ACT_CONNECT;
3533 chk->connect.options = (TCPCHK_OPT_DEFAULT_CONNECT|TCPCHK_OPT_IMPLICIT);
3534 LIST_ADD(px->tcpcheck_rules.list, &chk->list);
3535 }
3536
3537 /* Remove all comment rules. To do so, when a such rule is found, the
3538 * comment is assigned to the following rule(s).
3539 */
3540 list_for_each_entry_safe(chk, back, px->tcpcheck_rules.list, list) {
3541 if (chk->action != prev_action && prev_action != TCPCHK_ACT_COMMENT) {
3542 free(comment);
3543 comment = NULL;
3544 }
3545
3546 prev_action = chk->action;
3547 switch (chk->action) {
3548 case TCPCHK_ACT_COMMENT:
3549 free(comment);
3550 comment = chk->comment;
3551 LIST_DEL(&chk->list);
3552 free(chk);
3553 break;
3554 case TCPCHK_ACT_CONNECT:
3555 if (!chk->comment && comment)
3556 chk->comment = strdup(comment);
Tim Duesterhus588b3142020-05-29 14:35:51 +02003557 /* fall through */
Willy Tarreau51cd5952020-06-05 12:25:38 +02003558 case TCPCHK_ACT_ACTION_KW:
3559 free(comment);
3560 comment = NULL;
3561 break;
3562 case TCPCHK_ACT_SEND:
3563 case TCPCHK_ACT_EXPECT:
3564 if (!chk->comment && comment)
3565 chk->comment = strdup(comment);
3566 break;
3567 }
3568 }
3569 free(comment);
3570 comment = NULL;
3571
3572 out:
3573 return ret;
3574}
3575
3576void deinit_proxy_tcpcheck(struct proxy *px)
3577{
3578 free_tcpcheck_vars(&px->tcpcheck_rules.preset_vars);
3579 px->tcpcheck_rules.flags = 0;
3580 px->tcpcheck_rules.list = NULL;
3581}
3582
3583static void deinit_tcpchecks()
3584{
3585 struct tcpcheck_ruleset *rs;
3586 struct tcpcheck_rule *r, *rb;
3587 struct ebpt_node *node, *next;
3588
3589 node = ebpt_first(&shared_tcpchecks);
3590 while (node) {
3591 next = ebpt_next(node);
3592 ebpt_delete(node);
3593 free(node->key);
3594 rs = container_of(node, typeof(*rs), node);
3595 list_for_each_entry_safe(r, rb, &rs->rules, list) {
3596 LIST_DEL(&r->list);
3597 free_tcpcheck(r, 0);
3598 }
3599 free(rs);
3600 node = next;
3601 }
3602}
3603
3604int add_tcpcheck_expect_str(struct tcpcheck_rules *rules, const char *str)
3605{
3606 struct tcpcheck_rule *tcpcheck, *prev_check;
3607 struct tcpcheck_expect *expect;
3608
3609 if ((tcpcheck = pool_alloc(pool_head_tcpcheck_rule)) == NULL)
3610 return 0;
3611 memset(tcpcheck, 0, sizeof(*tcpcheck));
3612 tcpcheck->action = TCPCHK_ACT_EXPECT;
3613
3614 expect = &tcpcheck->expect;
3615 expect->type = TCPCHK_EXPECT_STRING;
3616 LIST_INIT(&expect->onerror_fmt);
3617 LIST_INIT(&expect->onsuccess_fmt);
3618 expect->ok_status = HCHK_STATUS_L7OKD;
3619 expect->err_status = HCHK_STATUS_L7RSP;
3620 expect->tout_status = HCHK_STATUS_L7TOUT;
3621 expect->data = ist2(strdup(str), strlen(str));
3622 if (!isttest(expect->data)) {
3623 pool_free(pool_head_tcpcheck_rule, tcpcheck);
3624 return 0;
3625 }
3626
3627 /* All tcp-check expect points back to the first inverse expect rule
3628 * in a chain of one or more expect rule, potentially itself.
3629 */
3630 tcpcheck->expect.head = tcpcheck;
3631 list_for_each_entry_rev(prev_check, rules->list, list) {
3632 if (prev_check->action == TCPCHK_ACT_EXPECT) {
3633 if (prev_check->expect.flags & TCPCHK_EXPT_FL_INV)
3634 tcpcheck->expect.head = prev_check;
3635 continue;
3636 }
3637 if (prev_check->action != TCPCHK_ACT_COMMENT && prev_check->action != TCPCHK_ACT_ACTION_KW)
3638 break;
3639 }
3640 LIST_ADDQ(rules->list, &tcpcheck->list);
3641 return 1;
3642}
3643
3644int add_tcpcheck_send_strs(struct tcpcheck_rules *rules, const char * const *strs)
3645{
3646 struct tcpcheck_rule *tcpcheck;
3647 struct tcpcheck_send *send;
3648 const char *in;
3649 char *dst;
3650 int i;
3651
3652 if ((tcpcheck = pool_alloc(pool_head_tcpcheck_rule)) == NULL)
3653 return 0;
3654 memset(tcpcheck, 0, sizeof(*tcpcheck));
3655 tcpcheck->action = TCPCHK_ACT_SEND;
3656
3657 send = &tcpcheck->send;
3658 send->type = TCPCHK_SEND_STRING;
3659
3660 for (i = 0; strs[i]; i++)
3661 send->data.len += strlen(strs[i]);
3662
3663 send->data.ptr = malloc(istlen(send->data) + 1);
3664 if (!isttest(send->data)) {
3665 pool_free(pool_head_tcpcheck_rule, tcpcheck);
3666 return 0;
3667 }
3668
3669 dst = istptr(send->data);
3670 for (i = 0; strs[i]; i++)
3671 for (in = strs[i]; (*dst = *in++); dst++);
3672 *dst = 0;
3673
3674 LIST_ADDQ(rules->list, &tcpcheck->list);
3675 return 1;
3676}
3677
3678/* Parses the "tcp-check" proxy keyword */
3679static int proxy_parse_tcpcheck(char **args, int section, struct proxy *curpx,
3680 struct proxy *defpx, const char *file, int line,
3681 char **errmsg)
3682{
3683 struct tcpcheck_ruleset *rs = NULL;
3684 struct tcpcheck_rule *chk = NULL;
3685 int index, cur_arg, ret = 0;
3686
3687 if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[0], NULL))
3688 ret = 1;
3689
3690 /* Deduce the ruleset name from the proxy info */
3691 chunk_printf(&trash, "*tcp-check-%s_%s-%d",
3692 ((curpx == defpx) ? "defaults" : curpx->id),
3693 curpx->conf.file, curpx->conf.line);
3694
3695 rs = find_tcpcheck_ruleset(b_orig(&trash));
3696 if (rs == NULL) {
3697 rs = create_tcpcheck_ruleset(b_orig(&trash));
3698 if (rs == NULL) {
3699 memprintf(errmsg, "out of memory.\n");
3700 goto error;
3701 }
3702 }
3703
3704 index = 0;
3705 if (!LIST_ISEMPTY(&rs->rules)) {
3706 chk = LIST_PREV(&rs->rules, typeof(chk), list);
3707 index = chk->index + 1;
3708 }
3709
3710 cur_arg = 1;
3711 if (strcmp(args[cur_arg], "connect") == 0)
3712 chk = parse_tcpcheck_connect(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
3713 else if (strcmp(args[cur_arg], "send") == 0 || strcmp(args[cur_arg], "send-binary") == 0 ||
3714 strcmp(args[cur_arg], "send-lf") == 0 || strcmp(args[cur_arg], "send-binary-lf") == 0)
3715 chk = parse_tcpcheck_send(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
3716 else if (strcmp(args[cur_arg], "expect") == 0)
3717 chk = parse_tcpcheck_expect(args, cur_arg, curpx, &rs->rules, 0, file, line, errmsg);
3718 else if (strcmp(args[cur_arg], "comment") == 0)
3719 chk = parse_tcpcheck_comment(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
3720 else {
3721 struct action_kw *kw = action_kw_tcp_check_lookup(args[cur_arg]);
3722
3723 if (!kw) {
3724 action_kw_tcp_check_build_list(&trash);
3725 memprintf(errmsg, "'%s' only supports 'comment', 'connect', 'send', 'send-binary', 'expect'"
3726 "%s%s. but got '%s'",
3727 args[0], (*trash.area ? ", " : ""), trash.area, args[1]);
3728 goto error;
3729 }
3730 chk = parse_tcpcheck_action(args, cur_arg, curpx, &rs->rules, kw, file, line, errmsg);
3731 }
3732
3733 if (!chk) {
3734 memprintf(errmsg, "'%s %s' : %s.", args[0], args[1], *errmsg);
3735 goto error;
3736 }
3737 ret = (ret || (*errmsg != NULL)); /* Handle warning */
3738
3739 /* No error: add the tcp-check rule in the list */
3740 chk->index = index;
3741 LIST_ADDQ(&rs->rules, &chk->list);
3742
3743 if ((curpx->options2 & PR_O2_CHK_ANY) == PR_O2_TCPCHK_CHK &&
3744 (curpx->tcpcheck_rules.flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_TCP_CHK) {
3745 /* Use this ruleset if the proxy already has tcp-check enabled */
3746 curpx->tcpcheck_rules.list = &rs->rules;
3747 curpx->tcpcheck_rules.flags &= ~TCPCHK_RULES_UNUSED_TCP_RS;
3748 }
3749 else {
3750 /* mark this ruleset as unused for now */
3751 curpx->tcpcheck_rules.flags |= TCPCHK_RULES_UNUSED_TCP_RS;
3752 }
3753
3754 return ret;
3755
3756 error:
3757 free_tcpcheck(chk, 0);
3758 free_tcpcheck_ruleset(rs);
3759 return -1;
3760}
3761
3762static struct cfg_kw_list cfg_kws = {ILH, {
3763 { CFG_LISTEN, "tcp-check", proxy_parse_tcpcheck },
3764 { 0, NULL, NULL },
3765}};
3766
3767REGISTER_POST_PROXY_CHECK(check_proxy_tcpcheck);
3768REGISTER_PROXY_DEINIT(deinit_proxy_tcpcheck);
3769REGISTER_POST_DEINIT(deinit_tcpchecks);
3770INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);