blob: 7e972a1931cc1f0ff76e390ed69d06ce6218a884 [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
Christopher Faulet444b7b12021-01-18 15:47:03 +0100987 /* For a connect action we'll create a new connection. The previous one,
988 * if any should have been killed. We don't want to leave *without* a
Willy Tarreau51cd5952020-06-05 12:25:38 +0200989 * 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)
Christopher Faulet444b7b12021-01-18 15:47:03 +0100992 * 2: Wait the connection is released (handled by process_chk_conn())
993 * 3: try to get a new connection
Willy Tarreau51cd5952020-06-05 12:25:38 +0200994 */
995
Christopher Fauletb51e0372020-11-25 13:47:00 +0100996 /* Always release input and output buffer when a new connect is evaluated */
997 check_release_buf(check, &check->bi);
998 check_release_buf(check, &check->bo);
999
Christopher Faulet444b7b12021-01-18 15:47:03 +01001000 /* prepare new connection */
Christopher Faulet236c93b2020-07-02 09:19:54 +02001001 cs = cs_new(NULL, (s ? &s->obj_type : &proxy->obj_type));
Willy Tarreau51cd5952020-06-05 12:25:38 +02001002 if (!cs) {
1003 chunk_printf(&trash, "TCPCHK error allocating connection at step %d",
1004 tcpcheck_get_step_id(check, rule));
1005 if (rule->comment)
1006 chunk_appendf(&trash, " comment: '%s'", rule->comment);
1007 set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.area);
1008 ret = TCPCHK_EVAL_STOP;
1009 goto out;
1010 }
1011
Willy Tarreau51cd5952020-06-05 12:25:38 +02001012 tasklet_set_tid(check->wait_list.tasklet, tid);
1013
1014 check->cs = cs;
1015 conn = cs->conn;
1016 conn_set_owner(conn, check->sess, NULL);
1017
1018 /* Maybe there were an older connection we were waiting on */
1019 check->wait_list.events = 0;
Willy Tarreau51cd5952020-06-05 12:25:38 +02001020
1021 /* no client address */
Willy Tarreau9b7587a2020-10-15 07:32:10 +02001022 if (!sockaddr_alloc(&conn->dst, NULL, 0)) {
Willy Tarreau51cd5952020-06-05 12:25:38 +02001023 status = SF_ERR_RESOURCE;
1024 goto fail_check;
1025 }
1026
1027 /* connect to the connect rule addr if specified, otherwise the check
1028 * addr if specified on the server. otherwise, use the server addr (it
1029 * MUST exist at this step).
1030 */
1031 *conn->dst = (is_addr(&connect->addr)
1032 ? connect->addr
1033 : (is_addr(&check->addr) ? check->addr : s->addr));
1034 proto = protocol_by_family(conn->dst->ss_family);
1035
1036 port = 0;
1037 if (!port && connect->port)
1038 port = connect->port;
1039 if (!port && connect->port_expr) {
1040 struct sample *smp;
1041
1042 smp = sample_fetch_as_type(check->proxy, check->sess, NULL,
1043 SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
1044 connect->port_expr, SMP_T_SINT);
1045 if (smp)
1046 port = smp->data.u.sint;
1047 }
1048 if (!port && is_inet_addr(&connect->addr))
1049 port = get_host_port(&connect->addr);
1050 if (!port && check->port)
1051 port = check->port;
1052 if (!port && is_inet_addr(&check->addr))
1053 port = get_host_port(&check->addr);
1054 if (!port) {
1055 /* The server MUST exist here */
1056 port = s->svc_port;
1057 }
1058 set_host_port(conn->dst, port);
1059
1060 xprt = ((connect->options & TCPCHK_OPT_SSL)
1061 ? xprt_get(XPRT_SSL)
1062 : ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) ? check->xprt : xprt_get(XPRT_RAW)));
1063
1064 conn_prepare(conn, proto, xprt);
1065 cs_attach(cs, check, &check_conn_cb);
1066
Christopher Fauletf7177272020-10-02 13:41:55 +02001067 if ((connect->options & TCPCHK_OPT_SOCKS4) && s && (s->flags & SRV_F_SOCKS4_PROXY)) {
1068 conn->send_proxy_ofs = 1;
1069 conn->flags |= CO_FL_SOCKS4;
1070 }
1071 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.via_socks4 && (s->flags & SRV_F_SOCKS4_PROXY)) {
1072 conn->send_proxy_ofs = 1;
1073 conn->flags |= CO_FL_SOCKS4;
1074 }
1075
1076 if (connect->options & TCPCHK_OPT_SEND_PROXY) {
1077 conn->send_proxy_ofs = 1;
1078 conn->flags |= CO_FL_SEND_PROXY;
1079 }
1080 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.send_proxy && !(check->state & CHK_ST_AGENT)) {
1081 conn->send_proxy_ofs = 1;
1082 conn->flags |= CO_FL_SEND_PROXY;
1083 }
1084
Willy Tarreau51cd5952020-06-05 12:25:38 +02001085 status = SF_ERR_INTERNAL;
1086 next = get_next_tcpcheck_rule(check->tcpcheck_rules, rule);
1087 if (proto && proto->connect) {
1088 int flags = 0;
1089
1090 if (check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK)
1091 flags |= CONNECT_HAS_DATA;
1092 if (!next || next->action != TCPCHK_ACT_EXPECT)
1093 flags |= CONNECT_DELACK_ALWAYS;
1094 status = proto->connect(conn, flags);
1095 }
1096
1097 if (status != SF_ERR_NONE)
1098 goto fail_check;
1099
Christopher Faulet21ddc742020-07-01 15:26:14 +02001100 conn_set_private(conn);
Willy Tarreau51cd5952020-06-05 12:25:38 +02001101 conn->ctx = cs;
1102
Willy Tarreau51cd5952020-06-05 12:25:38 +02001103#ifdef USE_OPENSSL
1104 if (connect->sni)
1105 ssl_sock_set_servername(conn, connect->sni);
1106 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.sni)
1107 ssl_sock_set_servername(conn, s->check.sni);
1108
1109 if (connect->alpn)
1110 ssl_sock_set_alpn(conn, (unsigned char *)connect->alpn, connect->alpn_len);
1111 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.alpn_str)
1112 ssl_sock_set_alpn(conn, (unsigned char *)s->check.alpn_str, s->check.alpn_len);
1113#endif
Willy Tarreau51cd5952020-06-05 12:25:38 +02001114
1115 if (conn_ctrl_ready(conn) && (connect->options & TCPCHK_OPT_LINGER)) {
1116 /* Some servers don't like reset on close */
1117 fdtab[cs->conn->handle.fd].linger_risk = 0;
1118 }
1119
1120 if (conn_ctrl_ready(conn) && (conn->flags & (CO_FL_SEND_PROXY | CO_FL_SOCKS4))) {
1121 if (xprt_add_hs(conn) < 0)
1122 status = SF_ERR_RESOURCE;
1123 }
1124
Willy Tarreau8e979fa2020-07-31 08:49:31 +02001125 /* The mux may be initialized now if there isn't server attached to the
1126 * check (email alerts) or if there is a mux proto specified or if there
1127 * is no alpn.
1128 */
1129 if (!s || ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && check->mux_proto) ||
1130 connect->mux_proto || (!connect->alpn && !check->alpn_str)) {
1131 const struct mux_ops *mux_ops;
1132
1133 if (connect->mux_proto)
1134 mux_ops = connect->mux_proto->mux;
1135 else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && check->mux_proto)
1136 mux_ops = check->mux_proto->mux;
1137 else {
1138 int mode = ((check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK
1139 ? PROTO_MODE_HTTP
1140 : PROTO_MODE_TCP);
1141
1142 mux_ops = conn_get_best_mux(conn, IST_NULL, PROTO_SIDE_BE, mode);
1143 }
1144 if (mux_ops && conn_install_mux(conn, mux_ops, cs, proxy, check->sess) < 0) {
1145 status = SF_ERR_INTERNAL;
1146 goto fail_check;
1147 }
1148 }
1149
Willy Tarreau51cd5952020-06-05 12:25:38 +02001150 fail_check:
1151 /* It can return one of :
1152 * - SF_ERR_NONE if everything's OK
1153 * - SF_ERR_SRVTO if there are no more servers
1154 * - SF_ERR_SRVCL if the connection was refused by the server
1155 * - SF_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1156 * - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1157 * - SF_ERR_INTERNAL for any other purely internal errors
1158 * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
1159 * Note that we try to prevent the network stack from sending the ACK during the
1160 * connect() when a pure TCP check is used (without PROXY protocol).
1161 */
1162 switch (status) {
1163 case SF_ERR_NONE:
1164 /* we allow up to min(inter, timeout.connect) for a connection
1165 * to establish but only when timeout.check is set as it may be
1166 * to short for a full check otherwise
1167 */
1168 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1169
1170 if (proxy->timeout.check && proxy->timeout.connect) {
1171 int t_con = tick_add(now_ms, proxy->timeout.connect);
1172 t->expire = tick_first(t->expire, t_con);
1173 }
1174 break;
1175 case SF_ERR_SRVTO: /* ETIMEDOUT */
1176 case SF_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
1177 case SF_ERR_PRXCOND:
1178 case SF_ERR_RESOURCE:
1179 case SF_ERR_INTERNAL:
1180 chk_report_conn_err(check, errno, 0);
1181 ret = TCPCHK_EVAL_STOP;
1182 goto out;
1183 }
1184
1185 /* don't do anything until the connection is established */
1186 if (conn->flags & CO_FL_WAIT_XPRT) {
1187 if (conn->mux) {
1188 if (next && next->action == TCPCHK_ACT_SEND)
1189 conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
1190 else
1191 conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
1192 }
1193 ret = TCPCHK_EVAL_WAIT;
1194 goto out;
1195 }
1196
1197 out:
1198 if (conn && check->result == CHK_RES_FAILED)
1199 conn->flags |= CO_FL_ERROR;
Christopher Fauletcc554532020-12-09 19:46:38 +01001200
1201 if (ret == TCPCHK_EVAL_CONTINUE && check->proxy->timeout.check)
1202 check->task->expire = tick_add_ifset(now_ms, check->proxy->timeout.check);
1203
Willy Tarreau51cd5952020-06-05 12:25:38 +02001204 return ret;
1205}
1206
1207/* Evaluates a TCPCHK_ACT_SEND rule. Returns TCPCHK_EVAL_WAIT if outgoing data
1208 * were not fully sent, TCPCHK_EVAL_CONTINUE to evaluate the next rule or
1209 * TCPCHK_EVAL_STOP if an error occurred.
1210 */
1211enum tcpcheck_eval_ret tcpcheck_eval_send(struct check *check, struct tcpcheck_rule *rule)
1212{
1213 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1214 struct tcpcheck_send *send = &rule->send;
1215 struct conn_stream *cs = check->cs;
1216 struct connection *conn = cs_conn(cs);
1217 struct buffer *tmp = NULL;
1218 struct htx *htx = NULL;
Amaury Denoyelleaea63022020-12-22 14:08:52 +01001219 int connection_hdr = 0;
Willy Tarreau51cd5952020-06-05 12:25:38 +02001220
Christopher Fauletb51e0372020-11-25 13:47:00 +01001221 if (check->state & CHK_ST_OUT_ALLOC) {
1222 ret = TCPCHK_EVAL_WAIT;
1223 goto out;
1224 }
1225
1226 if (!check_get_buf(check, &check->bo)) {
1227 check->state |= CHK_ST_OUT_ALLOC;
1228 ret = TCPCHK_EVAL_WAIT;
1229 goto out;
1230 }
1231
Christopher Faulet6f45f032020-11-25 13:34:51 +01001232 /* Data already pending in the output buffer, send them now */
1233 if (b_data(&check->bo))
1234 goto do_send;
1235
Christopher Fauletb51e0372020-11-25 13:47:00 +01001236 /* Always release input buffer when a new send is evaluated */
1237 check_release_buf(check, &check->bi);
Willy Tarreau51cd5952020-06-05 12:25:38 +02001238
1239 switch (send->type) {
1240 case TCPCHK_SEND_STRING:
1241 case TCPCHK_SEND_BINARY:
1242 if (istlen(send->data) >= b_size(&check->bo)) {
1243 chunk_printf(&trash, "tcp-check send : string too large (%u) for buffer size (%u) at step %d",
1244 (unsigned int)istlen(send->data), (unsigned int)b_size(&check->bo),
1245 tcpcheck_get_step_id(check, rule));
1246 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1247 ret = TCPCHK_EVAL_STOP;
1248 goto out;
1249 }
1250 b_putist(&check->bo, send->data);
1251 break;
1252 case TCPCHK_SEND_STRING_LF:
1253 check->bo.data = sess_build_logline(check->sess, NULL, b_orig(&check->bo), b_size(&check->bo), &rule->send.fmt);
1254 if (!b_data(&check->bo))
1255 goto out;
1256 break;
1257 case TCPCHK_SEND_BINARY_LF: {
1258 int len = b_size(&check->bo);
1259
1260 tmp = alloc_trash_chunk();
1261 if (!tmp)
1262 goto error_lf;
1263 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &rule->send.fmt);
1264 if (!b_data(tmp))
1265 goto out;
1266 tmp->area[tmp->data] = '\0';
1267 if (parse_binary(b_orig(tmp), &check->bo.area, &len, NULL) == 0)
1268 goto error_lf;
1269 check->bo.data = len;
1270 break;
1271 }
1272 case TCPCHK_SEND_HTTP: {
1273 struct htx_sl *sl;
1274 struct ist meth, uri, vsn, clen, body;
1275 unsigned int slflags = 0;
1276
1277 tmp = alloc_trash_chunk();
1278 if (!tmp)
1279 goto error_htx;
1280
1281 meth = ((send->http.meth.meth == HTTP_METH_OTHER)
1282 ? ist2(send->http.meth.str.area, send->http.meth.str.data)
1283 : http_known_methods[send->http.meth.meth]);
1284 if (send->http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) {
1285 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &send->http.uri_fmt);
1286 uri = (b_data(tmp) ? ist2(b_orig(tmp), b_data(tmp)) : ist("/"));
1287 }
1288 else
1289 uri = (isttest(send->http.uri) ? send->http.uri : ist("/"));
1290 vsn = (isttest(send->http.vsn) ? send->http.vsn : ist("HTTP/1.0"));
1291
1292 if ((istlen(vsn) == 6 && *(vsn.ptr+5) == '2') ||
1293 (istlen(vsn) == 8 && (*(vsn.ptr+5) > '1' || (*(vsn.ptr+5) == '1' && *(vsn.ptr+7) >= '1'))))
1294 slflags |= HTX_SL_F_VER_11;
1295 slflags |= (HTX_SL_F_XFER_LEN|HTX_SL_F_CLEN);
1296 if (!isttest(send->http.body))
1297 slflags |= HTX_SL_F_BODYLESS;
1298
1299 htx = htx_from_buf(&check->bo);
1300 sl = htx_add_stline(htx, HTX_BLK_REQ_SL, slflags, meth, uri, vsn);
1301 if (!sl)
1302 goto error_htx;
1303 sl->info.req.meth = send->http.meth.meth;
1304 if (!http_update_host(htx, sl, uri))
1305 goto error_htx;
1306
1307 if (!LIST_ISEMPTY(&send->http.hdrs)) {
1308 struct tcpcheck_http_hdr *hdr;
1309 struct ist hdr_value;
1310
1311 list_for_each_entry(hdr, &send->http.hdrs, list) {
1312 chunk_reset(tmp);
1313 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &hdr->value);
1314 if (!b_data(tmp))
1315 continue;
1316 hdr_value = ist2(b_orig(tmp), b_data(tmp));
1317 if (!htx_add_header(htx, hdr->name, hdr_value))
1318 goto error_htx;
1319 if ((sl->flags & HTX_SL_F_HAS_AUTHORITY) && isteqi(hdr->name, ist("host"))) {
1320 if (!http_update_authority(htx, sl, hdr_value))
1321 goto error_htx;
1322 }
Amaury Denoyelleaea63022020-12-22 14:08:52 +01001323 if (isteqi(hdr->name, ist("connection")))
1324 connection_hdr = 1;
Willy Tarreau51cd5952020-06-05 12:25:38 +02001325 }
1326
1327 }
1328 if (check->proxy->options2 & PR_O2_CHK_SNDST) {
1329 chunk_reset(tmp);
1330 httpchk_build_status_header(check->server, tmp);
1331 if (!htx_add_header(htx, ist("X-Haproxy-Server-State"), ist2(b_orig(tmp), b_data(tmp))))
1332 goto error_htx;
1333 }
1334
1335
1336 if (send->http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) {
1337 chunk_reset(tmp);
1338 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &send->http.body_fmt);
1339 body = ist2(b_orig(tmp), b_data(tmp));
1340 }
1341 else
1342 body = send->http.body;
1343 clen = ist((!istlen(body) ? "0" : ultoa(istlen(body))));
1344
Amaury Denoyelleaea63022020-12-22 14:08:52 +01001345 if ((!connection_hdr && !htx_add_header(htx, ist("Connection"), ist("close"))) ||
Willy Tarreau51cd5952020-06-05 12:25:38 +02001346 !htx_add_header(htx, ist("Content-length"), clen))
1347 goto error_htx;
1348
1349
1350 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Faulet810df062020-07-22 16:20:34 +02001351 (istlen(body) && !htx_add_data_atonce(htx, body)))
1352 goto error_htx;
1353
1354 htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
1355 if (!htx_add_endof(htx, HTX_BLK_EOM))
Willy Tarreau51cd5952020-06-05 12:25:38 +02001356 goto error_htx;
1357
1358 htx_to_buf(htx, &check->bo);
1359 break;
1360 }
1361 case TCPCHK_SEND_UNDEF:
1362 /* Should never happen. */
1363 ret = TCPCHK_EVAL_STOP;
1364 goto out;
1365 };
1366
Christopher Faulet6f45f032020-11-25 13:34:51 +01001367 do_send:
Willy Tarreau51cd5952020-06-05 12:25:38 +02001368 if (conn->mux->snd_buf(cs, &check->bo,
1369 (IS_HTX_CONN(conn) ? (htxbuf(&check->bo))->data: b_data(&check->bo)), 0) <= 0) {
1370 if ((conn->flags & CO_FL_ERROR) || (cs->flags & CS_FL_ERROR)) {
1371 ret = TCPCHK_EVAL_STOP;
1372 goto out;
1373 }
1374 }
1375 if ((IS_HTX_CONN(conn) && !htx_is_empty(htxbuf(&check->bo))) || b_data(&check->bo)) {
1376 cs->conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
1377 ret = TCPCHK_EVAL_WAIT;
1378 goto out;
1379 }
1380
1381 out:
1382 free_trash_chunk(tmp);
Christopher Fauletb51e0372020-11-25 13:47:00 +01001383 if (!b_data(&check->bo) || ret == TCPCHK_EVAL_STOP)
1384 check_release_buf(check, &check->bo);
Willy Tarreau51cd5952020-06-05 12:25:38 +02001385 return ret;
1386
1387 error_htx:
1388 if (htx) {
1389 htx_reset(htx);
1390 htx_to_buf(htx, &check->bo);
1391 }
1392 chunk_printf(&trash, "tcp-check send : failed to build HTTP request at step %d",
1393 tcpcheck_get_step_id(check, rule));
1394 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1395 ret = TCPCHK_EVAL_STOP;
1396 goto out;
1397
1398 error_lf:
1399 chunk_printf(&trash, "tcp-check send : failed to build log-format string at step %d",
1400 tcpcheck_get_step_id(check, rule));
1401 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1402 ret = TCPCHK_EVAL_STOP;
1403 goto out;
1404
1405}
1406
1407/* Try to receive data before evaluating a tcp-check expect rule. Returns
1408 * TCPCHK_EVAL_WAIT if it is already subscribed on receive events or if nothing
1409 * was received, TCPCHK_EVAL_CONTINUE to evaluate the expect rule or
1410 * TCPCHK_EVAL_STOP if an error occurred.
1411 */
1412enum tcpcheck_eval_ret tcpcheck_eval_recv(struct check *check, struct tcpcheck_rule *rule)
1413{
1414 struct conn_stream *cs = check->cs;
1415 struct connection *conn = cs_conn(cs);
1416 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1417 size_t max, read, cur_read = 0;
1418 int is_empty;
1419 int read_poll = MAX_READ_POLL_LOOPS;
1420
1421 if (check->wait_list.events & SUB_RETRY_RECV)
1422 goto wait_more_data;
1423
1424 if (cs->flags & CS_FL_EOS)
1425 goto end_recv;
1426
Christopher Fauletb51e0372020-11-25 13:47:00 +01001427 if (check->state & CHK_ST_IN_ALLOC)
1428 goto wait_more_data;
1429
1430 if (!check_get_buf(check, &check->bi)) {
1431 check->state |= CHK_ST_IN_ALLOC;
1432 goto wait_more_data;
1433 }
1434
Willy Tarreau51cd5952020-06-05 12:25:38 +02001435 /* errors on the connection and the conn-stream were already checked */
1436
1437 /* prepare to detect if the mux needs more room */
1438 cs->flags &= ~CS_FL_WANT_ROOM;
1439
1440 while ((cs->flags & CS_FL_RCV_MORE) ||
1441 (!(conn->flags & CO_FL_ERROR) && !(cs->flags & (CS_FL_ERROR|CS_FL_EOS)))) {
1442 max = (IS_HTX_CS(cs) ? htx_free_space(htxbuf(&check->bi)) : b_room(&check->bi));
1443 read = conn->mux->rcv_buf(cs, &check->bi, max, 0);
1444 cur_read += read;
1445 if (!read ||
1446 (cs->flags & CS_FL_WANT_ROOM) ||
1447 (--read_poll <= 0) ||
1448 (read < max && read >= global.tune.recv_enough))
1449 break;
1450 }
1451
1452 end_recv:
1453 is_empty = (IS_HTX_CS(cs) ? htx_is_empty(htxbuf(&check->bi)) : !b_data(&check->bi));
1454 if (is_empty && ((conn->flags & CO_FL_ERROR) || (cs->flags & CS_FL_ERROR))) {
1455 /* Report network errors only if we got no other data. Otherwise
1456 * we'll let the upper layers decide whether the response is OK
1457 * or not. It is very common that an RST sent by the server is
1458 * reported as an error just after the last data chunk.
1459 */
1460 goto stop;
1461 }
1462 if (!cur_read) {
1463 if (!(cs->flags & (CS_FL_WANT_ROOM|CS_FL_ERROR|CS_FL_EOS))) {
1464 conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
1465 goto wait_more_data;
1466 }
1467 if (is_empty) {
1468 int status;
1469
1470 chunk_printf(&trash, "TCPCHK got an empty response at step %d",
1471 tcpcheck_get_step_id(check, rule));
1472 if (rule->comment)
1473 chunk_appendf(&trash, " comment: '%s'", rule->comment);
1474
1475 status = ((rule->expect.err_status != HCHK_STATUS_UNKNOWN) ? rule->expect.err_status : HCHK_STATUS_L7RSP);
1476 set_server_check_status(check, status, trash.area);
1477 goto stop;
1478 }
1479 }
1480
1481 out:
Christopher Fauletb51e0372020-11-25 13:47:00 +01001482 if (!b_data(&check->bi) || ret == TCPCHK_EVAL_STOP)
1483 check_release_buf(check, &check->bi);
Willy Tarreau51cd5952020-06-05 12:25:38 +02001484 return ret;
1485
1486 stop:
1487 ret = TCPCHK_EVAL_STOP;
1488 goto out;
1489
1490 wait_more_data:
1491 ret = TCPCHK_EVAL_WAIT;
1492 goto out;
1493}
1494
1495/* Evaluates an HTTP TCPCHK_ACT_EXPECT rule. If <last_read> is set , no more data
1496 * are expected. Returns TCPCHK_EVAL_WAIT to wait for more data,
1497 * TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if an
1498 * error occurred.
1499 */
1500enum tcpcheck_eval_ret tcpcheck_eval_expect_http(struct check *check, struct tcpcheck_rule *rule, int last_read)
1501{
1502 struct htx *htx = htxbuf(&check->bi);
1503 struct htx_sl *sl;
1504 struct htx_blk *blk;
1505 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1506 struct tcpcheck_expect *expect = &rule->expect;
1507 struct buffer *msg = NULL, *tmp = NULL, *nbuf = NULL, *vbuf = NULL;
1508 enum healthcheck_status status = HCHK_STATUS_L7RSP;
1509 struct ist desc = IST_NULL;
1510 int i, match, inverse;
1511
Christopher Faulet18d98902020-12-09 19:45:07 +01001512 last_read |= (!htx_free_data_space(htx) || (htx_get_tail_type(htx) == HTX_BLK_EOM));
Willy Tarreau51cd5952020-06-05 12:25:38 +02001513
1514 if (htx->flags & HTX_FL_PARSING_ERROR) {
1515 status = HCHK_STATUS_L7RSP;
1516 goto error;
1517 }
1518
1519 if (htx_is_empty(htx)) {
1520 if (last_read) {
1521 status = HCHK_STATUS_L7RSP;
1522 goto error;
1523 }
1524 goto wait_more_data;
1525 }
1526
1527 sl = http_get_stline(htx);
1528 check->code = sl->info.res.status;
1529
1530 if (check->server &&
1531 (check->server->proxy->options & PR_O_DISABLE404) &&
1532 (check->server->next_state != SRV_ST_STOPPED) &&
1533 (check->code == 404)) {
1534 /* 404 may be accepted as "stopping" only if the server was up */
1535 goto out;
1536 }
1537
1538 inverse = !!(expect->flags & TCPCHK_EXPT_FL_INV);
1539 /* Make GCC happy ; initialize match to a failure state. */
1540 match = inverse;
1541 status = expect->err_status;
1542
1543 switch (expect->type) {
1544 case TCPCHK_EXPECT_HTTP_STATUS:
1545 match = 0;
1546 for (i = 0; i < expect->codes.num; i++) {
1547 if (sl->info.res.status >= expect->codes.codes[i][0] &&
1548 sl->info.res.status <= expect->codes.codes[i][1]) {
1549 match = 1;
1550 break;
1551 }
1552 }
1553
1554 /* Set status and description in case of error */
1555 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
1556 if (LIST_ISEMPTY(&expect->onerror_fmt))
1557 desc = htx_sl_res_reason(sl);
1558 break;
1559 case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
1560 match = regex_exec2(expect->regex, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
1561
1562 /* Set status and description in case of error */
1563 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
1564 if (LIST_ISEMPTY(&expect->onerror_fmt))
1565 desc = htx_sl_res_reason(sl);
1566 break;
1567
1568 case TCPCHK_EXPECT_HTTP_HEADER: {
1569 struct http_hdr_ctx ctx;
1570 struct ist npat, vpat, value;
1571 int full = (expect->flags & (TCPCHK_EXPT_FL_HTTP_HVAL_NONE|TCPCHK_EXPT_FL_HTTP_HVAL_FULL));
1572
1573 if (expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
1574 nbuf = alloc_trash_chunk();
1575 if (!nbuf) {
1576 status = HCHK_STATUS_L7RSP;
1577 desc = ist("Failed to allocate buffer to eval log-format string");
1578 goto error;
1579 }
1580 nbuf->data = sess_build_logline(check->sess, NULL, b_orig(nbuf), b_size(nbuf), &expect->hdr.name_fmt);
1581 if (!b_data(nbuf)) {
1582 status = HCHK_STATUS_L7RSP;
1583 desc = ist("log-format string evaluated to an empty string");
1584 goto error;
1585 }
1586 npat = ist2(b_orig(nbuf), b_data(nbuf));
1587 }
1588 else if (!(expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG))
1589 npat = expect->hdr.name;
1590
1591 if (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
1592 vbuf = alloc_trash_chunk();
1593 if (!vbuf) {
1594 status = HCHK_STATUS_L7RSP;
1595 desc = ist("Failed to allocate buffer to eval log-format string");
1596 goto error;
1597 }
1598 vbuf->data = sess_build_logline(check->sess, NULL, b_orig(vbuf), b_size(vbuf), &expect->hdr.value_fmt);
1599 if (!b_data(vbuf)) {
1600 status = HCHK_STATUS_L7RSP;
1601 desc = ist("log-format string evaluated to an empty string");
1602 goto error;
1603 }
1604 vpat = ist2(b_orig(vbuf), b_data(vbuf));
1605 }
1606 else if (!(expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG))
1607 vpat = expect->hdr.value;
1608
1609 match = 0;
1610 ctx.blk = NULL;
1611 while (1) {
1612 switch (expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_TYPE) {
1613 case TCPCHK_EXPT_FL_HTTP_HNAME_STR:
1614 if (!http_find_str_header(htx, npat, &ctx, full))
1615 goto end_of_match;
1616 break;
1617 case TCPCHK_EXPT_FL_HTTP_HNAME_BEG:
1618 if (!http_find_pfx_header(htx, npat, &ctx, full))
1619 goto end_of_match;
1620 break;
1621 case TCPCHK_EXPT_FL_HTTP_HNAME_END:
1622 if (!http_find_sfx_header(htx, npat, &ctx, full))
1623 goto end_of_match;
1624 break;
1625 case TCPCHK_EXPT_FL_HTTP_HNAME_SUB:
1626 if (!http_find_sub_header(htx, npat, &ctx, full))
1627 goto end_of_match;
1628 break;
1629 case TCPCHK_EXPT_FL_HTTP_HNAME_REG:
1630 if (!http_match_header(htx, expect->hdr.name_re, &ctx, full))
1631 goto end_of_match;
1632 break;
1633 default:
1634 /* should never happen */
1635 goto end_of_match;
1636 }
1637
1638 /* A header has matched the name pattern, let's test its
1639 * value now (always defined from there). If there is no
1640 * value pattern, it is a good match.
1641 */
1642
1643 if (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE) {
1644 match = 1;
1645 goto end_of_match;
1646 }
1647
1648 value = ctx.value;
1649 switch (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_TYPE) {
1650 case TCPCHK_EXPT_FL_HTTP_HVAL_STR:
1651 if (isteq(value, vpat)) {
1652 match = 1;
1653 goto end_of_match;
1654 }
1655 break;
1656 case TCPCHK_EXPT_FL_HTTP_HVAL_BEG:
1657 if (istlen(value) < istlen(vpat))
1658 break;
1659 value = ist2(istptr(value), istlen(vpat));
1660 if (isteq(value, vpat)) {
1661 match = 1;
1662 goto end_of_match;
1663 }
1664 break;
1665 case TCPCHK_EXPT_FL_HTTP_HVAL_END:
1666 if (istlen(value) < istlen(vpat))
1667 break;
1668 value = ist2(istptr(value) + istlen(value) - istlen(vpat), istlen(vpat));
1669 if (isteq(value, vpat)) {
1670 match = 1;
1671 goto end_of_match;
1672 }
1673 break;
1674 case TCPCHK_EXPT_FL_HTTP_HVAL_SUB:
1675 if (isttest(istist(value, vpat))) {
1676 match = 1;
1677 goto end_of_match;
1678 }
1679 break;
1680 case TCPCHK_EXPT_FL_HTTP_HVAL_REG:
1681 if (regex_exec2(expect->hdr.value_re, istptr(value), istlen(value))) {
1682 match = 1;
1683 goto end_of_match;
1684 }
1685 break;
1686 }
1687 }
1688
1689 end_of_match:
1690 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
1691 if (LIST_ISEMPTY(&expect->onerror_fmt))
1692 desc = htx_sl_res_reason(sl);
1693 break;
1694 }
1695
1696 case TCPCHK_EXPECT_HTTP_BODY:
1697 case TCPCHK_EXPECT_HTTP_BODY_REGEX:
1698 case TCPCHK_EXPECT_HTTP_BODY_LF:
1699 match = 0;
1700 chunk_reset(&trash);
1701 for (blk = htx_get_head_blk(htx); blk; blk = htx_get_next_blk(htx, blk)) {
1702 enum htx_blk_type type = htx_get_blk_type(blk);
1703
1704 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
1705 break;
1706 if (type == HTX_BLK_DATA) {
1707 if (!chunk_istcat(&trash, htx_get_blk_value(htx, blk)))
1708 break;
1709 }
1710 }
1711
1712 if (!b_data(&trash)) {
1713 if (!last_read)
1714 goto wait_more_data;
1715 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
1716 if (LIST_ISEMPTY(&expect->onerror_fmt))
1717 desc = ist("HTTP content check could not find a response body");
1718 goto error;
1719 }
1720
1721 if (expect->type == TCPCHK_EXPECT_HTTP_BODY_LF) {
1722 tmp = alloc_trash_chunk();
1723 if (!tmp) {
1724 status = HCHK_STATUS_L7RSP;
1725 desc = ist("Failed to allocate buffer to eval log-format string");
1726 goto error;
1727 }
1728 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &expect->fmt);
1729 if (!b_data(tmp)) {
1730 status = HCHK_STATUS_L7RSP;
1731 desc = ist("log-format string evaluated to an empty string");
1732 goto error;
1733 }
1734 }
1735
1736 if (!last_read &&
1737 ((expect->type == TCPCHK_EXPECT_HTTP_BODY && b_data(&trash) < istlen(expect->data)) ||
1738 ((expect->type == TCPCHK_EXPECT_HTTP_BODY_LF && b_data(&trash) < b_data(tmp))) ||
1739 (expect->min_recv > 0 && b_data(&trash) < expect->min_recv))) {
1740 ret = TCPCHK_EVAL_WAIT;
1741 goto out;
1742 }
1743
1744 if (expect->type ==TCPCHK_EXPECT_HTTP_BODY)
1745 match = my_memmem(b_orig(&trash), b_data(&trash), istptr(expect->data), istlen(expect->data)) != NULL;
1746 else if (expect->type ==TCPCHK_EXPECT_HTTP_BODY_LF)
1747 match = my_memmem(b_orig(&trash), b_data(&trash), b_orig(tmp), b_data(tmp)) != NULL;
1748 else
1749 match = regex_exec2(expect->regex, b_orig(&trash), b_data(&trash));
1750
Christopher Fauletac3b1552020-12-09 18:45:47 +01001751 /* Wait for more data on mismatch only if no minimum is defined (-1),
1752 * otherwise the absence of match is already conclusive.
1753 */
1754 if (!match && !last_read && (expect->min_recv == -1)) {
1755 ret = TCPCHK_EVAL_WAIT;
1756 goto out;
1757 }
1758
Willy Tarreau51cd5952020-06-05 12:25:38 +02001759 /* Set status and description in case of error */
1760 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
1761 if (LIST_ISEMPTY(&expect->onerror_fmt))
1762 desc = (inverse
1763 ? ist("HTTP check matched unwanted content")
1764 : ist("HTTP content check did not match"));
1765 break;
1766
1767
1768 default:
1769 /* should never happen */
1770 status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
1771 goto error;
1772 }
1773
Willy Tarreau51cd5952020-06-05 12:25:38 +02001774 if (!(match ^ inverse))
1775 goto error;
1776
1777 out:
1778 free_trash_chunk(tmp);
1779 free_trash_chunk(nbuf);
1780 free_trash_chunk(vbuf);
1781 free_trash_chunk(msg);
1782 return ret;
1783
1784 error:
1785 ret = TCPCHK_EVAL_STOP;
1786 msg = alloc_trash_chunk();
1787 if (msg)
1788 tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
1789 set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
1790 goto out;
1791
1792 wait_more_data:
1793 ret = TCPCHK_EVAL_WAIT;
1794 goto out;
1795}
1796
1797/* Evaluates a TCP TCPCHK_ACT_EXPECT rule. Returns TCPCHK_EVAL_WAIT to wait for
1798 * more data, TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP
1799 * if an error occurred.
1800 */
1801enum tcpcheck_eval_ret tcpcheck_eval_expect(struct check *check, struct tcpcheck_rule *rule, int last_read)
1802{
1803 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1804 struct tcpcheck_expect *expect = &rule->expect;
1805 struct buffer *msg = NULL, *tmp = NULL;
1806 struct ist desc = IST_NULL;
1807 enum healthcheck_status status;
1808 int match, inverse;
1809
1810 last_read |= b_full(&check->bi);
1811
1812 /* The current expect might need more data than the previous one, check again
1813 * that the minimum amount data required to match is respected.
1814 */
1815 if (!last_read) {
1816 if ((expect->type == TCPCHK_EXPECT_STRING || expect->type == TCPCHK_EXPECT_BINARY) &&
1817 (b_data(&check->bi) < istlen(expect->data))) {
1818 ret = TCPCHK_EVAL_WAIT;
1819 goto out;
1820 }
1821 if (expect->min_recv > 0 && (b_data(&check->bi) < expect->min_recv)) {
1822 ret = TCPCHK_EVAL_WAIT;
1823 goto out;
1824 }
1825 }
1826
1827 inverse = !!(expect->flags & TCPCHK_EXPT_FL_INV);
1828 /* Make GCC happy ; initialize match to a failure state. */
1829 match = inverse;
1830 status = ((expect->err_status != HCHK_STATUS_UNKNOWN) ? expect->err_status : HCHK_STATUS_L7RSP);
1831
1832 switch (expect->type) {
1833 case TCPCHK_EXPECT_STRING:
1834 case TCPCHK_EXPECT_BINARY:
1835 match = my_memmem(b_head(&check->bi), b_data(&check->bi), istptr(expect->data), istlen(expect->data)) != NULL;
1836 break;
1837 case TCPCHK_EXPECT_STRING_REGEX:
1838 match = regex_exec2(expect->regex, b_head(&check->bi), MIN(b_data(&check->bi), b_size(&check->bi)-1));
1839 break;
1840
1841 case TCPCHK_EXPECT_BINARY_REGEX:
1842 chunk_reset(&trash);
1843 dump_binary(&trash, b_head(&check->bi), b_data(&check->bi));
1844 match = regex_exec2(expect->regex, b_head(&trash), MIN(b_data(&trash), b_size(&trash)-1));
1845 break;
1846
1847 case TCPCHK_EXPECT_STRING_LF:
1848 case TCPCHK_EXPECT_BINARY_LF:
1849 match = 0;
1850 tmp = alloc_trash_chunk();
1851 if (!tmp) {
1852 status = HCHK_STATUS_L7RSP;
1853 desc = ist("Failed to allocate buffer to eval format string");
1854 goto error;
1855 }
1856 tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &expect->fmt);
1857 if (!b_data(tmp)) {
1858 status = HCHK_STATUS_L7RSP;
1859 desc = ist("log-format string evaluated to an empty string");
1860 goto error;
1861 }
1862 if (expect->type == TCPCHK_EXPECT_BINARY_LF) {
1863 int len = tmp->data;
1864 if (parse_binary(b_orig(tmp), &tmp->area, &len, NULL) == 0) {
1865 status = HCHK_STATUS_L7RSP;
1866 desc = ist("Failed to parse hexastring resulting of eval of a log-format string");
1867 goto error;
1868 }
1869 tmp->data = len;
1870 }
1871 if (b_data(&check->bi) < tmp->data) {
1872 if (!last_read) {
1873 ret = TCPCHK_EVAL_WAIT;
1874 goto out;
1875 }
1876 break;
1877 }
1878 match = my_memmem(b_head(&check->bi), b_data(&check->bi), b_orig(tmp), b_data(tmp)) != NULL;
1879 break;
1880
1881 case TCPCHK_EXPECT_CUSTOM:
1882 if (expect->custom)
1883 ret = expect->custom(check, rule, last_read);
1884 goto out;
1885 default:
1886 /* Should never happen. */
1887 ret = TCPCHK_EVAL_STOP;
1888 goto out;
1889 }
1890
1891
1892 /* Wait for more data on mismatch only if no minimum is defined (-1),
1893 * otherwise the absence of match is already conclusive.
1894 */
1895 if (!match && !last_read && (expect->min_recv == -1)) {
1896 ret = TCPCHK_EVAL_WAIT;
1897 goto out;
1898 }
1899
1900 /* Result as expected, next rule. */
1901 if (match ^ inverse)
1902 goto out;
1903
1904 error:
1905 /* From this point on, we matched something we did not want, this is an error state. */
1906 ret = TCPCHK_EVAL_STOP;
1907 msg = alloc_trash_chunk();
1908 if (msg)
1909 tcpcheck_expect_onerror_message(msg, check, rule, match, desc);
1910 set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
1911 free_trash_chunk(msg);
1912
1913 out:
1914 free_trash_chunk(tmp);
1915 return ret;
1916}
1917
1918/* Evaluates a TCPCHK_ACT_ACTION_KW rule. Returns TCPCHK_EVAL_CONTINUE to
1919 * evaluate the next rule or TCPCHK_EVAL_STOP if an error occurred. It never
1920 * waits.
1921 */
1922enum tcpcheck_eval_ret tcpcheck_eval_action_kw(struct check *check, struct tcpcheck_rule *rule)
1923{
1924 enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
1925 struct act_rule *act_rule;
1926 enum act_return act_ret;
1927
1928 act_rule =rule->action_kw.rule;
1929 act_ret = act_rule->action_ptr(act_rule, check->proxy, check->sess, NULL, 0);
1930 if (act_ret != ACT_RET_CONT) {
1931 chunk_printf(&trash, "TCPCHK ACTION unexpected result at step %d\n",
1932 tcpcheck_get_step_id(check, rule));
1933 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
1934 ret = TCPCHK_EVAL_STOP;
1935 }
1936
1937 return ret;
1938}
1939
1940/* Executes a tcp-check ruleset. Note that this is called both from the
1941 * connection's wake() callback and from the check scheduling task. It returns
1942 * 0 on normal cases, or <0 if a close() has happened on an existing connection,
1943 * presenting the risk of an fd replacement.
1944 *
1945 * Please do NOT place any return statement in this function and only leave
1946 * via the out_end_tcpcheck label after setting retcode.
1947 */
1948int tcpcheck_main(struct check *check)
1949{
1950 struct tcpcheck_rule *rule;
1951 struct conn_stream *cs = check->cs;
1952 struct connection *conn = cs_conn(cs);
1953 int must_read = 1, last_read = 0;
Christopher Faulet6f45f032020-11-25 13:34:51 +01001954 int retcode = 0;
Willy Tarreau51cd5952020-06-05 12:25:38 +02001955 enum tcpcheck_eval_ret eval_ret;
1956
1957 /* here, we know that the check is complete or that it failed */
1958 if (check->result != CHK_RES_UNKNOWN)
1959 goto out;
1960
1961 /* Note: the conn-stream and the connection may only be undefined before
1962 * the first rule evaluation (it is always a connect rule) or when the
1963 * conn-stream allocation failed on the first connect.
1964 */
1965
1966 /* 1- check for connection error, if any */
1967 if ((conn && conn->flags & CO_FL_ERROR) || (cs && cs->flags & CS_FL_ERROR))
1968 goto out_end_tcpcheck;
1969
1970 /* 2- check if we are waiting for the connection establishment. It only
1971 * happens during TCPCHK_ACT_CONNECT. */
1972 if (check->current_step && check->current_step->action == TCPCHK_ACT_CONNECT) {
Christopher Faulet444b7b12021-01-18 15:47:03 +01001973 if (!cs)
1974 rule = check->current_step;
1975 else if (cs && (check->state & CHK_ST_CLOSE_CONN)) {
1976 /* We are still waiting the connection gets closed */
1977 goto out;
1978 }
1979 else {
1980 if (conn->flags & CO_FL_WAIT_XPRT) {
1981 struct tcpcheck_rule *next;
Willy Tarreau51cd5952020-06-05 12:25:38 +02001982
Christopher Faulet444b7b12021-01-18 15:47:03 +01001983 next = get_next_tcpcheck_rule(check->tcpcheck_rules, check->current_step);
1984 if (next && next->action == TCPCHK_ACT_SEND) {
1985 if (!(check->wait_list.events & SUB_RETRY_SEND))
1986 conn->mux->subscribe(cs, SUB_RETRY_SEND, &check->wait_list);
Willy Tarreau51cd5952020-06-05 12:25:38 +02001987 goto out;
Christopher Faulet444b7b12021-01-18 15:47:03 +01001988 }
1989 else {
1990 eval_ret = tcpcheck_eval_recv(check, check->current_step);
1991 if (eval_ret == TCPCHK_EVAL_STOP)
1992 goto out_end_tcpcheck;
1993 else if (eval_ret == TCPCHK_EVAL_WAIT)
1994 goto out;
1995 last_read = ((conn->flags & CO_FL_ERROR) || (cs->flags & (CS_FL_ERROR|CS_FL_EOS)));
1996 must_read = 0;
1997 }
Willy Tarreau51cd5952020-06-05 12:25:38 +02001998 }
Christopher Fauletcc554532020-12-09 19:46:38 +01001999
Christopher Faulet444b7b12021-01-18 15:47:03 +01002000 if (check->proxy->timeout.check)
2001 check->task->expire = tick_add_ifset(now_ms, check->proxy->timeout.check);
Christopher Fauletcc554532020-12-09 19:46:38 +01002002
Christopher Faulet444b7b12021-01-18 15:47:03 +01002003 rule = LIST_NEXT(&check->current_step->list, typeof(rule), list);
2004 }
Willy Tarreau51cd5952020-06-05 12:25:38 +02002005 }
2006
Christopher Faulet6f45f032020-11-25 13:34:51 +01002007 /* 3- check if a rule must be resume. It happens if check->current_step
Willy Tarreau51cd5952020-06-05 12:25:38 +02002008 * is defined. */
2009 else if (check->current_step)
2010 rule = check->current_step;
2011
Christopher Faulet6f45f032020-11-25 13:34:51 +01002012 /* 4- It is the first evaluation. We must create a session and preset
Willy Tarreau51cd5952020-06-05 12:25:38 +02002013 * tcp-check variables */
2014 else {
2015 struct tcpcheck_var *var;
2016
2017 /* First evaluation, create a session */
2018 check->sess = session_new(&checks_fe, NULL, &check->obj_type);
2019 if (!check->sess) {
2020 chunk_printf(&trash, "TCPCHK error allocating check session");
2021 set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.area);
2022 goto out_end_tcpcheck;
2023 }
2024 vars_init(&check->vars, SCOPE_CHECK);
2025 rule = LIST_NEXT(check->tcpcheck_rules->list, typeof(rule), list);
2026
2027 /* Preset tcp-check variables */
2028 list_for_each_entry(var, &check->tcpcheck_rules->preset_vars, list) {
2029 struct sample smp;
2030
2031 memset(&smp, 0, sizeof(smp));
2032 smp_set_owner(&smp, check->proxy, check->sess, NULL, SMP_OPT_FINAL);
2033 smp.data = var->data;
2034 vars_set_by_name_ifexist(istptr(var->name), istlen(var->name), &smp);
2035 }
2036 }
2037
2038 /* Now evaluate the tcp-check rules */
2039
2040 list_for_each_entry_from(rule, check->tcpcheck_rules->list, list) {
2041 check->code = 0;
2042 switch (rule->action) {
2043 case TCPCHK_ACT_CONNECT:
Christopher Faulet444b7b12021-01-18 15:47:03 +01002044 /* Not the first connection, release it first */
2045 if (check->cs && check->current_step != rule) {
2046 check->state |= CHK_ST_CLOSE_CONN;
2047 retcode = -1;
2048 }
2049
Willy Tarreau51cd5952020-06-05 12:25:38 +02002050 check->current_step = rule;
2051
Christopher Faulet444b7b12021-01-18 15:47:03 +01002052 /* We are still waiting the connection gets closed */
2053 if (check->cs && (check->state & CHK_ST_CLOSE_CONN)) {
2054 eval_ret = TCPCHK_EVAL_WAIT;
2055 break;
Willy Tarreau51cd5952020-06-05 12:25:38 +02002056 }
Christopher Faulet444b7b12021-01-18 15:47:03 +01002057
Willy Tarreau51cd5952020-06-05 12:25:38 +02002058 eval_ret = tcpcheck_eval_connect(check, rule);
2059
2060 /* Refresh conn-stream and connection */
2061 cs = check->cs;
2062 conn = cs_conn(cs);
2063 must_read = 1; last_read = 0;
2064 break;
2065 case TCPCHK_ACT_SEND:
2066 check->current_step = rule;
2067 eval_ret = tcpcheck_eval_send(check, rule);
2068 must_read = 1;
2069 break;
2070 case TCPCHK_ACT_EXPECT:
2071 check->current_step = rule;
2072 if (must_read) {
Willy Tarreau51cd5952020-06-05 12:25:38 +02002073 eval_ret = tcpcheck_eval_recv(check, rule);
2074 if (eval_ret == TCPCHK_EVAL_STOP)
2075 goto out_end_tcpcheck;
2076 else if (eval_ret == TCPCHK_EVAL_WAIT)
2077 goto out;
2078 last_read = ((conn->flags & CO_FL_ERROR) || (cs->flags & (CS_FL_ERROR|CS_FL_EOS)));
2079 must_read = 0;
2080 }
2081
2082 eval_ret = ((check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK
2083 ? tcpcheck_eval_expect_http(check, rule, last_read)
2084 : tcpcheck_eval_expect(check, rule, last_read));
2085
2086 if (eval_ret == TCPCHK_EVAL_WAIT) {
2087 check->current_step = rule->expect.head;
2088 if (!(check->wait_list.events & SUB_RETRY_RECV))
2089 conn->mux->subscribe(cs, SUB_RETRY_RECV, &check->wait_list);
2090 }
2091 break;
2092 case TCPCHK_ACT_ACTION_KW:
2093 /* Don't update the current step */
2094 eval_ret = tcpcheck_eval_action_kw(check, rule);
2095 break;
2096 default:
2097 /* Otherwise, just go to the next one and don't update
2098 * the current step
2099 */
2100 eval_ret = TCPCHK_EVAL_CONTINUE;
2101 break;
2102 }
2103
2104 switch (eval_ret) {
2105 case TCPCHK_EVAL_CONTINUE:
2106 break;
2107 case TCPCHK_EVAL_WAIT:
2108 goto out;
2109 case TCPCHK_EVAL_STOP:
2110 goto out_end_tcpcheck;
2111 }
2112 }
2113
2114 /* All rules was evaluated */
2115 if (check->current_step) {
2116 rule = check->current_step;
2117
2118 if (rule->action == TCPCHK_ACT_EXPECT) {
2119 struct buffer *msg;
2120 enum healthcheck_status status;
2121
2122 if (check->server &&
2123 (check->server->proxy->options & PR_O_DISABLE404) &&
2124 (check->server->next_state != SRV_ST_STOPPED) &&
2125 (check->code == 404)) {
2126 set_server_check_status(check, HCHK_STATUS_L7OKCD, NULL);
2127 goto out_end_tcpcheck;
2128 }
2129
2130 msg = alloc_trash_chunk();
2131 if (msg)
2132 tcpcheck_expect_onsuccess_message(msg, check, rule, IST_NULL);
2133 status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
2134 set_server_check_status(check, status, (msg ? b_head(msg) : "(tcp-check)"));
2135 free_trash_chunk(msg);
2136 }
2137 else if (rule->action == TCPCHK_ACT_CONNECT) {
2138 const char *msg = ((rule->connect.options & TCPCHK_OPT_IMPLICIT) ? NULL : "(tcp-check)");
2139 enum healthcheck_status status = HCHK_STATUS_L4OK;
2140#ifdef USE_OPENSSL
2141 if (ssl_sock_is_ssl(conn))
2142 status = HCHK_STATUS_L6OK;
2143#endif
2144 set_server_check_status(check, status, msg);
2145 }
Christopher Fauletb4ae2472021-01-05 16:56:07 +01002146 else
2147 set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
Willy Tarreau51cd5952020-06-05 12:25:38 +02002148 }
2149 else
2150 set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
2151
2152 out_end_tcpcheck:
2153 if ((conn && conn->flags & CO_FL_ERROR) || (cs && cs->flags & CS_FL_ERROR))
2154 chk_report_conn_err(check, errno, 0);
2155
Christopher Fauletb51e0372020-11-25 13:47:00 +01002156 /* the tcpcheck is finished, release in/out buffer now */
2157 check_release_buf(check, &check->bi);
2158 check_release_buf(check, &check->bo);
2159
Willy Tarreau51cd5952020-06-05 12:25:38 +02002160 out:
2161 return retcode;
2162}
2163
2164
2165/**************************************************************************/
2166/******************* Internals to parse tcp-check rules *******************/
2167/**************************************************************************/
2168struct action_kw_list tcp_check_keywords = {
2169 .list = LIST_HEAD_INIT(tcp_check_keywords.list),
2170};
2171
2172/* Creates a tcp-check rule resulting from parsing a custom keyword. NULL is
2173 * returned on error.
2174 */
2175struct tcpcheck_rule *parse_tcpcheck_action(char **args, int cur_arg, struct proxy *px,
2176 struct list *rules, struct action_kw *kw,
2177 const char *file, int line, char **errmsg)
2178{
2179 struct tcpcheck_rule *chk = NULL;
2180 struct act_rule *actrule = NULL;
2181
2182 actrule = calloc(1, sizeof(*actrule));
2183 if (!actrule) {
2184 memprintf(errmsg, "out of memory");
2185 goto error;
2186 }
2187 actrule->kw = kw;
2188 actrule->from = ACT_F_TCP_CHK;
2189
2190 cur_arg++;
2191 if (kw->parse((const char **)args, &cur_arg, px, actrule, errmsg) == ACT_RET_PRS_ERR) {
2192 memprintf(errmsg, "'%s' : %s", kw->kw, *errmsg);
2193 goto error;
2194 }
2195
2196 chk = calloc(1, sizeof(*chk));
2197 if (!chk) {
2198 memprintf(errmsg, "out of memory");
2199 goto error;
2200 }
2201 chk->action = TCPCHK_ACT_ACTION_KW;
2202 chk->action_kw.rule = actrule;
2203 return chk;
2204
2205 error:
2206 free(actrule);
2207 return NULL;
2208}
2209
2210/* Parses and creates a tcp-check connect or an http-check connect rule. NULL is
2211 * returned on error.
2212 */
2213struct tcpcheck_rule *parse_tcpcheck_connect(char **args, int cur_arg, struct proxy *px, struct list *rules,
2214 const char *file, int line, char **errmsg)
2215{
2216 struct tcpcheck_rule *chk = NULL;
2217 struct sockaddr_storage *sk = NULL;
2218 char *comment = NULL, *sni = NULL, *alpn = NULL;
2219 struct sample_expr *port_expr = NULL;
2220 const struct mux_proto_list *mux_proto = NULL;
2221 unsigned short conn_opts = 0;
2222 long port = 0;
2223 int alpn_len = 0;
2224
2225 list_for_each_entry(chk, rules, list) {
2226 if (chk->action == TCPCHK_ACT_CONNECT)
2227 break;
2228 if (chk->action == TCPCHK_ACT_COMMENT ||
2229 chk->action == TCPCHK_ACT_ACTION_KW ||
2230 (chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)))
2231 continue;
2232
2233 memprintf(errmsg, "first step MUST also be a 'connect', "
2234 "optionally preceded by a 'set-var', an 'unset-var' or a 'comment', "
2235 "when there is a 'connect' step in the tcp-check ruleset");
2236 goto error;
2237 }
2238
2239 cur_arg++;
2240 while (*(args[cur_arg])) {
2241 if (strcmp(args[cur_arg], "default") == 0)
2242 conn_opts |= TCPCHK_OPT_DEFAULT_CONNECT;
2243 else if (strcmp(args[cur_arg], "addr") == 0) {
2244 int port1, port2;
Willy Tarreau51cd5952020-06-05 12:25:38 +02002245
2246 if (!*(args[cur_arg+1])) {
2247 memprintf(errmsg, "'%s' expects <ipv4|ipv6> as argument.", args[cur_arg]);
2248 goto error;
2249 }
2250
Willy Tarreau65ec4e32020-09-16 19:17:08 +02002251 sk = str2sa_range(args[cur_arg+1], NULL, &port1, &port2, NULL, NULL,
2252 errmsg, NULL, NULL, PA_O_RESOLVE | PA_O_PORT_OK | PA_O_STREAM | PA_O_CONNECT);
Willy Tarreau51cd5952020-06-05 12:25:38 +02002253 if (!sk) {
2254 memprintf(errmsg, "'%s' : %s.", args[cur_arg], *errmsg);
2255 goto error;
2256 }
2257
Willy Tarreau51cd5952020-06-05 12:25:38 +02002258 cur_arg++;
2259 }
2260 else if (strcmp(args[cur_arg], "port") == 0) {
2261 const char *p, *end;
2262
2263 if (!*(args[cur_arg+1])) {
2264 memprintf(errmsg, "'%s' expects a port number or a sample expression as argument.", args[cur_arg]);
2265 goto error;
2266 }
2267 cur_arg++;
2268
2269 port = 0;
2270 release_sample_expr(port_expr);
2271 p = args[cur_arg]; end = p + strlen(p);
2272 port = read_uint(&p, end);
2273 if (p != end) {
2274 int idx = 0;
2275
2276 px->conf.args.ctx = ARGC_SRV;
2277 port_expr = sample_parse_expr((char *[]){args[cur_arg], NULL}, &idx,
2278 file, line, errmsg, &px->conf.args, NULL);
2279
2280 if (!port_expr) {
2281 memprintf(errmsg, "error detected while parsing port expression : %s", *errmsg);
2282 goto error;
2283 }
2284 if (!(port_expr->fetch->val & SMP_VAL_BE_CHK_RUL)) {
2285 memprintf(errmsg, "error detected while parsing port expression : "
2286 " fetch method '%s' extracts information from '%s', "
2287 "none of which is available here.\n",
2288 args[cur_arg], sample_src_names(port_expr->fetch->use));
2289 goto error;
2290 }
2291 px->http_needed |= !!(port_expr->fetch->use & SMP_USE_HTTP_ANY);
2292 }
2293 else if (port > 65535 || port < 1) {
2294 memprintf(errmsg, "expects a valid TCP port (from range 1 to 65535) or a sample expression, got %s.",
2295 args[cur_arg]);
2296 goto error;
2297 }
2298 }
2299 else if (strcmp(args[cur_arg], "proto") == 0) {
2300 if (!*(args[cur_arg+1])) {
2301 memprintf(errmsg, "'%s' expects a MUX protocol as argument.", args[cur_arg]);
2302 goto error;
2303 }
2304 mux_proto = get_mux_proto(ist2(args[cur_arg+1], strlen(args[cur_arg+1])));
2305 if (!mux_proto) {
2306 memprintf(errmsg, "'%s' : unknown MUX protocol '%s'.", args[cur_arg], args[cur_arg+1]);
2307 goto error;
2308 }
Amaury Denoyelle34ff9ac2020-11-13 12:34:58 +01002309
2310 if (strcmp(args[0], "tcp-check") == 0 && mux_proto->mode != PROTO_MODE_TCP) {
2311 memprintf(errmsg, "'%s' : invalid MUX protocol '%s' for tcp-check", args[cur_arg], args[cur_arg+1]);
2312 goto error;
2313 }
2314 else if (strcmp(args[0], "http-check") == 0 && mux_proto->mode != PROTO_MODE_HTTP) {
2315 memprintf(errmsg, "'%s' : invalid MUX protocol '%s' for http-check", args[cur_arg], args[cur_arg+1]);
2316 goto error;
2317 }
2318
Willy Tarreau51cd5952020-06-05 12:25:38 +02002319 cur_arg++;
2320 }
2321 else if (strcmp(args[cur_arg], "comment") == 0) {
2322 if (!*(args[cur_arg+1])) {
2323 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2324 goto error;
2325 }
2326 cur_arg++;
2327 free(comment);
2328 comment = strdup(args[cur_arg]);
2329 if (!comment) {
2330 memprintf(errmsg, "out of memory");
2331 goto error;
2332 }
2333 }
2334 else if (strcmp(args[cur_arg], "send-proxy") == 0)
2335 conn_opts |= TCPCHK_OPT_SEND_PROXY;
2336 else if (strcmp(args[cur_arg], "via-socks4") == 0)
2337 conn_opts |= TCPCHK_OPT_SOCKS4;
2338 else if (strcmp(args[cur_arg], "linger") == 0)
2339 conn_opts |= TCPCHK_OPT_LINGER;
2340#ifdef USE_OPENSSL
2341 else if (strcmp(args[cur_arg], "ssl") == 0) {
2342 px->options |= PR_O_TCPCHK_SSL;
2343 conn_opts |= TCPCHK_OPT_SSL;
2344 }
2345 else if (strcmp(args[cur_arg], "sni") == 0) {
2346 if (!*(args[cur_arg+1])) {
2347 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2348 goto error;
2349 }
2350 cur_arg++;
2351 free(sni);
2352 sni = strdup(args[cur_arg]);
2353 if (!sni) {
2354 memprintf(errmsg, "out of memory");
2355 goto error;
2356 }
2357 }
2358 else if (strcmp(args[cur_arg], "alpn") == 0) {
2359#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2360 free(alpn);
2361 if (ssl_sock_parse_alpn(args[cur_arg + 1], &alpn, &alpn_len, errmsg)) {
2362 memprintf(errmsg, "'%s' : %s", args[cur_arg], *errmsg);
2363 goto error;
2364 }
2365 cur_arg++;
2366#else
2367 memprintf(errmsg, "'%s' : library does not support TLS ALPN extension.", args[cur_arg]);
2368 goto error;
2369#endif
2370 }
2371#endif /* USE_OPENSSL */
2372
2373 else {
2374 memprintf(errmsg, "expects 'comment', 'port', 'addr', 'send-proxy'"
2375#ifdef USE_OPENSSL
2376 ", 'ssl', 'sni', 'alpn'"
2377#endif /* USE_OPENSSL */
2378 " or 'via-socks4', 'linger', 'default' but got '%s' as argument.",
2379 args[cur_arg]);
2380 goto error;
2381 }
2382 cur_arg++;
2383 }
2384
2385 chk = calloc(1, sizeof(*chk));
2386 if (!chk) {
2387 memprintf(errmsg, "out of memory");
2388 goto error;
2389 }
2390 chk->action = TCPCHK_ACT_CONNECT;
2391 chk->comment = comment;
2392 chk->connect.port = port;
2393 chk->connect.options = conn_opts;
2394 chk->connect.sni = sni;
2395 chk->connect.alpn = alpn;
2396 chk->connect.alpn_len= alpn_len;
2397 chk->connect.port_expr= port_expr;
2398 chk->connect.mux_proto= mux_proto;
2399 if (sk)
2400 chk->connect.addr = *sk;
2401 return chk;
2402
2403 error:
2404 free(alpn);
2405 free(sni);
2406 free(comment);
2407 release_sample_expr(port_expr);
2408 return NULL;
2409}
2410
2411/* Parses and creates a tcp-check send rule. NULL is returned on error */
2412struct tcpcheck_rule *parse_tcpcheck_send(char **args, int cur_arg, struct proxy *px, struct list *rules,
2413 const char *file, int line, char **errmsg)
2414{
2415 struct tcpcheck_rule *chk = NULL;
2416 char *comment = NULL, *data = NULL;
2417 enum tcpcheck_send_type type = TCPCHK_SEND_UNDEF;
2418
2419 if (strcmp(args[cur_arg], "send-binary-lf") == 0)
2420 type = TCPCHK_SEND_BINARY_LF;
2421 else if (strcmp(args[cur_arg], "send-binary") == 0)
2422 type = TCPCHK_SEND_BINARY;
2423 else if (strcmp(args[cur_arg], "send-lf") == 0)
2424 type = TCPCHK_SEND_STRING_LF;
2425 else if (strcmp(args[cur_arg], "send") == 0)
2426 type = TCPCHK_SEND_STRING;
2427
2428 if (!*(args[cur_arg+1])) {
2429 memprintf(errmsg, "'%s' expects a %s as argument",
2430 (type == TCPCHK_SEND_BINARY ? "binary string": "string"), args[cur_arg]);
2431 goto error;
2432 }
2433
2434 data = args[cur_arg+1];
2435
2436 cur_arg += 2;
2437 while (*(args[cur_arg])) {
2438 if (strcmp(args[cur_arg], "comment") == 0) {
2439 if (!*(args[cur_arg+1])) {
2440 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2441 goto error;
2442 }
2443 cur_arg++;
2444 free(comment);
2445 comment = strdup(args[cur_arg]);
2446 if (!comment) {
2447 memprintf(errmsg, "out of memory");
2448 goto error;
2449 }
2450 }
2451 else {
2452 memprintf(errmsg, "expects 'comment' but got '%s' as argument.",
2453 args[cur_arg]);
2454 goto error;
2455 }
2456 cur_arg++;
2457 }
2458
2459 chk = calloc(1, sizeof(*chk));
2460 if (!chk) {
2461 memprintf(errmsg, "out of memory");
2462 goto error;
2463 }
2464 chk->action = TCPCHK_ACT_SEND;
2465 chk->comment = comment;
2466 chk->send.type = type;
2467
2468 switch (chk->send.type) {
2469 case TCPCHK_SEND_STRING:
2470 chk->send.data = ist2(strdup(data), strlen(data));
2471 if (!isttest(chk->send.data)) {
2472 memprintf(errmsg, "out of memory");
2473 goto error;
2474 }
2475 break;
2476 case TCPCHK_SEND_BINARY: {
2477 int len = chk->send.data.len;
2478 if (parse_binary(data, &chk->send.data.ptr, &len, errmsg) == 0) {
2479 memprintf(errmsg, "'%s' invalid binary string (%s).\n", data, *errmsg);
2480 goto error;
2481 }
2482 chk->send.data.len = len;
2483 break;
2484 }
2485 case TCPCHK_SEND_STRING_LF:
2486 case TCPCHK_SEND_BINARY_LF:
2487 LIST_INIT(&chk->send.fmt);
2488 px->conf.args.ctx = ARGC_SRV;
2489 if (!parse_logformat_string(data, px, &chk->send.fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
2490 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", data, *errmsg);
2491 goto error;
2492 }
2493 break;
2494 case TCPCHK_SEND_HTTP:
2495 case TCPCHK_SEND_UNDEF:
2496 goto error;
2497 }
2498
2499 return chk;
2500
2501 error:
2502 free(chk);
2503 free(comment);
2504 return NULL;
2505}
2506
2507/* Parses and creates a http-check send rule. NULL is returned on error */
2508struct tcpcheck_rule *parse_tcpcheck_send_http(char **args, int cur_arg, struct proxy *px, struct list *rules,
2509 const char *file, int line, char **errmsg)
2510{
2511 struct tcpcheck_rule *chk = NULL;
2512 struct tcpcheck_http_hdr *hdr = NULL;
2513 struct http_hdr hdrs[global.tune.max_http_hdr];
2514 char *meth = NULL, *uri = NULL, *vsn = NULL;
2515 char *body = NULL, *comment = NULL;
2516 unsigned int flags = 0;
2517 int i = 0, host_hdr = -1;
2518
2519 cur_arg++;
2520 while (*(args[cur_arg])) {
2521 if (strcmp(args[cur_arg], "meth") == 0) {
2522 if (!*(args[cur_arg+1])) {
2523 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2524 goto error;
2525 }
2526 cur_arg++;
2527 meth = args[cur_arg];
2528 }
2529 else if (strcmp(args[cur_arg], "uri") == 0 || strcmp(args[cur_arg], "uri-lf") == 0) {
2530 if (!*(args[cur_arg+1])) {
2531 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2532 goto error;
2533 }
2534 flags &= ~TCPCHK_SND_HTTP_FL_URI_FMT;
2535 if (strcmp(args[cur_arg], "uri-lf") == 0)
2536 flags |= TCPCHK_SND_HTTP_FL_URI_FMT;
2537 cur_arg++;
2538 uri = args[cur_arg];
2539 }
2540 else if (strcmp(args[cur_arg], "ver") == 0) {
2541 if (!*(args[cur_arg+1])) {
2542 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2543 goto error;
2544 }
2545 cur_arg++;
2546 vsn = args[cur_arg];
2547 }
2548 else if (strcmp(args[cur_arg], "hdr") == 0) {
2549 if (!*args[cur_arg+1] || !*args[cur_arg+2]) {
2550 memprintf(errmsg, "'%s' expects <name> and <value> as arguments", args[cur_arg]);
2551 goto error;
2552 }
2553
2554 if (strcasecmp(args[cur_arg+1], "host") == 0) {
2555 if (host_hdr >= 0) {
2556 memprintf(errmsg, "'%s' header already defined (previous value is '%s')",
2557 args[cur_arg+1], istptr(hdrs[host_hdr].v));
2558 goto error;
2559 }
2560 host_hdr = i;
2561 }
Amaury Denoyelleaea63022020-12-22 14:08:52 +01002562 else if (strcasecmp(args[cur_arg+1], "content-length") == 0 ||
Willy Tarreau51cd5952020-06-05 12:25:38 +02002563 strcasecmp(args[cur_arg+1], "transfer-encoding") == 0)
2564 goto skip_hdr;
2565
2566 hdrs[i].n = ist2(args[cur_arg+1], strlen(args[cur_arg+1]));
2567 hdrs[i].v = ist2(args[cur_arg+2], strlen(args[cur_arg+2]));
2568 i++;
2569 skip_hdr:
2570 cur_arg += 2;
2571 }
2572 else if (strcmp(args[cur_arg], "body") == 0 || strcmp(args[cur_arg], "body-lf") == 0) {
2573 if (!*(args[cur_arg+1])) {
2574 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2575 goto error;
2576 }
2577 flags &= ~TCPCHK_SND_HTTP_FL_BODY_FMT;
2578 if (strcmp(args[cur_arg], "body-lf") == 0)
2579 flags |= TCPCHK_SND_HTTP_FL_BODY_FMT;
2580 cur_arg++;
2581 body = args[cur_arg];
2582 }
2583 else if (strcmp(args[cur_arg], "comment") == 0) {
2584 if (!*(args[cur_arg+1])) {
2585 memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
2586 goto error;
2587 }
2588 cur_arg++;
2589 free(comment);
2590 comment = strdup(args[cur_arg]);
2591 if (!comment) {
2592 memprintf(errmsg, "out of memory");
2593 goto error;
2594 }
2595 }
2596 else {
2597 memprintf(errmsg, "expects 'comment', 'meth', 'uri', 'uri-lf', 'ver', 'hdr', 'body' or 'body-lf'"
2598 " but got '%s' as argument.", args[cur_arg]);
2599 goto error;
2600 }
2601 cur_arg++;
2602 }
2603
2604 hdrs[i].n = hdrs[i].v = IST_NULL;
2605
2606 chk = calloc(1, sizeof(*chk));
2607 if (!chk) {
2608 memprintf(errmsg, "out of memory");
2609 goto error;
2610 }
2611 chk->action = TCPCHK_ACT_SEND;
2612 chk->comment = comment; comment = NULL;
2613 chk->send.type = TCPCHK_SEND_HTTP;
2614 chk->send.http.flags = flags;
2615 LIST_INIT(&chk->send.http.hdrs);
2616
2617 if (meth) {
2618 chk->send.http.meth.meth = find_http_meth(meth, strlen(meth));
2619 chk->send.http.meth.str.area = strdup(meth);
2620 chk->send.http.meth.str.data = strlen(meth);
2621 if (!chk->send.http.meth.str.area) {
2622 memprintf(errmsg, "out of memory");
2623 goto error;
2624 }
2625 }
2626 if (uri) {
2627 if (chk->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) {
2628 LIST_INIT(&chk->send.http.uri_fmt);
2629 px->conf.args.ctx = ARGC_SRV;
2630 if (!parse_logformat_string(uri, px, &chk->send.http.uri_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
2631 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", uri, *errmsg);
2632 goto error;
2633 }
2634 }
2635 else {
2636 chk->send.http.uri = ist2(strdup(uri), strlen(uri));
2637 if (!isttest(chk->send.http.uri)) {
2638 memprintf(errmsg, "out of memory");
2639 goto error;
2640 }
2641 }
2642 }
2643 if (vsn) {
2644 chk->send.http.vsn = ist2(strdup(vsn), strlen(vsn));
2645 if (!isttest(chk->send.http.vsn)) {
2646 memprintf(errmsg, "out of memory");
2647 goto error;
2648 }
2649 }
2650 for (i = 0; istlen(hdrs[i].n); i++) {
2651 hdr = calloc(1, sizeof(*hdr));
2652 if (!hdr) {
2653 memprintf(errmsg, "out of memory");
2654 goto error;
2655 }
2656 LIST_INIT(&hdr->value);
2657 hdr->name = istdup(hdrs[i].n);
2658 if (!isttest(hdr->name)) {
2659 memprintf(errmsg, "out of memory");
2660 goto error;
2661 }
2662
2663 ist0(hdrs[i].v);
2664 if (!parse_logformat_string(istptr(hdrs[i].v), px, &hdr->value, 0, SMP_VAL_BE_CHK_RUL, errmsg))
2665 goto error;
2666 LIST_ADDQ(&chk->send.http.hdrs, &hdr->list);
2667 hdr = NULL;
2668 }
2669
2670 if (body) {
2671 if (chk->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) {
2672 LIST_INIT(&chk->send.http.body_fmt);
2673 px->conf.args.ctx = ARGC_SRV;
2674 if (!parse_logformat_string(body, px, &chk->send.http.body_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
2675 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", body, *errmsg);
2676 goto error;
2677 }
2678 }
2679 else {
2680 chk->send.http.body = ist2(strdup(body), strlen(body));
2681 if (!isttest(chk->send.http.body)) {
2682 memprintf(errmsg, "out of memory");
2683 goto error;
2684 }
2685 }
2686 }
2687
2688 return chk;
2689
2690 error:
2691 free_tcpcheck_http_hdr(hdr);
2692 free_tcpcheck(chk, 0);
2693 free(comment);
2694 return NULL;
2695}
2696
2697/* Parses and creates a http-check comment rule. NULL is returned on error */
2698struct tcpcheck_rule *parse_tcpcheck_comment(char **args, int cur_arg, struct proxy *px, struct list *rules,
2699 const char *file, int line, char **errmsg)
2700{
2701 struct tcpcheck_rule *chk = NULL;
2702 char *comment = NULL;
2703
2704 if (!*(args[cur_arg+1])) {
2705 memprintf(errmsg, "expects a string as argument");
2706 goto error;
2707 }
2708 cur_arg++;
2709 comment = strdup(args[cur_arg]);
2710 if (!comment) {
2711 memprintf(errmsg, "out of memory");
2712 goto error;
2713 }
2714
2715 chk = calloc(1, sizeof(*chk));
2716 if (!chk) {
2717 memprintf(errmsg, "out of memory");
2718 goto error;
2719 }
2720 chk->action = TCPCHK_ACT_COMMENT;
2721 chk->comment = comment;
2722 return chk;
2723
2724 error:
2725 free(comment);
2726 return NULL;
2727}
2728
2729/* Parses and creates a tcp-check or an http-check expect rule. NULL is returned
2730 * on error. <proto> is set to the right protocol flags (covered by the
2731 * TCPCHK_RULES_PROTO_CHK mask).
2732 */
2733struct tcpcheck_rule *parse_tcpcheck_expect(char **args, int cur_arg, struct proxy *px,
2734 struct list *rules, unsigned int proto,
2735 const char *file, int line, char **errmsg)
2736{
2737 struct tcpcheck_rule *prev_check, *chk = NULL;
2738 struct sample_expr *status_expr = NULL;
2739 char *on_success_msg, *on_error_msg, *comment, *pattern, *npat, *vpat;
2740 enum tcpcheck_expect_type type = TCPCHK_EXPECT_UNDEF;
2741 enum healthcheck_status ok_st = HCHK_STATUS_UNKNOWN;
2742 enum healthcheck_status err_st = HCHK_STATUS_UNKNOWN;
2743 enum healthcheck_status tout_st = HCHK_STATUS_UNKNOWN;
2744 unsigned int flags = 0;
2745 long min_recv = -1;
2746 int inverse = 0;
2747
2748 on_success_msg = on_error_msg = comment = pattern = npat = vpat = NULL;
2749 if (!*(args[cur_arg+1])) {
2750 memprintf(errmsg, "expects at least a matching pattern as arguments");
2751 goto error;
2752 }
2753
2754 cur_arg++;
2755 while (*(args[cur_arg])) {
2756 int in_pattern = 0;
2757
2758 rescan:
2759 if (strcmp(args[cur_arg], "min-recv") == 0) {
2760 if (in_pattern) {
2761 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2762 goto error;
2763 }
2764 if (!*(args[cur_arg+1])) {
2765 memprintf(errmsg, "'%s' expects a integer as argument", args[cur_arg]);
2766 goto error;
2767 }
Christopher Faulet7151a122020-11-25 17:20:57 +01002768 /* Use an signed integer here because of bufsize */
Willy Tarreau51cd5952020-06-05 12:25:38 +02002769 cur_arg++;
2770 min_recv = atol(args[cur_arg]);
2771 if (min_recv < -1 || min_recv > INT_MAX) {
2772 memprintf(errmsg, "'%s' expects -1 or an integer from 0 to INT_MAX" , args[cur_arg-1]);
2773 goto error;
2774 }
2775 }
2776 else if (*(args[cur_arg]) == '!') {
2777 in_pattern = 1;
2778 while (*(args[cur_arg]) == '!') {
2779 inverse = !inverse;
2780 args[cur_arg]++;
2781 }
2782 if (!*(args[cur_arg]))
2783 cur_arg++;
2784 goto rescan;
2785 }
2786 else if (strcmp(args[cur_arg], "string") == 0 || strcmp(args[cur_arg], "rstring") == 0) {
2787 if (type != TCPCHK_EXPECT_UNDEF) {
2788 memprintf(errmsg, "only on pattern expected");
2789 goto error;
2790 }
2791 if (proto != TCPCHK_RULES_HTTP_CHK)
2792 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_STRING : TCPCHK_EXPECT_STRING_REGEX);
2793 else
2794 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_HTTP_BODY : TCPCHK_EXPECT_HTTP_BODY_REGEX);
2795
2796 if (!*(args[cur_arg+1])) {
2797 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2798 goto error;
2799 }
2800 cur_arg++;
2801 pattern = args[cur_arg];
2802 }
2803 else if (strcmp(args[cur_arg], "binary") == 0 || strcmp(args[cur_arg], "rbinary") == 0) {
2804 if (proto == TCPCHK_RULES_HTTP_CHK)
2805 goto bad_http_kw;
2806 if (type != TCPCHK_EXPECT_UNDEF) {
2807 memprintf(errmsg, "only on pattern expected");
2808 goto error;
2809 }
2810 type = ((*(args[cur_arg]) == 'b') ? TCPCHK_EXPECT_BINARY : TCPCHK_EXPECT_BINARY_REGEX);
2811
2812 if (!*(args[cur_arg+1])) {
2813 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2814 goto error;
2815 }
2816 cur_arg++;
2817 pattern = args[cur_arg];
2818 }
2819 else if (strcmp(args[cur_arg], "string-lf") == 0 || strcmp(args[cur_arg], "binary-lf") == 0) {
2820 if (type != TCPCHK_EXPECT_UNDEF) {
2821 memprintf(errmsg, "only on pattern expected");
2822 goto error;
2823 }
2824 if (proto != TCPCHK_RULES_HTTP_CHK)
2825 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_STRING_LF : TCPCHK_EXPECT_BINARY_LF);
2826 else {
2827 if (*(args[cur_arg]) != 's')
2828 goto bad_http_kw;
2829 type = TCPCHK_EXPECT_HTTP_BODY_LF;
2830 }
2831
2832 if (!*(args[cur_arg+1])) {
2833 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2834 goto error;
2835 }
2836 cur_arg++;
2837 pattern = args[cur_arg];
2838 }
2839 else if (strcmp(args[cur_arg], "status") == 0 || strcmp(args[cur_arg], "rstatus") == 0) {
2840 if (proto != TCPCHK_RULES_HTTP_CHK)
2841 goto bad_tcp_kw;
2842 if (type != TCPCHK_EXPECT_UNDEF) {
2843 memprintf(errmsg, "only on pattern expected");
2844 goto error;
2845 }
2846 type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_HTTP_STATUS : TCPCHK_EXPECT_HTTP_STATUS_REGEX);
2847
2848 if (!*(args[cur_arg+1])) {
2849 memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
2850 goto error;
2851 }
2852 cur_arg++;
2853 pattern = args[cur_arg];
2854 }
2855 else if (strcmp(args[cur_arg], "custom") == 0) {
2856 if (in_pattern) {
2857 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2858 goto error;
2859 }
2860 if (type != TCPCHK_EXPECT_UNDEF) {
2861 memprintf(errmsg, "only on pattern expected");
2862 goto error;
2863 }
2864 type = TCPCHK_EXPECT_CUSTOM;
2865 }
2866 else if (strcmp(args[cur_arg], "hdr") == 0 || strcmp(args[cur_arg], "fhdr") == 0) {
2867 int orig_arg = cur_arg;
2868
2869 if (proto != TCPCHK_RULES_HTTP_CHK)
2870 goto bad_tcp_kw;
2871 if (type != TCPCHK_EXPECT_UNDEF) {
2872 memprintf(errmsg, "only on pattern expected");
2873 goto error;
2874 }
2875 type = TCPCHK_EXPECT_HTTP_HEADER;
2876
2877 if (strcmp(args[cur_arg], "fhdr") == 0)
2878 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_FULL;
2879
2880 /* Parse the name pattern, mandatory */
2881 if (!*(args[cur_arg+1]) || !*(args[cur_arg+2]) ||
2882 (strcmp(args[cur_arg+1], "name") != 0 && strcmp(args[cur_arg+1], "name-lf") != 0)) {
2883 memprintf(errmsg, "'%s' expects at the name keyword as first argument followed by a pattern",
2884 args[orig_arg]);
2885 goto error;
2886 }
2887
2888 if (strcmp(args[cur_arg+1], "name-lf") == 0)
2889 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_FMT;
2890
2891 cur_arg += 2;
2892 if (strcmp(args[cur_arg], "-m") == 0) {
2893 if (!*(args[cur_arg+1])) {
2894 memprintf(errmsg, "'%s' : '%s' expects at a matching pattern ('str', 'beg', 'end', 'sub' or 'reg')",
2895 args[orig_arg], args[cur_arg]);
2896 goto error;
2897 }
2898 if (strcmp(args[cur_arg+1], "str") == 0)
2899 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_STR;
2900 else if (strcmp(args[cur_arg+1], "beg") == 0)
2901 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_BEG;
2902 else if (strcmp(args[cur_arg+1], "end") == 0)
2903 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_END;
2904 else if (strcmp(args[cur_arg+1], "sub") == 0)
2905 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_SUB;
2906 else if (strcmp(args[cur_arg+1], "reg") == 0) {
2907 if (flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
2908 memprintf(errmsg, "'%s': log-format string is not supported with a regex matching method",
2909 args[orig_arg]);
2910 goto error;
2911 }
2912 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_REG;
2913 }
2914 else {
2915 memprintf(errmsg, "'%s' : '%s' only supports 'str', 'beg', 'end', 'sub' or 'reg' (got '%s')",
2916 args[orig_arg], args[cur_arg], args[cur_arg+1]);
2917 goto error;
2918 }
2919 cur_arg += 2;
2920 }
2921 else
2922 flags |= TCPCHK_EXPT_FL_HTTP_HNAME_STR;
2923 npat = args[cur_arg];
2924
2925 if (!*(args[cur_arg+1]) ||
2926 (strcmp(args[cur_arg+1], "value") != 0 && strcmp(args[cur_arg+1], "value-lf") != 0)) {
2927 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_NONE;
2928 goto next;
2929 }
2930 if (strcmp(args[cur_arg+1], "value-lf") == 0)
2931 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_FMT;
2932
2933 /* Parse the value pattern, optional */
2934 if (strcmp(args[cur_arg+2], "-m") == 0) {
2935 cur_arg += 2;
2936 if (!*(args[cur_arg+1])) {
2937 memprintf(errmsg, "'%s' : '%s' expects at a matching pattern ('str', 'beg', 'end', 'sub' or 'reg')",
2938 args[orig_arg], args[cur_arg]);
2939 goto error;
2940 }
2941 if (strcmp(args[cur_arg+1], "str") == 0)
2942 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_STR;
2943 else if (strcmp(args[cur_arg+1], "beg") == 0)
2944 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_BEG;
2945 else if (strcmp(args[cur_arg+1], "end") == 0)
2946 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_END;
2947 else if (strcmp(args[cur_arg+1], "sub") == 0)
2948 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_SUB;
2949 else if (strcmp(args[cur_arg+1], "reg") == 0) {
2950 if (flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
2951 memprintf(errmsg, "'%s': log-format string is not supported with a regex matching method",
2952 args[orig_arg]);
2953 goto error;
2954 }
2955 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_REG;
2956 }
2957 else {
2958 memprintf(errmsg, "'%s' : '%s' only supports 'str', 'beg', 'end', 'sub' or 'reg' (got '%s')",
2959 args[orig_arg], args[cur_arg], args[cur_arg+1]);
2960 goto error;
2961 }
2962 }
2963 else
2964 flags |= TCPCHK_EXPT_FL_HTTP_HVAL_STR;
2965
2966 if (!*(args[cur_arg+2])) {
2967 memprintf(errmsg, "'%s' expect a pattern with the value keyword", args[orig_arg]);
2968 goto error;
2969 }
2970 vpat = args[cur_arg+2];
2971 cur_arg += 2;
2972 }
2973 else if (strcmp(args[cur_arg], "comment") == 0) {
2974 if (in_pattern) {
2975 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2976 goto error;
2977 }
2978 if (!*(args[cur_arg+1])) {
2979 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
2980 goto error;
2981 }
2982 cur_arg++;
2983 free(comment);
2984 comment = strdup(args[cur_arg]);
2985 if (!comment) {
2986 memprintf(errmsg, "out of memory");
2987 goto error;
2988 }
2989 }
2990 else if (strcmp(args[cur_arg], "on-success") == 0) {
2991 if (in_pattern) {
2992 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
2993 goto error;
2994 }
2995 if (!*(args[cur_arg+1])) {
2996 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
2997 goto error;
2998 }
2999 cur_arg++;
3000 on_success_msg = args[cur_arg];
3001 }
3002 else if (strcmp(args[cur_arg], "on-error") == 0) {
3003 if (in_pattern) {
3004 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3005 goto error;
3006 }
3007 if (!*(args[cur_arg+1])) {
3008 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
3009 goto error;
3010 }
3011 cur_arg++;
3012 on_error_msg = args[cur_arg];
3013 }
3014 else if (strcmp(args[cur_arg], "ok-status") == 0) {
3015 if (in_pattern) {
3016 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3017 goto error;
3018 }
3019 if (!*(args[cur_arg+1])) {
3020 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
3021 goto error;
3022 }
3023 if (strcasecmp(args[cur_arg+1], "L7OK") == 0)
3024 ok_st = HCHK_STATUS_L7OKD;
3025 else if (strcasecmp(args[cur_arg+1], "L7OKC") == 0)
3026 ok_st = HCHK_STATUS_L7OKCD;
3027 else if (strcasecmp(args[cur_arg+1], "L6OK") == 0)
3028 ok_st = HCHK_STATUS_L6OK;
3029 else if (strcasecmp(args[cur_arg+1], "L4OK") == 0)
3030 ok_st = HCHK_STATUS_L4OK;
3031 else {
3032 memprintf(errmsg, "'%s' only supports 'L4OK', 'L6OK', 'L7OK' or 'L7OKC' status (got '%s').",
3033 args[cur_arg], args[cur_arg+1]);
3034 goto error;
3035 }
3036 cur_arg++;
3037 }
3038 else if (strcmp(args[cur_arg], "error-status") == 0) {
3039 if (in_pattern) {
3040 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3041 goto error;
3042 }
3043 if (!*(args[cur_arg+1])) {
3044 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
3045 goto error;
3046 }
3047 if (strcasecmp(args[cur_arg+1], "L7RSP") == 0)
3048 err_st = HCHK_STATUS_L7RSP;
3049 else if (strcasecmp(args[cur_arg+1], "L7STS") == 0)
3050 err_st = HCHK_STATUS_L7STS;
3051 else if (strcasecmp(args[cur_arg+1], "L6RSP") == 0)
3052 err_st = HCHK_STATUS_L6RSP;
3053 else if (strcasecmp(args[cur_arg+1], "L4CON") == 0)
3054 err_st = HCHK_STATUS_L4CON;
3055 else {
3056 memprintf(errmsg, "'%s' only supports 'L4CON', 'L6RSP', 'L7RSP' or 'L7STS' status (got '%s').",
3057 args[cur_arg], args[cur_arg+1]);
3058 goto error;
3059 }
3060 cur_arg++;
3061 }
3062 else if (strcmp(args[cur_arg], "status-code") == 0) {
3063 int idx = 0;
3064
3065 if (in_pattern) {
3066 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3067 goto error;
3068 }
3069 if (!*(args[cur_arg+1])) {
3070 memprintf(errmsg, "'%s' expects an expression as argument", args[cur_arg]);
3071 goto error;
3072 }
3073
3074 cur_arg++;
3075 release_sample_expr(status_expr);
3076 px->conf.args.ctx = ARGC_SRV;
3077 status_expr = sample_parse_expr((char *[]){args[cur_arg], NULL}, &idx,
3078 file, line, errmsg, &px->conf.args, NULL);
3079 if (!status_expr) {
3080 memprintf(errmsg, "error detected while parsing status-code expression : %s", *errmsg);
3081 goto error;
3082 }
3083 if (!(status_expr->fetch->val & SMP_VAL_BE_CHK_RUL)) {
3084 memprintf(errmsg, "error detected while parsing status-code expression : "
3085 " fetch method '%s' extracts information from '%s', "
3086 "none of which is available here.\n",
3087 args[cur_arg], sample_src_names(status_expr->fetch->use));
3088 goto error;
3089 }
3090 px->http_needed |= !!(status_expr->fetch->use & SMP_USE_HTTP_ANY);
3091 }
3092 else if (strcmp(args[cur_arg], "tout-status") == 0) {
3093 if (in_pattern) {
3094 memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
3095 goto error;
3096 }
3097 if (!*(args[cur_arg+1])) {
3098 memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
3099 goto error;
3100 }
3101 if (strcasecmp(args[cur_arg+1], "L7TOUT") == 0)
3102 tout_st = HCHK_STATUS_L7TOUT;
3103 else if (strcasecmp(args[cur_arg+1], "L6TOUT") == 0)
3104 tout_st = HCHK_STATUS_L6TOUT;
3105 else if (strcasecmp(args[cur_arg+1], "L4TOUT") == 0)
3106 tout_st = HCHK_STATUS_L4TOUT;
3107 else {
3108 memprintf(errmsg, "'%s' only supports 'L4TOUT', 'L6TOUT' or 'L7TOUT' status (got '%s').",
3109 args[cur_arg], args[cur_arg+1]);
3110 goto error;
3111 }
3112 cur_arg++;
3113 }
3114 else {
3115 if (proto == TCPCHK_RULES_HTTP_CHK) {
3116 bad_http_kw:
3117 memprintf(errmsg, "'only supports min-recv, [!]string', '[!]rstring', '[!]string-lf', '[!]status', "
3118 "'[!]rstatus', [!]hdr, [!]fhdr or comment but got '%s' as argument.", args[cur_arg]);
3119 }
3120 else {
3121 bad_tcp_kw:
3122 memprintf(errmsg, "'only supports min-recv, '[!]binary', '[!]string', '[!]rstring', '[!]string-lf'"
3123 "'[!]rbinary', '[!]binary-lf' or comment but got '%s' as argument.", args[cur_arg]);
3124 }
3125 goto error;
3126 }
3127 next:
3128 cur_arg++;
3129 }
3130
3131 chk = calloc(1, sizeof(*chk));
3132 if (!chk) {
3133 memprintf(errmsg, "out of memory");
3134 goto error;
3135 }
3136 chk->action = TCPCHK_ACT_EXPECT;
3137 LIST_INIT(&chk->expect.onerror_fmt);
3138 LIST_INIT(&chk->expect.onsuccess_fmt);
3139 chk->comment = comment; comment = NULL;
3140 chk->expect.type = type;
3141 chk->expect.min_recv = min_recv;
3142 chk->expect.flags = flags | (inverse ? TCPCHK_EXPT_FL_INV : 0);
3143 chk->expect.ok_status = ok_st;
3144 chk->expect.err_status = err_st;
3145 chk->expect.tout_status = tout_st;
3146 chk->expect.status_expr = status_expr; status_expr = NULL;
3147
3148 if (on_success_msg) {
3149 px->conf.args.ctx = ARGC_SRV;
3150 if (!parse_logformat_string(on_success_msg, px, &chk->expect.onsuccess_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3151 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", on_success_msg, *errmsg);
3152 goto error;
3153 }
3154 }
3155 if (on_error_msg) {
3156 px->conf.args.ctx = ARGC_SRV;
3157 if (!parse_logformat_string(on_error_msg, px, &chk->expect.onerror_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3158 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", on_error_msg, *errmsg);
3159 goto error;
3160 }
3161 }
3162
3163 switch (chk->expect.type) {
3164 case TCPCHK_EXPECT_HTTP_STATUS: {
3165 const char *p = pattern;
3166 unsigned int c1,c2;
3167
3168 chk->expect.codes.codes = NULL;
3169 chk->expect.codes.num = 0;
3170 while (1) {
3171 c1 = c2 = read_uint(&p, pattern + strlen(pattern));
3172 if (*p == '-') {
3173 p++;
3174 c2 = read_uint(&p, pattern + strlen(pattern));
3175 }
3176 if (c1 > c2) {
3177 memprintf(errmsg, "invalid range of status codes '%s'", pattern);
3178 goto error;
3179 }
3180
3181 chk->expect.codes.num++;
3182 chk->expect.codes.codes = my_realloc2(chk->expect.codes.codes,
3183 chk->expect.codes.num * sizeof(*chk->expect.codes.codes));
3184 if (!chk->expect.codes.codes) {
3185 memprintf(errmsg, "out of memory");
3186 goto error;
3187 }
3188 chk->expect.codes.codes[chk->expect.codes.num-1][0] = c1;
3189 chk->expect.codes.codes[chk->expect.codes.num-1][1] = c2;
3190
3191 if (*p == '\0')
3192 break;
3193 if (*p != ',') {
3194 memprintf(errmsg, "invalid character '%c' in the list of status codes", *p);
3195 goto error;
3196 }
3197 p++;
3198 }
3199 break;
3200 }
3201 case TCPCHK_EXPECT_STRING:
3202 case TCPCHK_EXPECT_HTTP_BODY:
3203 chk->expect.data = ist2(strdup(pattern), strlen(pattern));
3204 if (!isttest(chk->expect.data)) {
3205 memprintf(errmsg, "out of memory");
3206 goto error;
3207 }
3208 break;
3209 case TCPCHK_EXPECT_BINARY: {
3210 int len = chk->expect.data.len;
3211
3212 if (parse_binary(pattern, &chk->expect.data.ptr, &len, errmsg) == 0) {
3213 memprintf(errmsg, "invalid binary string (%s)", *errmsg);
3214 goto error;
3215 }
3216 chk->expect.data.len = len;
3217 break;
3218 }
3219 case TCPCHK_EXPECT_STRING_REGEX:
3220 case TCPCHK_EXPECT_BINARY_REGEX:
3221 case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
3222 case TCPCHK_EXPECT_HTTP_BODY_REGEX:
3223 chk->expect.regex = regex_comp(pattern, 1, 0, errmsg);
3224 if (!chk->expect.regex)
3225 goto error;
3226 break;
3227
3228 case TCPCHK_EXPECT_STRING_LF:
3229 case TCPCHK_EXPECT_BINARY_LF:
3230 case TCPCHK_EXPECT_HTTP_BODY_LF:
3231 LIST_INIT(&chk->expect.fmt);
3232 px->conf.args.ctx = ARGC_SRV;
3233 if (!parse_logformat_string(pattern, px, &chk->expect.fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3234 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", pattern, *errmsg);
3235 goto error;
3236 }
3237 break;
3238
3239 case TCPCHK_EXPECT_HTTP_HEADER:
3240 if (!npat) {
3241 memprintf(errmsg, "unexpected error, undefined header name pattern");
3242 goto error;
3243 }
3244 if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG) {
3245 chk->expect.hdr.name_re = regex_comp(npat, 0, 0, errmsg);
3246 if (!chk->expect.hdr.name_re)
3247 goto error;
3248 }
3249 else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
3250 px->conf.args.ctx = ARGC_SRV;
3251 LIST_INIT(&chk->expect.hdr.name_fmt);
3252 if (!parse_logformat_string(npat, px, &chk->expect.hdr.name_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3253 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", npat, *errmsg);
3254 goto error;
3255 }
3256 }
3257 else {
3258 chk->expect.hdr.name = ist2(strdup(npat), strlen(npat));
3259 if (!isttest(chk->expect.hdr.name)) {
3260 memprintf(errmsg, "out of memory");
3261 goto error;
3262 }
3263 }
3264
3265 if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE) {
3266 chk->expect.hdr.value = IST_NULL;
3267 break;
3268 }
3269
3270 if (!vpat) {
3271 memprintf(errmsg, "unexpected error, undefined header value pattern");
3272 goto error;
3273 }
3274 else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG) {
3275 chk->expect.hdr.value_re = regex_comp(vpat, 1, 0, errmsg);
3276 if (!chk->expect.hdr.value_re)
3277 goto error;
3278 }
3279 else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
3280 px->conf.args.ctx = ARGC_SRV;
3281 LIST_INIT(&chk->expect.hdr.value_fmt);
3282 if (!parse_logformat_string(vpat, px, &chk->expect.hdr.value_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
3283 memprintf(errmsg, "'%s' invalid log-format string (%s).\n", npat, *errmsg);
3284 goto error;
3285 }
3286 }
3287 else {
3288 chk->expect.hdr.value = ist2(strdup(vpat), strlen(vpat));
3289 if (!isttest(chk->expect.hdr.value)) {
3290 memprintf(errmsg, "out of memory");
3291 goto error;
3292 }
3293 }
3294
3295 break;
3296 case TCPCHK_EXPECT_CUSTOM:
3297 chk->expect.custom = NULL; /* Must be defined by the caller ! */
3298 break;
3299 case TCPCHK_EXPECT_UNDEF:
3300 memprintf(errmsg, "pattern not found");
3301 goto error;
3302 }
3303
3304 /* All tcp-check expect points back to the first inverse expect rule in
3305 * a chain of one or more expect rule, potentially itself.
3306 */
3307 chk->expect.head = chk;
3308 list_for_each_entry_rev(prev_check, rules, list) {
3309 if (prev_check->action == TCPCHK_ACT_EXPECT) {
3310 if (prev_check->expect.flags & TCPCHK_EXPT_FL_INV)
3311 chk->expect.head = prev_check;
3312 continue;
3313 }
3314 if (prev_check->action != TCPCHK_ACT_COMMENT && prev_check->action != TCPCHK_ACT_ACTION_KW)
3315 break;
3316 }
3317 return chk;
3318
3319 error:
3320 free_tcpcheck(chk, 0);
3321 free(comment);
3322 release_sample_expr(status_expr);
3323 return NULL;
3324}
3325
3326/* Overwrites fields of the old http send rule with those of the new one. When
3327 * replaced, old values are freed and replaced by the new ones. New values are
3328 * not copied but transferred. At the end <new> should be empty and can be
3329 * safely released. This function never fails.
3330 */
3331void tcpcheck_overwrite_send_http_rule(struct tcpcheck_rule *old, struct tcpcheck_rule *new)
3332{
3333 struct logformat_node *lf, *lfb;
3334 struct tcpcheck_http_hdr *hdr, *bhdr;
3335
3336
3337 if (new->send.http.meth.str.area) {
3338 free(old->send.http.meth.str.area);
3339 old->send.http.meth.meth = new->send.http.meth.meth;
3340 old->send.http.meth.str.area = new->send.http.meth.str.area;
3341 old->send.http.meth.str.data = new->send.http.meth.str.data;
3342 new->send.http.meth.str = BUF_NULL;
3343 }
3344
3345 if (!(new->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) && isttest(new->send.http.uri)) {
3346 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
3347 istfree(&old->send.http.uri);
3348 else
3349 free_tcpcheck_fmt(&old->send.http.uri_fmt);
3350 old->send.http.flags &= ~TCPCHK_SND_HTTP_FL_URI_FMT;
3351 old->send.http.uri = new->send.http.uri;
3352 new->send.http.uri = IST_NULL;
3353 }
3354 else if ((new->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) && !LIST_ISEMPTY(&new->send.http.uri_fmt)) {
3355 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
3356 istfree(&old->send.http.uri);
3357 else
3358 free_tcpcheck_fmt(&old->send.http.uri_fmt);
3359 old->send.http.flags |= TCPCHK_SND_HTTP_FL_URI_FMT;
3360 LIST_INIT(&old->send.http.uri_fmt);
3361 list_for_each_entry_safe(lf, lfb, &new->send.http.uri_fmt, list) {
3362 LIST_DEL(&lf->list);
3363 LIST_ADDQ(&old->send.http.uri_fmt, &lf->list);
3364 }
3365 }
3366
3367 if (isttest(new->send.http.vsn)) {
3368 istfree(&old->send.http.vsn);
3369 old->send.http.vsn = new->send.http.vsn;
3370 new->send.http.vsn = IST_NULL;
3371 }
3372
3373 free_tcpcheck_http_hdrs(&old->send.http.hdrs);
3374 list_for_each_entry_safe(hdr, bhdr, &new->send.http.hdrs, list) {
3375 LIST_DEL(&hdr->list);
3376 LIST_ADDQ(&old->send.http.hdrs, &hdr->list);
3377 }
3378
3379 if (!(new->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) && isttest(new->send.http.body)) {
3380 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
3381 istfree(&old->send.http.body);
3382 else
3383 free_tcpcheck_fmt(&old->send.http.body_fmt);
3384 old->send.http.flags &= ~TCPCHK_SND_HTTP_FL_BODY_FMT;
3385 old->send.http.body = new->send.http.body;
3386 new->send.http.body = IST_NULL;
3387 }
3388 else if ((new->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) && !LIST_ISEMPTY(&new->send.http.body_fmt)) {
3389 if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
3390 istfree(&old->send.http.body);
3391 else
3392 free_tcpcheck_fmt(&old->send.http.body_fmt);
3393 old->send.http.flags |= TCPCHK_SND_HTTP_FL_BODY_FMT;
3394 LIST_INIT(&old->send.http.body_fmt);
3395 list_for_each_entry_safe(lf, lfb, &new->send.http.body_fmt, list) {
3396 LIST_DEL(&lf->list);
3397 LIST_ADDQ(&old->send.http.body_fmt, &lf->list);
3398 }
3399 }
3400}
3401
3402/* Internal function used to add an http-check rule in a list during the config
3403 * parsing step. Depending on its type, and the previously inserted rules, a
3404 * specific action may be performed or an error may be reported. This functions
3405 * returns 1 on success and 0 on error and <errmsg> is filled with the error
3406 * message.
3407 */
3408int tcpcheck_add_http_rule(struct tcpcheck_rule *chk, struct tcpcheck_rules *rules, char **errmsg)
3409{
3410 struct tcpcheck_rule *r;
3411
3412 /* the implicit send rule coming from an "option httpchk" line must be
3413 * merged with the first explici http-check send rule, if
Ilya Shipitsin47d17182020-06-21 21:42:57 +05003414 * any. Depending on the declaration order some tests are required.
Willy Tarreau51cd5952020-06-05 12:25:38 +02003415 *
Ilya Shipitsin47d17182020-06-21 21:42:57 +05003416 * Some tests are also required for other kinds of http-check rules to be
Willy Tarreau51cd5952020-06-05 12:25:38 +02003417 * sure the ruleset remains valid.
3418 */
3419
3420 if (chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
3421 /* Tries to add an implicit http-check send rule from an "option httpchk" line.
3422 * First, the first rule is retrieved, skipping the first CONNECT, if any, and
3423 * following tests are performed :
3424 *
3425 * 1- If there is no such rule or if it is not a send rule, the implicit send
3426 * rule is pushed in front of the ruleset
3427 *
3428 * 2- If it is another implicit send rule, it is replaced with the new one.
3429 *
3430 * 3- Otherwise, it means it is an explicit send rule. In this case we merge
3431 * both, overwriting the old send rule (the explicit one) with info of the
3432 * new send rule (the implicit one).
3433 */
3434 r = get_first_tcpcheck_rule(rules);
3435 if (r && r->action == TCPCHK_ACT_CONNECT)
3436 r = get_next_tcpcheck_rule(rules, r);
3437 if (!r || r->action != TCPCHK_ACT_SEND)
3438 LIST_ADD(rules->list, &chk->list);
3439 else if (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT) {
3440 LIST_DEL(&r->list);
3441 free_tcpcheck(r, 0);
3442 LIST_ADD(rules->list, &chk->list);
3443 }
3444 else {
3445 tcpcheck_overwrite_send_http_rule(r, chk);
3446 free_tcpcheck(chk, 0);
3447 }
3448 }
3449 else {
3450 /* Tries to add an explicit http-check rule. First of all we check the typefo the
3451 * last inserted rule to be sure it is valid. Then for send rule, we try to merge it
3452 * with an existing implicit send rule, if any. At the end, if there is no error,
3453 * the rule is appended to the list.
3454 */
3455
3456 r = get_last_tcpcheck_rule(rules);
3457 if (!r || (r->action == TCPCHK_ACT_SEND && (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)))
3458 /* no error */;
3459 else if (r->action != TCPCHK_ACT_CONNECT && chk->action == TCPCHK_ACT_SEND) {
3460 memprintf(errmsg, "unable to add http-check send rule at step %d (missing connect rule).",
3461 chk->index+1);
3462 return 0;
3463 }
3464 else if (r->action != TCPCHK_ACT_SEND && r->action != TCPCHK_ACT_EXPECT && chk->action == TCPCHK_ACT_EXPECT) {
3465 memprintf(errmsg, "unable to add http-check expect rule at step %d (missing send rule).",
3466 chk->index+1);
3467 return 0;
3468 }
3469 else if (r->action != TCPCHK_ACT_EXPECT && chk->action == TCPCHK_ACT_CONNECT) {
3470 memprintf(errmsg, "unable to add http-check connect rule at step %d (missing expect rule).",
3471 chk->index+1);
3472 return 0;
3473 }
3474
3475 if (chk->action == TCPCHK_ACT_SEND) {
3476 r = get_first_tcpcheck_rule(rules);
3477 if (r && r->action == TCPCHK_ACT_SEND && (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
3478 tcpcheck_overwrite_send_http_rule(r, chk);
3479 free_tcpcheck(chk, 0);
3480 LIST_DEL(&r->list);
3481 r->send.http.flags &= ~TCPCHK_SND_HTTP_FROM_OPT;
3482 chk = r;
3483 }
3484 }
3485 LIST_ADDQ(rules->list, &chk->list);
3486 }
3487 return 1;
3488}
3489
3490/* Check tcp-check health-check configuration for the proxy <px>. */
3491static int check_proxy_tcpcheck(struct proxy *px)
3492{
3493 struct tcpcheck_rule *chk, *back;
3494 char *comment = NULL, *errmsg = NULL;
3495 enum tcpcheck_rule_type prev_action = TCPCHK_ACT_COMMENT;
3496 int ret = 0;
3497
3498 if (!(px->cap & PR_CAP_BE) || (px->options2 & PR_O2_CHK_ANY) != PR_O2_TCPCHK_CHK) {
3499 deinit_proxy_tcpcheck(px);
3500 goto out;
3501 }
3502
3503 free(px->check_command);
3504 free(px->check_path);
3505 px->check_command = px->check_path = NULL;
3506
3507 if (!px->tcpcheck_rules.list) {
3508 ha_alert("config : proxy '%s' : tcp-check configured but no ruleset defined.\n", px->id);
3509 ret |= ERR_ALERT | ERR_FATAL;
3510 goto out;
3511 }
3512
3513 /* HTTP ruleset only : */
3514 if ((px->tcpcheck_rules.flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK) {
3515 struct tcpcheck_rule *next;
3516
3517 /* move remaining implicit send rule from "option httpchk" line to the right place.
3518 * If such rule exists, it must be the first one. In this case, the rule is moved
3519 * after the first connect rule, if any. Otherwise, nothing is done.
3520 */
3521 chk = get_first_tcpcheck_rule(&px->tcpcheck_rules);
3522 if (chk && chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
3523 next = get_next_tcpcheck_rule(&px->tcpcheck_rules, chk);
3524 if (next && next->action == TCPCHK_ACT_CONNECT) {
3525 LIST_DEL(&chk->list);
3526 LIST_ADD(&next->list, &chk->list);
3527 chk->index = next->index;
3528 }
3529 }
3530
3531 /* add implicit expect rule if the last one is a send. It is inherited from previous
3532 * versions where the http expect rule was optional. Now it is possible to chained
3533 * send/expect rules but the last expect may still be implicit.
3534 */
3535 chk = get_last_tcpcheck_rule(&px->tcpcheck_rules);
3536 if (chk && chk->action == TCPCHK_ACT_SEND) {
3537 next = parse_tcpcheck_expect((char *[]){"http-check", "expect", "status", "200-399", ""},
3538 1, px, px->tcpcheck_rules.list, TCPCHK_RULES_HTTP_CHK,
3539 px->conf.file, px->conf.line, &errmsg);
3540 if (!next) {
3541 ha_alert("config : proxy '%s': unable to add implicit http-check expect rule "
3542 "(%s).\n", px->id, errmsg);
3543 free(errmsg);
3544 ret |= ERR_ALERT | ERR_FATAL;
3545 goto out;
3546 }
3547 LIST_ADDQ(px->tcpcheck_rules.list, &next->list);
3548 next->index = chk->index;
3549 }
3550 }
3551
3552 /* For all ruleset: */
3553
3554 /* If there is no connect rule preceding all send / expect rules, an
3555 * implicit one is inserted before all others.
3556 */
3557 chk = get_first_tcpcheck_rule(&px->tcpcheck_rules);
3558 if (!chk || chk->action != TCPCHK_ACT_CONNECT) {
3559 chk = calloc(1, sizeof(*chk));
3560 if (!chk) {
3561 ha_alert("config : proxy '%s': unable to add implicit tcp-check connect rule "
3562 "(out of memory).\n", px->id);
3563 ret |= ERR_ALERT | ERR_FATAL;
3564 goto out;
3565 }
3566 chk->action = TCPCHK_ACT_CONNECT;
3567 chk->connect.options = (TCPCHK_OPT_DEFAULT_CONNECT|TCPCHK_OPT_IMPLICIT);
3568 LIST_ADD(px->tcpcheck_rules.list, &chk->list);
3569 }
3570
3571 /* Remove all comment rules. To do so, when a such rule is found, the
3572 * comment is assigned to the following rule(s).
3573 */
3574 list_for_each_entry_safe(chk, back, px->tcpcheck_rules.list, list) {
3575 if (chk->action != prev_action && prev_action != TCPCHK_ACT_COMMENT) {
3576 free(comment);
3577 comment = NULL;
3578 }
3579
3580 prev_action = chk->action;
3581 switch (chk->action) {
3582 case TCPCHK_ACT_COMMENT:
3583 free(comment);
3584 comment = chk->comment;
3585 LIST_DEL(&chk->list);
3586 free(chk);
3587 break;
3588 case TCPCHK_ACT_CONNECT:
3589 if (!chk->comment && comment)
3590 chk->comment = strdup(comment);
Tim Duesterhus588b3142020-05-29 14:35:51 +02003591 /* fall through */
Willy Tarreau51cd5952020-06-05 12:25:38 +02003592 case TCPCHK_ACT_ACTION_KW:
3593 free(comment);
3594 comment = NULL;
3595 break;
3596 case TCPCHK_ACT_SEND:
3597 case TCPCHK_ACT_EXPECT:
3598 if (!chk->comment && comment)
3599 chk->comment = strdup(comment);
3600 break;
3601 }
3602 }
3603 free(comment);
3604 comment = NULL;
3605
3606 out:
3607 return ret;
3608}
3609
3610void deinit_proxy_tcpcheck(struct proxy *px)
3611{
3612 free_tcpcheck_vars(&px->tcpcheck_rules.preset_vars);
3613 px->tcpcheck_rules.flags = 0;
3614 px->tcpcheck_rules.list = NULL;
3615}
3616
3617static void deinit_tcpchecks()
3618{
3619 struct tcpcheck_ruleset *rs;
3620 struct tcpcheck_rule *r, *rb;
3621 struct ebpt_node *node, *next;
3622
3623 node = ebpt_first(&shared_tcpchecks);
3624 while (node) {
3625 next = ebpt_next(node);
3626 ebpt_delete(node);
3627 free(node->key);
3628 rs = container_of(node, typeof(*rs), node);
3629 list_for_each_entry_safe(r, rb, &rs->rules, list) {
3630 LIST_DEL(&r->list);
3631 free_tcpcheck(r, 0);
3632 }
3633 free(rs);
3634 node = next;
3635 }
3636}
3637
3638int add_tcpcheck_expect_str(struct tcpcheck_rules *rules, const char *str)
3639{
3640 struct tcpcheck_rule *tcpcheck, *prev_check;
3641 struct tcpcheck_expect *expect;
3642
3643 if ((tcpcheck = pool_alloc(pool_head_tcpcheck_rule)) == NULL)
3644 return 0;
3645 memset(tcpcheck, 0, sizeof(*tcpcheck));
3646 tcpcheck->action = TCPCHK_ACT_EXPECT;
3647
3648 expect = &tcpcheck->expect;
3649 expect->type = TCPCHK_EXPECT_STRING;
3650 LIST_INIT(&expect->onerror_fmt);
3651 LIST_INIT(&expect->onsuccess_fmt);
3652 expect->ok_status = HCHK_STATUS_L7OKD;
3653 expect->err_status = HCHK_STATUS_L7RSP;
3654 expect->tout_status = HCHK_STATUS_L7TOUT;
3655 expect->data = ist2(strdup(str), strlen(str));
3656 if (!isttest(expect->data)) {
3657 pool_free(pool_head_tcpcheck_rule, tcpcheck);
3658 return 0;
3659 }
3660
3661 /* All tcp-check expect points back to the first inverse expect rule
3662 * in a chain of one or more expect rule, potentially itself.
3663 */
3664 tcpcheck->expect.head = tcpcheck;
3665 list_for_each_entry_rev(prev_check, rules->list, list) {
3666 if (prev_check->action == TCPCHK_ACT_EXPECT) {
3667 if (prev_check->expect.flags & TCPCHK_EXPT_FL_INV)
3668 tcpcheck->expect.head = prev_check;
3669 continue;
3670 }
3671 if (prev_check->action != TCPCHK_ACT_COMMENT && prev_check->action != TCPCHK_ACT_ACTION_KW)
3672 break;
3673 }
3674 LIST_ADDQ(rules->list, &tcpcheck->list);
3675 return 1;
3676}
3677
3678int add_tcpcheck_send_strs(struct tcpcheck_rules *rules, const char * const *strs)
3679{
3680 struct tcpcheck_rule *tcpcheck;
3681 struct tcpcheck_send *send;
3682 const char *in;
3683 char *dst;
3684 int i;
3685
3686 if ((tcpcheck = pool_alloc(pool_head_tcpcheck_rule)) == NULL)
3687 return 0;
3688 memset(tcpcheck, 0, sizeof(*tcpcheck));
3689 tcpcheck->action = TCPCHK_ACT_SEND;
3690
3691 send = &tcpcheck->send;
3692 send->type = TCPCHK_SEND_STRING;
3693
3694 for (i = 0; strs[i]; i++)
3695 send->data.len += strlen(strs[i]);
3696
3697 send->data.ptr = malloc(istlen(send->data) + 1);
3698 if (!isttest(send->data)) {
3699 pool_free(pool_head_tcpcheck_rule, tcpcheck);
3700 return 0;
3701 }
3702
3703 dst = istptr(send->data);
3704 for (i = 0; strs[i]; i++)
3705 for (in = strs[i]; (*dst = *in++); dst++);
3706 *dst = 0;
3707
3708 LIST_ADDQ(rules->list, &tcpcheck->list);
3709 return 1;
3710}
3711
3712/* Parses the "tcp-check" proxy keyword */
3713static int proxy_parse_tcpcheck(char **args, int section, struct proxy *curpx,
3714 struct proxy *defpx, const char *file, int line,
3715 char **errmsg)
3716{
3717 struct tcpcheck_ruleset *rs = NULL;
3718 struct tcpcheck_rule *chk = NULL;
3719 int index, cur_arg, ret = 0;
3720
3721 if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[0], NULL))
3722 ret = 1;
3723
3724 /* Deduce the ruleset name from the proxy info */
3725 chunk_printf(&trash, "*tcp-check-%s_%s-%d",
3726 ((curpx == defpx) ? "defaults" : curpx->id),
3727 curpx->conf.file, curpx->conf.line);
3728
3729 rs = find_tcpcheck_ruleset(b_orig(&trash));
3730 if (rs == NULL) {
3731 rs = create_tcpcheck_ruleset(b_orig(&trash));
3732 if (rs == NULL) {
3733 memprintf(errmsg, "out of memory.\n");
3734 goto error;
3735 }
3736 }
3737
3738 index = 0;
3739 if (!LIST_ISEMPTY(&rs->rules)) {
3740 chk = LIST_PREV(&rs->rules, typeof(chk), list);
3741 index = chk->index + 1;
3742 }
3743
3744 cur_arg = 1;
3745 if (strcmp(args[cur_arg], "connect") == 0)
3746 chk = parse_tcpcheck_connect(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
3747 else if (strcmp(args[cur_arg], "send") == 0 || strcmp(args[cur_arg], "send-binary") == 0 ||
3748 strcmp(args[cur_arg], "send-lf") == 0 || strcmp(args[cur_arg], "send-binary-lf") == 0)
3749 chk = parse_tcpcheck_send(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
3750 else if (strcmp(args[cur_arg], "expect") == 0)
3751 chk = parse_tcpcheck_expect(args, cur_arg, curpx, &rs->rules, 0, file, line, errmsg);
3752 else if (strcmp(args[cur_arg], "comment") == 0)
3753 chk = parse_tcpcheck_comment(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
3754 else {
3755 struct action_kw *kw = action_kw_tcp_check_lookup(args[cur_arg]);
3756
3757 if (!kw) {
3758 action_kw_tcp_check_build_list(&trash);
3759 memprintf(errmsg, "'%s' only supports 'comment', 'connect', 'send', 'send-binary', 'expect'"
3760 "%s%s. but got '%s'",
3761 args[0], (*trash.area ? ", " : ""), trash.area, args[1]);
3762 goto error;
3763 }
3764 chk = parse_tcpcheck_action(args, cur_arg, curpx, &rs->rules, kw, file, line, errmsg);
3765 }
3766
3767 if (!chk) {
3768 memprintf(errmsg, "'%s %s' : %s.", args[0], args[1], *errmsg);
3769 goto error;
3770 }
3771 ret = (ret || (*errmsg != NULL)); /* Handle warning */
3772
3773 /* No error: add the tcp-check rule in the list */
3774 chk->index = index;
3775 LIST_ADDQ(&rs->rules, &chk->list);
3776
3777 if ((curpx->options2 & PR_O2_CHK_ANY) == PR_O2_TCPCHK_CHK &&
3778 (curpx->tcpcheck_rules.flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_TCP_CHK) {
3779 /* Use this ruleset if the proxy already has tcp-check enabled */
3780 curpx->tcpcheck_rules.list = &rs->rules;
3781 curpx->tcpcheck_rules.flags &= ~TCPCHK_RULES_UNUSED_TCP_RS;
3782 }
3783 else {
3784 /* mark this ruleset as unused for now */
3785 curpx->tcpcheck_rules.flags |= TCPCHK_RULES_UNUSED_TCP_RS;
3786 }
3787
3788 return ret;
3789
3790 error:
3791 free_tcpcheck(chk, 0);
3792 free_tcpcheck_ruleset(rs);
3793 return -1;
3794}
3795
3796static struct cfg_kw_list cfg_kws = {ILH, {
3797 { CFG_LISTEN, "tcp-check", proxy_parse_tcpcheck },
3798 { 0, NULL, NULL },
3799}};
3800
3801REGISTER_POST_PROXY_CHECK(check_proxy_tcpcheck);
3802REGISTER_PROXY_DEINIT(deinit_proxy_tcpcheck);
3803REGISTER_POST_DEINIT(deinit_tcpchecks);
3804INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);