1 /*
2  * ACL management functions.
3  *
4  * Copyright 2000-2013 Willy Tarreau <w@1wt.eu>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  *
11  */
12 
13 #include <ctype.h>
14 #include <stdio.h>
15 #include <string.h>
16 
17 #include <import/ebsttree.h>
18 
19 #include <haproxy/acl.h>
20 #include <haproxy/api.h>
21 #include <haproxy/arg.h>
22 #include <haproxy/auth.h>
23 #include <haproxy/errors.h>
24 #include <haproxy/global.h>
25 #include <haproxy/list.h>
26 #include <haproxy/pattern.h>
27 #include <haproxy/proxy-t.h>
28 #include <haproxy/sample.h>
29 #include <haproxy/stick_table.h>
30 #include <haproxy/tools.h>
31 
32 /* List head of all known ACL keywords */
33 static struct acl_kw_list acl_keywords = {
34 	.list = LIST_HEAD_INIT(acl_keywords.list)
35 };
36 
37 /* input values are 0 or 3, output is the same */
pat2acl(struct pattern * pat)38 static inline enum acl_test_res pat2acl(struct pattern *pat)
39 {
40 	if (pat)
41 		return ACL_TEST_PASS;
42 	else
43 		return ACL_TEST_FAIL;
44 }
45 
46 /*
47  * Registers the ACL keyword list <kwl> as a list of valid keywords for next
48  * parsing sessions.
49  */
acl_register_keywords(struct acl_kw_list * kwl)50 void acl_register_keywords(struct acl_kw_list *kwl)
51 {
52 	LIST_APPEND(&acl_keywords.list, &kwl->list);
53 }
54 
55 /*
56  * Unregisters the ACL keyword list <kwl> from the list of valid keywords.
57  */
acl_unregister_keywords(struct acl_kw_list * kwl)58 void acl_unregister_keywords(struct acl_kw_list *kwl)
59 {
60 	LIST_DELETE(&kwl->list);
61 	LIST_INIT(&kwl->list);
62 }
63 
64 /* Return a pointer to the ACL <name> within the list starting at <head>, or
65  * NULL if not found.
66  */
find_acl_by_name(const char * name,struct list * head)67 struct acl *find_acl_by_name(const char *name, struct list *head)
68 {
69 	struct acl *acl;
70 	list_for_each_entry(acl, head, list) {
71 		if (strcmp(acl->name, name) == 0)
72 			return acl;
73 	}
74 	return NULL;
75 }
76 
77 /* Return a pointer to the ACL keyword <kw>, or NULL if not found. Note that if
78  * <kw> contains an opening parenthesis or a comma, only the left part of it is
79  * checked.
80  */
find_acl_kw(const char * kw)81 struct acl_keyword *find_acl_kw(const char *kw)
82 {
83 	int index;
84 	const char *kwend;
85 	struct acl_kw_list *kwl;
86 
87 	kwend = kw;
88 	while (is_idchar(*kwend))
89 		kwend++;
90 
91 	list_for_each_entry(kwl, &acl_keywords.list, list) {
92 		for (index = 0; kwl->kw[index].kw != NULL; index++) {
93 			if ((strncmp(kwl->kw[index].kw, kw, kwend - kw) == 0) &&
94 			    kwl->kw[index].kw[kwend-kw] == 0)
95 				return &kwl->kw[index];
96 		}
97 	}
98 	return NULL;
99 }
100 
prune_acl_expr(struct acl_expr * expr)101 static struct acl_expr *prune_acl_expr(struct acl_expr *expr)
102 {
103 	struct arg *arg;
104 	int unresolved = 0;
105 
106 	pattern_prune(&expr->pat);
107 
108 	for (arg = expr->smp->arg_p; arg; arg++) {
109 		if (arg->type == ARGT_STOP)
110 			break;
111 		if (arg->type == ARGT_STR || arg->unresolved) {
112 			chunk_destroy(&arg->data.str);
113 			unresolved |= arg->unresolved;
114 			arg->unresolved = 0;
115 		}
116 	}
117 
118 	release_sample_expr(expr->smp);
119 
120 	return expr;
121 }
122 
123 /* Parse an ACL expression starting at <args>[0], and return it. If <err> is
124  * not NULL, it will be filled with a pointer to an error message in case of
125  * error. This pointer must be freeable or NULL. <al> is an arg_list serving
126  * as a list head to report missing dependencies. It may be NULL if such
127  * dependencies are not allowed.
128  *
129  * Right now, the only accepted syntax is :
130  * <subject> [<value>...]
131  */
parse_acl_expr(const char ** args,char ** err,struct arg_list * al,const char * file,int line)132 struct acl_expr *parse_acl_expr(const char **args, char **err, struct arg_list *al,
133                                 const char *file, int line)
134 {
135 	__label__ out_return, out_free_expr;
136 	struct acl_expr *expr;
137 	struct acl_keyword *aclkw;
138 	int refflags, patflags;
139 	const char *arg;
140 	struct sample_expr *smp = NULL;
141 	int idx = 0;
142 	char *ckw = NULL;
143 	const char *begw;
144 	const char *endw;
145 	const char *endt;
146 	int cur_type;
147 	int nbargs;
148 	int operator = STD_OP_EQ;
149 	int op;
150 	int contain_colon, have_dot;
151 	const char *dot;
152 	signed long long value, minor;
153 	/* The following buffer contain two numbers, a ':' separator and the final \0. */
154 	char buffer[NB_LLMAX_STR + 1 + NB_LLMAX_STR + 1];
155 	int is_loaded;
156 	int unique_id;
157 	char *error;
158 	struct pat_ref *ref;
159 	struct pattern_expr *pattern_expr;
160 	int load_as_map = 0;
161 	int acl_conv_found = 0;
162 
163 	/* First, we look for an ACL keyword. And if we don't find one, then
164 	 * we look for a sample fetch expression starting with a sample fetch
165 	 * keyword.
166 	 */
167 
168 	if (al) {
169 		al->ctx  = ARGC_ACL;   // to report errors while resolving args late
170 		al->kw   = *args;
171 		al->conv = NULL;
172 	}
173 
174 	aclkw = find_acl_kw(args[0]);
175 	if (aclkw) {
176 		/* OK we have a real ACL keyword */
177 
178 		/* build new sample expression for this ACL */
179 		smp = calloc(1, sizeof(*smp));
180 		if (!smp) {
181 			memprintf(err, "out of memory when parsing ACL expression");
182 			goto out_return;
183 		}
184 		LIST_INIT(&(smp->conv_exprs));
185 		smp->fetch = aclkw->smp;
186 		smp->arg_p = empty_arg_list;
187 
188 		/* look for the beginning of the subject arguments */
189 		for (arg = args[0]; is_idchar(*arg); arg++)
190 			;
191 
192 		/* At this point, we have :
193 		 *   - args[0] : beginning of the keyword
194 		 *   - arg     : end of the keyword, first character not part of keyword
195 		 */
196 		nbargs = make_arg_list(arg, -1, smp->fetch->arg_mask, &smp->arg_p,
197 		                       err, &endt, NULL, al);
198 		if (nbargs < 0) {
199 			/* note that make_arg_list will have set <err> here */
200 			memprintf(err, "ACL keyword '%s' : %s", aclkw->kw, *err);
201 			goto out_free_smp;
202 		}
203 
204 		if (!smp->arg_p) {
205 			smp->arg_p = empty_arg_list;
206 		}
207 		else if (smp->fetch->val_args && !smp->fetch->val_args(smp->arg_p, err)) {
208 			/* invalid keyword argument, error must have been
209 			 * set by val_args().
210 			 */
211 			memprintf(err, "in argument to '%s', %s", aclkw->kw, *err);
212 			goto out_free_smp;
213 		}
214 		arg = endt;
215 
216 		/* look for the beginning of the converters list. Those directly attached
217 		 * to the ACL keyword are found just after <arg> which points to the comma.
218 		 * If we find any converter, then we don't use the ACL keyword's match
219 		 * anymore but the one related to the converter's output type.
220 		 */
221 		cur_type = smp->fetch->out_type;
222 		while (*arg) {
223 			struct sample_conv *conv;
224 			struct sample_conv_expr *conv_expr;
225 			int err_arg;
226 			int argcnt;
227 
228 			if (*arg && *arg != ',') {
229 				if (ckw)
230 					memprintf(err, "ACL keyword '%s' : missing comma after converter '%s'.",
231 						  aclkw->kw, ckw);
232 				else
233 					memprintf(err, "ACL keyword '%s' : missing comma after fetch keyword.",
234 						  aclkw->kw);
235 				goto out_free_smp;
236 			}
237 
238 			/* FIXME: how long should we support such idiocies ? Maybe we
239 			 * should already warn ?
240 			 */
241 			while (*arg == ',') /* then trailing commas */
242 				arg++;
243 
244 			begw = arg; /* start of converter keyword */
245 
246 			if (!*begw)
247 				/* none ? end of converters */
248 				break;
249 
250 			for (endw = begw; is_idchar(*endw); endw++)
251 				;
252 
253 			free(ckw);
254 			ckw = my_strndup(begw, endw - begw);
255 
256 			conv = find_sample_conv(begw, endw - begw);
257 			if (!conv) {
258 				/* Unknown converter method */
259 				memprintf(err, "ACL keyword '%s' : unknown converter '%s'.",
260 					  aclkw->kw, ckw);
261 				goto out_free_smp;
262 			}
263 
264 			arg = endw;
265 
266 			if (conv->in_type >= SMP_TYPES || conv->out_type >= SMP_TYPES) {
267 				memprintf(err, "ACL keyword '%s' : returns type of converter '%s' is unknown.",
268 					  aclkw->kw, ckw);
269 				goto out_free_smp;
270 			}
271 
272 			/* If impossible type conversion */
273 			if (!sample_casts[cur_type][conv->in_type]) {
274 				memprintf(err, "ACL keyword '%s' : converter '%s' cannot be applied.",
275 					  aclkw->kw, ckw);
276 				goto out_free_smp;
277 			}
278 
279 			cur_type = conv->out_type;
280 			conv_expr = calloc(1, sizeof(*conv_expr));
281 			if (!conv_expr)
282 				goto out_free_smp;
283 
284 			LIST_APPEND(&(smp->conv_exprs), &(conv_expr->list));
285 			conv_expr->conv = conv;
286 			acl_conv_found = 1;
287 
288 			if (al) {
289 				al->kw = smp->fetch->kw;
290 				al->conv = conv_expr->conv->kw;
291 			}
292 			argcnt = make_arg_list(endw, -1, conv->arg_mask, &conv_expr->arg_p, err, &arg, &err_arg, al);
293 			if (argcnt < 0) {
294 				memprintf(err, "ACL keyword '%s' : invalid arg %d in converter '%s' : %s.",
295 				          aclkw->kw, err_arg+1, ckw, *err);
296 				goto out_free_smp;
297 			}
298 
299 			if (argcnt && !conv->arg_mask) {
300 				memprintf(err, "converter '%s' does not support any args", ckw);
301 				goto out_free_smp;
302 			}
303 
304 			if (!conv_expr->arg_p)
305 				conv_expr->arg_p = empty_arg_list;
306 
307 			if (conv->val_args && !conv->val_args(conv_expr->arg_p, conv, file, line, err)) {
308 				memprintf(err, "ACL keyword '%s' : invalid args in converter '%s' : %s.",
309 					  aclkw->kw, ckw, *err);
310 				goto out_free_smp;
311 			}
312 		}
313 		ha_free(&ckw);
314 	}
315 	else {
316 		/* This is not an ACL keyword, so we hope this is a sample fetch
317 		 * keyword that we're going to transparently use as an ACL. If
318 		 * so, we retrieve a completely parsed expression with args and
319 		 * convs already done.
320 		 */
321 		smp = sample_parse_expr((char **)args, &idx, file, line, err, al, NULL);
322 		if (!smp) {
323 			memprintf(err, "%s in ACL expression '%s'", *err, *args);
324 			goto out_return;
325 		}
326 		cur_type = smp_expr_output_type(smp);
327 	}
328 
329 	expr = calloc(1, sizeof(*expr));
330 	if (!expr) {
331 		memprintf(err, "out of memory when parsing ACL expression");
332 		goto out_free_smp;
333 	}
334 
335 	pattern_init_head(&expr->pat);
336 
337 	expr->pat.expect_type = cur_type;
338 	expr->smp             = smp;
339 	expr->kw              = smp->fetch->kw;
340 	smp = NULL; /* don't free it anymore */
341 
342 	if (aclkw && !acl_conv_found) {
343 		expr->kw = aclkw->kw;
344 		expr->pat.parse  = aclkw->parse  ? aclkw->parse  : pat_parse_fcts[aclkw->match_type];
345 		expr->pat.index  = aclkw->index  ? aclkw->index  : pat_index_fcts[aclkw->match_type];
346 		expr->pat.match  = aclkw->match  ? aclkw->match  : pat_match_fcts[aclkw->match_type];
347 		expr->pat.prune  = aclkw->prune  ? aclkw->prune  : pat_prune_fcts[aclkw->match_type];
348 	}
349 
350 	if (!expr->pat.parse) {
351 		/* Parse/index/match functions depend on the expression type,
352 		 * so we have to map them now. Some types can be automatically
353 		 * converted.
354 		 */
355 		switch (cur_type) {
356 		case SMP_T_BOOL:
357 			expr->pat.parse = pat_parse_fcts[PAT_MATCH_BOOL];
358 			expr->pat.index = pat_index_fcts[PAT_MATCH_BOOL];
359 			expr->pat.match = pat_match_fcts[PAT_MATCH_BOOL];
360 			expr->pat.prune = pat_prune_fcts[PAT_MATCH_BOOL];
361 			expr->pat.expect_type = pat_match_types[PAT_MATCH_BOOL];
362 			break;
363 		case SMP_T_SINT:
364 			expr->pat.parse = pat_parse_fcts[PAT_MATCH_INT];
365 			expr->pat.index = pat_index_fcts[PAT_MATCH_INT];
366 			expr->pat.match = pat_match_fcts[PAT_MATCH_INT];
367 			expr->pat.prune = pat_prune_fcts[PAT_MATCH_INT];
368 			expr->pat.expect_type = pat_match_types[PAT_MATCH_INT];
369 			break;
370 		case SMP_T_ADDR:
371 		case SMP_T_IPV4:
372 		case SMP_T_IPV6:
373 			expr->pat.parse = pat_parse_fcts[PAT_MATCH_IP];
374 			expr->pat.index = pat_index_fcts[PAT_MATCH_IP];
375 			expr->pat.match = pat_match_fcts[PAT_MATCH_IP];
376 			expr->pat.prune = pat_prune_fcts[PAT_MATCH_IP];
377 			expr->pat.expect_type = pat_match_types[PAT_MATCH_IP];
378 			break;
379 		case SMP_T_STR:
380 			expr->pat.parse = pat_parse_fcts[PAT_MATCH_STR];
381 			expr->pat.index = pat_index_fcts[PAT_MATCH_STR];
382 			expr->pat.match = pat_match_fcts[PAT_MATCH_STR];
383 			expr->pat.prune = pat_prune_fcts[PAT_MATCH_STR];
384 			expr->pat.expect_type = pat_match_types[PAT_MATCH_STR];
385 			break;
386 		}
387 	}
388 
389 	/* Additional check to protect against common mistakes */
390 	if (expr->pat.parse && cur_type != SMP_T_BOOL && !*args[1]) {
391 		ha_warning("parsing acl keyword '%s' :\n"
392 			   "  no pattern to match against were provided, so this ACL will never match.\n"
393 			   "  If this is what you intended, please add '--' to get rid of this warning.\n"
394 			   "  If you intended to match only for existence, please use '-m found'.\n"
395 			   "  If you wanted to force an int to match as a bool, please use '-m bool'.\n"
396 			   "\n",
397 			   args[0]);
398 	}
399 
400 	args++;
401 
402 	/* check for options before patterns. Supported options are :
403 	 *   -i : ignore case for all patterns by default
404 	 *   -f : read patterns from those files
405 	 *   -m : force matching method (must be used before -f)
406 	 *   -M : load the file as map file
407 	 *   -u : force the unique id of the acl
408 	 *   -- : everything after this is not an option
409 	 */
410 	refflags = PAT_REF_ACL;
411 	patflags = 0;
412 	is_loaded = 0;
413 	unique_id = -1;
414 	while (**args == '-') {
415 		if (strcmp(*args, "-i") == 0)
416 			patflags |= PAT_MF_IGNORE_CASE;
417 		else if (strcmp(*args, "-n") == 0)
418 			patflags |= PAT_MF_NO_DNS;
419 		else if (strcmp(*args, "-u") == 0) {
420 			unique_id = strtol(args[1], &error, 10);
421 			if (*error != '\0') {
422 				memprintf(err, "the argument of -u must be an integer");
423 				goto out_free_expr;
424 			}
425 
426 			/* Check if this id is really unique. */
427 			if (pat_ref_lookupid(unique_id)) {
428 				memprintf(err, "the id is already used");
429 				goto out_free_expr;
430 			}
431 
432 			args++;
433 		}
434 		else if (strcmp(*args, "-f") == 0) {
435 			if (!expr->pat.parse) {
436 				memprintf(err, "matching method must be specified first (using '-m') when using a sample fetch of this type ('%s')", expr->kw);
437 				goto out_free_expr;
438 			}
439 
440 			if (!pattern_read_from_file(&expr->pat, refflags, args[1], patflags, load_as_map, err, file, line))
441 				goto out_free_expr;
442 			is_loaded = 1;
443 			args++;
444 		}
445 		else if (strcmp(*args, "-m") == 0) {
446 			int idx;
447 
448 			if (is_loaded) {
449 				memprintf(err, "'-m' must only be specified before patterns and files in parsing ACL expression");
450 				goto out_free_expr;
451 			}
452 
453 			idx = pat_find_match_name(args[1]);
454 			if (idx < 0) {
455 				memprintf(err, "unknown matching method '%s' when parsing ACL expression", args[1]);
456 				goto out_free_expr;
457 			}
458 
459 			/* Note: -m found is always valid, bool/int are compatible, str/bin/reg/len are compatible */
460 			if (idx != PAT_MATCH_FOUND && !sample_casts[cur_type][pat_match_types[idx]]) {
461 				memprintf(err, "matching method '%s' cannot be used with fetch keyword '%s'", args[1], expr->kw);
462 				goto out_free_expr;
463 			}
464 			expr->pat.parse = pat_parse_fcts[idx];
465 			expr->pat.index = pat_index_fcts[idx];
466 			expr->pat.match = pat_match_fcts[idx];
467 			expr->pat.prune = pat_prune_fcts[idx];
468 			expr->pat.expect_type = pat_match_types[idx];
469 			args++;
470 		}
471 		else if (strcmp(*args, "-M") == 0) {
472 			refflags |= PAT_REF_MAP;
473 			load_as_map = 1;
474 		}
475 		else if (strcmp(*args, "--") == 0) {
476 			args++;
477 			break;
478 		}
479 		else {
480 			memprintf(err, "'%s' is not a valid ACL option. Please use '--' before any pattern beginning with a '-'", args[0]);
481 			goto out_free_expr;
482 			break;
483 		}
484 		args++;
485 	}
486 
487 	if (!expr->pat.parse) {
488 		memprintf(err, "matching method must be specified first (using '-m') when using a sample fetch of this type ('%s')", expr->kw);
489 		goto out_free_expr;
490 	}
491 
492 	/* Create displayed reference */
493 	snprintf(trash.area, trash.size, "acl '%s' file '%s' line %d",
494 		 expr->kw, file, line);
495 	trash.area[trash.size - 1] = '\0';
496 
497 	/* Create new pattern reference. */
498 	ref = pat_ref_newid(unique_id, trash.area, PAT_REF_ACL);
499 	if (!ref) {
500 		memprintf(err, "memory error");
501 		goto out_free_expr;
502 	}
503 
504 	/* Create new pattern expression associated to this reference. */
505 	pattern_expr = pattern_new_expr(&expr->pat, ref, patflags, err, NULL);
506 	if (!pattern_expr)
507 		goto out_free_expr;
508 
509 	/* now parse all patterns */
510 	while (**args) {
511 		arg = *args;
512 
513 		/* Compatibility layer. Each pattern can parse only one string per pattern,
514 		 * but the pat_parser_int() and pat_parse_dotted_ver() parsers were need
515 		 * optionally two operators. The first operator is the match method: eq,
516 		 * le, lt, ge and gt. pat_parse_int() and pat_parse_dotted_ver() functions
517 		 * can have a compatibility syntax based on ranges:
518 		 *
519 		 * pat_parse_int():
520 		 *
521 		 *   "eq x" -> "x" or "x:x"
522 		 *   "le x" -> ":x"
523 		 *   "lt x" -> ":y" (with y = x - 1)
524 		 *   "ge x" -> "x:"
525 		 *   "gt x" -> "y:" (with y = x + 1)
526 		 *
527 		 * pat_parse_dotted_ver():
528 		 *
529 		 *   "eq x.y" -> "x.y" or "x.y:x.y"
530 		 *   "le x.y" -> ":x.y"
531 		 *   "lt x.y" -> ":w.z" (with w.z = x.y - 1)
532 		 *   "ge x.y" -> "x.y:"
533 		 *   "gt x.y" -> "w.z:" (with w.z = x.y + 1)
534 		 *
535 		 * If y is not present, assume that is "0".
536 		 *
537 		 * The syntax eq, le, lt, ge and gt are proper to the acl syntax. The
538 		 * following block of code detect the operator, and rewrite each value
539 		 * in parsable string.
540 		 */
541 		if (expr->pat.parse == pat_parse_int ||
542 		    expr->pat.parse == pat_parse_dotted_ver) {
543 			/* Check for operator. If the argument is operator, memorise it and
544 			 * continue to the next argument.
545 			 */
546 			op = get_std_op(arg);
547 			if (op != -1) {
548 				operator = op;
549 				args++;
550 				continue;
551 			}
552 
553 			/* Check if the pattern contain ':' or '-' character. */
554 			contain_colon = (strchr(arg, ':') || strchr(arg, '-'));
555 
556 			/* If the pattern contain ':' or '-' character, give it to the parser as is.
557 			 * If no contain ':' and operator is STD_OP_EQ, give it to the parser as is.
558 			 * In other case, try to convert the value according with the operator.
559 			 */
560 			if (!contain_colon && operator != STD_OP_EQ) {
561 				/* Search '.' separator. */
562 				dot = strchr(arg, '.');
563 				if (!dot) {
564 					have_dot = 0;
565 					minor = 0;
566 					dot = arg + strlen(arg);
567 				}
568 				else
569 					have_dot = 1;
570 
571 				/* convert the integer minor part for the pat_parse_dotted_ver() function. */
572 				if (expr->pat.parse == pat_parse_dotted_ver && have_dot) {
573 					if (strl2llrc(dot+1, strlen(dot+1), &minor) != 0) {
574 						memprintf(err, "'%s' is neither a number nor a supported operator", arg);
575 						goto out_free_expr;
576 					}
577 					if (minor >= 65536) {
578 						memprintf(err, "'%s' contains too large a minor value", arg);
579 						goto out_free_expr;
580 					}
581 				}
582 
583 				/* convert the integer value for the pat_parse_int() function, and the
584 				 * integer major part for the pat_parse_dotted_ver() function.
585 				 */
586 				if (strl2llrc(arg, dot - arg, &value) != 0) {
587 					memprintf(err, "'%s' is neither a number nor a supported operator", arg);
588 					goto out_free_expr;
589 				}
590 				if (expr->pat.parse == pat_parse_dotted_ver)  {
591 					if (value >= 65536) {
592 						memprintf(err, "'%s' contains too large a major value", arg);
593 						goto out_free_expr;
594 					}
595 					value = (value << 16) | (minor & 0xffff);
596 				}
597 
598 				switch (operator) {
599 
600 				case STD_OP_EQ: /* this case is not possible. */
601 					memprintf(err, "internal error");
602 					goto out_free_expr;
603 
604 				case STD_OP_GT:
605 					value++; /* gt = ge + 1 */
606 					/* fall through */
607 
608 				case STD_OP_GE:
609 					if (expr->pat.parse == pat_parse_int)
610 						snprintf(buffer, NB_LLMAX_STR+NB_LLMAX_STR+2, "%lld:", value);
611 					else
612 						snprintf(buffer, NB_LLMAX_STR+NB_LLMAX_STR+2, "%lld.%lld:",
613 						         value >> 16, value & 0xffff);
614 					arg = buffer;
615 					break;
616 
617 				case STD_OP_LT:
618 					value--; /* lt = le - 1 */
619 					/* fall through */
620 
621 				case STD_OP_LE:
622 					if (expr->pat.parse == pat_parse_int)
623 						snprintf(buffer, NB_LLMAX_STR+NB_LLMAX_STR+2, ":%lld", value);
624 					else
625 						snprintf(buffer, NB_LLMAX_STR+NB_LLMAX_STR+2, ":%lld.%lld",
626 						         value >> 16, value & 0xffff);
627 					arg = buffer;
628 					break;
629 				}
630 			}
631 		}
632 
633 		/* Add sample to the reference, and try to compile it fior each pattern
634 		 * using this value.
635 		 */
636 		if (!pat_ref_add(ref, arg, NULL, err))
637 			goto out_free_expr;
638 		args++;
639 	}
640 
641 	return expr;
642 
643  out_free_expr:
644 	prune_acl_expr(expr);
645 	free(expr);
646  out_free_smp:
647 	free(ckw);
648 	free(smp);
649  out_return:
650 	return NULL;
651 }
652 
653 /* Purge everything in the acl <acl>, then return <acl>. */
prune_acl(struct acl * acl)654 struct acl *prune_acl(struct acl *acl) {
655 
656 	struct acl_expr *expr, *exprb;
657 
658 	free(acl->name);
659 
660 	list_for_each_entry_safe(expr, exprb, &acl->expr, list) {
661 		LIST_DELETE(&expr->list);
662 		prune_acl_expr(expr);
663 		free(expr);
664 	}
665 
666 	return acl;
667 }
668 
669 /* Parse an ACL with the name starting at <args>[0], and with a list of already
670  * known ACLs in <acl>. If the ACL was not in the list, it will be added.
671  * A pointer to that ACL is returned. If the ACL has an empty name, then it's
672  * an anonymous one and it won't be merged with any other one. If <err> is not
673  * NULL, it will be filled with an appropriate error. This pointer must be
674  * freeable or NULL. <al> is the arg_list serving as a head for unresolved
675  * dependencies. It may be NULL if such dependencies are not allowed.
676  *
677  * args syntax: <aclname> <acl_expr>
678  */
parse_acl(const char ** args,struct list * known_acl,char ** err,struct arg_list * al,const char * file,int line)679 struct acl *parse_acl(const char **args, struct list *known_acl, char **err, struct arg_list *al,
680                       const char *file, int line)
681 {
682 	__label__ out_return, out_free_acl_expr, out_free_name;
683 	struct acl *cur_acl;
684 	struct acl_expr *acl_expr;
685 	char *name;
686 	const char *pos;
687 
688 	if (**args && (pos = invalid_char(*args))) {
689 		memprintf(err, "invalid character in ACL name : '%c'", *pos);
690 		goto out_return;
691 	}
692 
693 	acl_expr = parse_acl_expr(args + 1, err, al, file, line);
694 	if (!acl_expr) {
695 		/* parse_acl_expr will have filled <err> here */
696 		goto out_return;
697 	}
698 
699 	/* Check for args beginning with an opening parenthesis just after the
700 	 * subject, as this is almost certainly a typo. Right now we can only
701 	 * emit a warning, so let's do so.
702 	 */
703 	if (!strchr(args[1], '(') && *args[2] == '(')
704 		ha_warning("parsing acl '%s' :\n"
705 			   "  matching '%s' for pattern '%s' is likely a mistake and probably\n"
706 			   "  not what you want. Maybe you need to remove the extraneous space before '('.\n"
707 			   "  If you are really sure this is not an error, please insert '--' between the\n"
708 			   "  match and the pattern to make this warning message disappear.\n",
709 			   args[0], args[1], args[2]);
710 
711 	if (*args[0])
712 		cur_acl = find_acl_by_name(args[0], known_acl);
713 	else
714 		cur_acl = NULL;
715 
716 	if (!cur_acl) {
717 		name = strdup(args[0]);
718 		if (!name) {
719 			memprintf(err, "out of memory when parsing ACL");
720 			goto out_free_acl_expr;
721 		}
722 		cur_acl = calloc(1, sizeof(*cur_acl));
723 		if (cur_acl == NULL) {
724 			memprintf(err, "out of memory when parsing ACL");
725 			goto out_free_name;
726 		}
727 
728 		LIST_INIT(&cur_acl->expr);
729 		LIST_APPEND(known_acl, &cur_acl->list);
730 		cur_acl->name = name;
731 	}
732 
733 	/* We want to know what features the ACL needs (typically HTTP parsing),
734 	 * and where it may be used. If an ACL relies on multiple matches, it is
735 	 * OK if at least one of them may match in the context where it is used.
736 	 */
737 	cur_acl->use |= acl_expr->smp->fetch->use;
738 	cur_acl->val |= acl_expr->smp->fetch->val;
739 	LIST_APPEND(&cur_acl->expr, &acl_expr->list);
740 	return cur_acl;
741 
742  out_free_name:
743 	free(name);
744  out_free_acl_expr:
745 	prune_acl_expr(acl_expr);
746 	free(acl_expr);
747  out_return:
748 	return NULL;
749 }
750 
751 /* Some useful ACLs provided by default. Only those used are allocated. */
752 
753 const struct {
754 	const char *name;
755 	const char *expr[4]; /* put enough for longest expression */
756 } default_acl_list[] = {
757 	{ .name = "TRUE",           .expr = {"always_true",""}},
758 	{ .name = "FALSE",          .expr = {"always_false",""}},
759 	{ .name = "LOCALHOST",      .expr = {"src","127.0.0.1/8",""}},
760 	{ .name = "HTTP",           .expr = {"req.proto_http",""}},
761 	{ .name = "HTTP_1.0",       .expr = {"req.ver","1.0",""}},
762 	{ .name = "HTTP_1.1",       .expr = {"req.ver","1.1",""}},
763 	{ .name = "HTTP_2.0",       .expr = {"req.ver","2.0",""}},
764 	{ .name = "METH_CONNECT",   .expr = {"method","CONNECT",""}},
765 	{ .name = "METH_DELETE",    .expr = {"method","DELETE",""}},
766 	{ .name = "METH_GET",       .expr = {"method","GET","HEAD",""}},
767 	{ .name = "METH_HEAD",      .expr = {"method","HEAD",""}},
768 	{ .name = "METH_OPTIONS",   .expr = {"method","OPTIONS",""}},
769 	{ .name = "METH_POST",      .expr = {"method","POST",""}},
770 	{ .name = "METH_PUT",       .expr = {"method","PUT",""}},
771 	{ .name = "METH_TRACE",     .expr = {"method","TRACE",""}},
772 	{ .name = "HTTP_URL_ABS",   .expr = {"url_reg","^[^/:]*://",""}},
773 	{ .name = "HTTP_URL_SLASH", .expr = {"url_beg","/",""}},
774 	{ .name = "HTTP_URL_STAR",  .expr = {"url","*",""}},
775 	{ .name = "HTTP_CONTENT",   .expr = {"req.hdr_val(content-length)","gt","0",""}},
776 	{ .name = "RDP_COOKIE",     .expr = {"req.rdp_cookie_cnt","gt","0",""}},
777 	{ .name = "REQ_CONTENT",    .expr = {"req.len","gt","0",""}},
778 	{ .name = "WAIT_END",       .expr = {"wait_end",""}},
779 	{ .name = NULL, .expr = {""}}
780 };
781 
782 /* Find a default ACL from the default_acl list, compile it and return it.
783  * If the ACL is not found, NULL is returned. In theory, it cannot fail,
784  * except when default ACLs are broken, in which case it will return NULL.
785  * If <known_acl> is not NULL, the ACL will be queued at its tail. If <err> is
786  * not NULL, it will be filled with an error message if an error occurs. This
787  * pointer must be freeable or NULL. <al> is an arg_list serving as a list head
788  * to report missing dependencies. It may be NULL if such dependencies are not
789  * allowed.
790  */
find_acl_default(const char * acl_name,struct list * known_acl,char ** err,struct arg_list * al,const char * file,int line)791 static struct acl *find_acl_default(const char *acl_name, struct list *known_acl,
792                                     char **err, struct arg_list *al,
793                                     const char *file, int line)
794 {
795 	__label__ out_return, out_free_acl_expr, out_free_name;
796 	struct acl *cur_acl;
797 	struct acl_expr *acl_expr;
798 	char *name;
799 	int index;
800 
801 	for (index = 0; default_acl_list[index].name != NULL; index++) {
802 		if (strcmp(acl_name, default_acl_list[index].name) == 0)
803 			break;
804 	}
805 
806 	if (default_acl_list[index].name == NULL) {
807 		memprintf(err, "no such ACL : '%s'", acl_name);
808 		return NULL;
809 	}
810 
811 	acl_expr = parse_acl_expr((const char **)default_acl_list[index].expr, err, al, file, line);
812 	if (!acl_expr) {
813 		/* parse_acl_expr must have filled err here */
814 		goto out_return;
815 	}
816 
817 	name = strdup(acl_name);
818 	if (!name) {
819 		memprintf(err, "out of memory when building default ACL '%s'", acl_name);
820 		goto out_free_acl_expr;
821 	}
822 
823 	cur_acl = calloc(1, sizeof(*cur_acl));
824 	if (cur_acl == NULL) {
825 		memprintf(err, "out of memory when building default ACL '%s'", acl_name);
826 		goto out_free_name;
827 	}
828 
829 	cur_acl->name = name;
830 	cur_acl->use |= acl_expr->smp->fetch->use;
831 	cur_acl->val |= acl_expr->smp->fetch->val;
832 	LIST_INIT(&cur_acl->expr);
833 	LIST_APPEND(&cur_acl->expr, &acl_expr->list);
834 	if (known_acl)
835 		LIST_APPEND(known_acl, &cur_acl->list);
836 
837 	return cur_acl;
838 
839  out_free_name:
840 	free(name);
841  out_free_acl_expr:
842 	prune_acl_expr(acl_expr);
843 	free(acl_expr);
844  out_return:
845 	return NULL;
846 }
847 
848 /* Purge everything in the acl_cond <cond>, then return <cond>. */
prune_acl_cond(struct acl_cond * cond)849 struct acl_cond *prune_acl_cond(struct acl_cond *cond)
850 {
851 	struct acl_term_suite *suite, *tmp_suite;
852 	struct acl_term *term, *tmp_term;
853 
854 	/* iterate through all term suites and free all terms and all suites */
855 	list_for_each_entry_safe(suite, tmp_suite, &cond->suites, list) {
856 		list_for_each_entry_safe(term, tmp_term, &suite->terms, list)
857 			free(term);
858 		free(suite);
859 	}
860 	return cond;
861 }
862 
863 /* Parse an ACL condition starting at <args>[0], relying on a list of already
864  * known ACLs passed in <known_acl>. The new condition is returned (or NULL in
865  * case of low memory). Supports multiple conditions separated by "or". If
866  * <err> is not NULL, it will be filled with a pointer to an error message in
867  * case of error, that the caller is responsible for freeing. The initial
868  * location must either be freeable or NULL. The list <al> serves as a list head
869  * for unresolved dependencies. It may be NULL if such dependencies are not
870  * allowed.
871  */
parse_acl_cond(const char ** args,struct list * known_acl,enum acl_cond_pol pol,char ** err,struct arg_list * al,const char * file,int line)872 struct acl_cond *parse_acl_cond(const char **args, struct list *known_acl,
873                                 enum acl_cond_pol pol, char **err, struct arg_list *al,
874                                 const char *file, int line)
875 {
876 	__label__ out_return, out_free_suite, out_free_term;
877 	int arg, neg;
878 	const char *word;
879 	struct acl *cur_acl;
880 	struct acl_term *cur_term;
881 	struct acl_term_suite *cur_suite;
882 	struct acl_cond *cond;
883 	unsigned int suite_val;
884 
885 	cond = calloc(1, sizeof(*cond));
886 	if (cond == NULL) {
887 		memprintf(err, "out of memory when parsing condition");
888 		goto out_return;
889 	}
890 
891 	LIST_INIT(&cond->list);
892 	LIST_INIT(&cond->suites);
893 	cond->pol = pol;
894 	cond->val = 0;
895 
896 	cur_suite = NULL;
897 	suite_val = ~0U;
898 	neg = 0;
899 	for (arg = 0; *args[arg]; arg++) {
900 		word = args[arg];
901 
902 		/* remove as many exclamation marks as we can */
903 		while (*word == '!') {
904 			neg = !neg;
905 			word++;
906 		}
907 
908 		/* an empty word is allowed because we cannot force the user to
909 		 * always think about not leaving exclamation marks alone.
910 		 */
911 		if (!*word)
912 			continue;
913 
914 		if (strcasecmp(word, "or") == 0 || strcmp(word, "||") == 0) {
915 			/* new term suite */
916 			cond->val |= suite_val;
917 			suite_val = ~0U;
918 			cur_suite = NULL;
919 			neg = 0;
920 			continue;
921 		}
922 
923 		if (strcmp(word, "{") == 0) {
924 			/* we may have a complete ACL expression between two braces,
925 			 * find the last one.
926 			 */
927 			int arg_end = arg + 1;
928 			const char **args_new;
929 
930 			while (*args[arg_end] && strcmp(args[arg_end], "}") != 0)
931 				arg_end++;
932 
933 			if (!*args[arg_end]) {
934 				memprintf(err, "missing closing '}' in condition");
935 				goto out_free_suite;
936 			}
937 
938 			args_new = calloc(1, (arg_end - arg + 1) * sizeof(*args_new));
939 			if (!args_new) {
940 				memprintf(err, "out of memory when parsing condition");
941 				goto out_free_suite;
942 			}
943 
944 			args_new[0] = "";
945 			memcpy(args_new + 1, args + arg + 1, (arg_end - arg) * sizeof(*args_new));
946 			args_new[arg_end - arg] = "";
947 			cur_acl = parse_acl(args_new, known_acl, err, al, file, line);
948 			free(args_new);
949 
950 			if (!cur_acl) {
951 				/* note that parse_acl() must have filled <err> here */
952 				goto out_free_suite;
953 			}
954 			arg = arg_end;
955 		}
956 		else {
957 			/* search for <word> in the known ACL names. If we do not find
958 			 * it, let's look for it in the default ACLs, and if found, add
959 			 * it to the list of ACLs of this proxy. This makes it possible
960 			 * to override them.
961 			 */
962 			cur_acl = find_acl_by_name(word, known_acl);
963 			if (cur_acl == NULL) {
964 				cur_acl = find_acl_default(word, known_acl, err, al, file, line);
965 				if (cur_acl == NULL) {
966 					/* note that find_acl_default() must have filled <err> here */
967 					goto out_free_suite;
968 				}
969 			}
970 		}
971 
972 		cur_term = calloc(1, sizeof(*cur_term));
973 		if (cur_term == NULL) {
974 			memprintf(err, "out of memory when parsing condition");
975 			goto out_free_suite;
976 		}
977 
978 		cur_term->acl = cur_acl;
979 		cur_term->neg = neg;
980 
981 		/* Here it is a bit complex. The acl_term_suite is a conjunction
982 		 * of many terms. It may only be used if all of its terms are
983 		 * usable at the same time. So the suite's validity domain is an
984 		 * AND between all ACL keywords' ones. But, the global condition
985 		 * is valid if at least one term suite is OK. So it's an OR between
986 		 * all of their validity domains. We could emit a warning as soon
987 		 * as suite_val is null because it means that the last ACL is not
988 		 * compatible with the previous ones. Let's remain simple for now.
989 		 */
990 		cond->use |= cur_acl->use;
991 		suite_val &= cur_acl->val;
992 
993 		if (!cur_suite) {
994 			cur_suite = calloc(1, sizeof(*cur_suite));
995 			if (cur_suite == NULL) {
996 				memprintf(err, "out of memory when parsing condition");
997 				goto out_free_term;
998 			}
999 			LIST_INIT(&cur_suite->terms);
1000 			LIST_APPEND(&cond->suites, &cur_suite->list);
1001 		}
1002 		LIST_APPEND(&cur_suite->terms, &cur_term->list);
1003 		neg = 0;
1004 	}
1005 
1006 	cond->val |= suite_val;
1007 	return cond;
1008 
1009  out_free_term:
1010 	free(cur_term);
1011  out_free_suite:
1012 	prune_acl_cond(cond);
1013 	free(cond);
1014  out_return:
1015 	return NULL;
1016 }
1017 
1018 /* Builds an ACL condition starting at the if/unless keyword. The complete
1019  * condition is returned. NULL is returned in case of error or if the first
1020  * word is neither "if" nor "unless". It automatically sets the file name and
1021  * the line number in the condition for better error reporting, and sets the
1022  * HTTP intiailization requirements in the proxy. If <err> is not NULL, it will
1023  * be filled with a pointer to an error message in case of error, that the
1024  * caller is responsible for freeing. The initial location must either be
1025  * freeable or NULL.
1026  */
build_acl_cond(const char * file,int line,struct list * known_acl,struct proxy * px,const char ** args,char ** err)1027 struct acl_cond *build_acl_cond(const char *file, int line, struct list *known_acl,
1028 				struct proxy *px, const char **args, char **err)
1029 {
1030 	enum acl_cond_pol pol = ACL_COND_NONE;
1031 	struct acl_cond *cond = NULL;
1032 
1033 	if (err)
1034 		*err = NULL;
1035 
1036 	if (strcmp(*args, "if") == 0) {
1037 		pol = ACL_COND_IF;
1038 		args++;
1039 	}
1040 	else if (strcmp(*args, "unless") == 0) {
1041 		pol = ACL_COND_UNLESS;
1042 		args++;
1043 	}
1044 	else {
1045 		memprintf(err, "conditions must start with either 'if' or 'unless'");
1046 		return NULL;
1047 	}
1048 
1049 	cond = parse_acl_cond(args, known_acl, pol, err, &px->conf.args, file, line);
1050 	if (!cond) {
1051 		/* note that parse_acl_cond must have filled <err> here */
1052 		return NULL;
1053 	}
1054 
1055 	cond->file = file;
1056 	cond->line = line;
1057 	px->http_needed |= !!(cond->use & SMP_USE_HTTP_ANY);
1058 	return cond;
1059 }
1060 
1061 /* Execute condition <cond> and return either ACL_TEST_FAIL, ACL_TEST_MISS or
1062  * ACL_TEST_PASS depending on the test results. ACL_TEST_MISS may only be
1063  * returned if <opt> does not contain SMP_OPT_FINAL, indicating that incomplete
1064  * data is being examined. The function automatically sets SMP_OPT_ITERATE. This
1065  * function only computes the condition, it does not apply the polarity required
1066  * by IF/UNLESS, it's up to the caller to do this using something like this :
1067  *
1068  *     res = acl_pass(res);
1069  *     if (res == ACL_TEST_MISS)
1070  *         return 0;
1071  *     if (cond->pol == ACL_COND_UNLESS)
1072  *         res = !res;
1073  */
acl_exec_cond(struct acl_cond * cond,struct proxy * px,struct session * sess,struct stream * strm,unsigned int opt)1074 enum acl_test_res acl_exec_cond(struct acl_cond *cond, struct proxy *px, struct session *sess, struct stream *strm, unsigned int opt)
1075 {
1076 	__label__ fetch_next;
1077 	struct acl_term_suite *suite;
1078 	struct acl_term *term;
1079 	struct acl_expr *expr;
1080 	struct acl *acl;
1081 	struct sample smp;
1082 	enum acl_test_res acl_res, suite_res, cond_res;
1083 
1084 	/* ACLs are iterated over all values, so let's always set the flag to
1085 	 * indicate this to the fetch functions.
1086 	 */
1087 	opt |= SMP_OPT_ITERATE;
1088 
1089 	/* We're doing a logical OR between conditions so we initialize to FAIL.
1090 	 * The MISS status is propagated down from the suites.
1091 	 */
1092 	cond_res = ACL_TEST_FAIL;
1093 	list_for_each_entry(suite, &cond->suites, list) {
1094 		/* Evaluate condition suite <suite>. We stop at the first term
1095 		 * which returns ACL_TEST_FAIL. The MISS status is still propagated
1096 		 * in case of uncertainty in the result.
1097 		 */
1098 
1099 		/* we're doing a logical AND between terms, so we must set the
1100 		 * initial value to PASS.
1101 		 */
1102 		suite_res = ACL_TEST_PASS;
1103 		list_for_each_entry(term, &suite->terms, list) {
1104 			acl = term->acl;
1105 
1106 			/* FIXME: use cache !
1107 			 * check acl->cache_idx for this.
1108 			 */
1109 
1110 			/* ACL result not cached. Let's scan all the expressions
1111 			 * and use the first one to match.
1112 			 */
1113 			acl_res = ACL_TEST_FAIL;
1114 			list_for_each_entry(expr, &acl->expr, list) {
1115 				/* we need to reset context and flags */
1116 				memset(&smp, 0, sizeof(smp));
1117 			fetch_next:
1118 				if (!sample_process(px, sess, strm, opt, expr->smp, &smp)) {
1119 					/* maybe we could not fetch because of missing data */
1120 					if (smp.flags & SMP_F_MAY_CHANGE && !(opt & SMP_OPT_FINAL))
1121 						acl_res |= ACL_TEST_MISS;
1122 					continue;
1123 				}
1124 
1125 				acl_res |= pat2acl(pattern_exec_match(&expr->pat, &smp, 0));
1126 				/*
1127 				 * OK now acl_res holds the result of this expression
1128 				 * as one of ACL_TEST_FAIL, ACL_TEST_MISS or ACL_TEST_PASS.
1129 				 *
1130 				 * Then if (!MISS) we can cache the result, and put
1131 				 * (smp.flags & SMP_F_VOLATILE) in the cache flags.
1132 				 *
1133 				 * FIXME: implement cache.
1134 				 *
1135 				 */
1136 
1137 				/* we're ORing these terms, so a single PASS is enough */
1138 				if (acl_res == ACL_TEST_PASS)
1139 					break;
1140 
1141 				if (smp.flags & SMP_F_NOT_LAST)
1142 					goto fetch_next;
1143 
1144 				/* sometimes we know the fetched data is subject to change
1145 				 * later and give another chance for a new match (eg: request
1146 				 * size, time, ...)
1147 				 */
1148 				if (smp.flags & SMP_F_MAY_CHANGE && !(opt & SMP_OPT_FINAL))
1149 					acl_res |= ACL_TEST_MISS;
1150 			}
1151 			/*
1152 			 * Here we have the result of an ACL (cached or not).
1153 			 * ACLs are combined, negated or not, to form conditions.
1154 			 */
1155 
1156 			if (term->neg)
1157 				acl_res = acl_neg(acl_res);
1158 
1159 			suite_res &= acl_res;
1160 
1161 			/* we're ANDing these terms, so a single FAIL or MISS is enough */
1162 			if (suite_res != ACL_TEST_PASS)
1163 				break;
1164 		}
1165 		cond_res |= suite_res;
1166 
1167 		/* we're ORing these terms, so a single PASS is enough */
1168 		if (cond_res == ACL_TEST_PASS)
1169 			break;
1170 	}
1171 	return cond_res;
1172 }
1173 
1174 /* Returns a pointer to the first ACL conflicting with usage at place <where>
1175  * which is one of the SMP_VAL_* bits indicating a check place, or NULL if
1176  * no conflict is found. Only full conflicts are detected (ACL is not usable).
1177  * Use the next function to check for useless keywords.
1178  */
acl_cond_conflicts(const struct acl_cond * cond,unsigned int where)1179 const struct acl *acl_cond_conflicts(const struct acl_cond *cond, unsigned int where)
1180 {
1181 	struct acl_term_suite *suite;
1182 	struct acl_term *term;
1183 	struct acl *acl;
1184 
1185 	list_for_each_entry(suite, &cond->suites, list) {
1186 		list_for_each_entry(term, &suite->terms, list) {
1187 			acl = term->acl;
1188 			if (!(acl->val & where))
1189 				return acl;
1190 		}
1191 	}
1192 	return NULL;
1193 }
1194 
1195 /* Returns a pointer to the first ACL and its first keyword to conflict with
1196  * usage at place <where> which is one of the SMP_VAL_* bits indicating a check
1197  * place. Returns true if a conflict is found, with <acl> and <kw> set (if non
1198  * null), or false if not conflict is found. The first useless keyword is
1199  * returned.
1200  */
acl_cond_kw_conflicts(const struct acl_cond * cond,unsigned int where,struct acl const ** acl,char const ** kw)1201 int acl_cond_kw_conflicts(const struct acl_cond *cond, unsigned int where, struct acl const **acl, char const **kw)
1202 {
1203 	struct acl_term_suite *suite;
1204 	struct acl_term *term;
1205 	struct acl_expr *expr;
1206 
1207 	list_for_each_entry(suite, &cond->suites, list) {
1208 		list_for_each_entry(term, &suite->terms, list) {
1209 			list_for_each_entry(expr, &term->acl->expr, list) {
1210 				if (!(expr->smp->fetch->val & where)) {
1211 					if (acl)
1212 						*acl = term->acl;
1213 					if (kw)
1214 						*kw = expr->kw;
1215 					return 1;
1216 				}
1217 			}
1218 		}
1219 	}
1220 	return 0;
1221 }
1222 
1223 /*
1224  * Find targets for userlist and groups in acl. Function returns the number
1225  * of errors or OK if everything is fine. It must be called only once sample
1226  * fetch arguments have been resolved (after smp_resolve_args()).
1227  */
acl_find_targets(struct proxy * p)1228 int acl_find_targets(struct proxy *p)
1229 {
1230 
1231 	struct acl *acl;
1232 	struct acl_expr *expr;
1233 	struct pattern_list *pattern;
1234 	int cfgerr = 0;
1235 	struct pattern_expr_list *pexp;
1236 
1237 	list_for_each_entry(acl, &p->acl, list) {
1238 		list_for_each_entry(expr, &acl->expr, list) {
1239 			if (strcmp(expr->kw, "http_auth_group") == 0) {
1240 				/* Note: the ARGT_USR argument may only have been resolved earlier
1241 				 * by smp_resolve_args().
1242 				 */
1243 				if (expr->smp->arg_p->unresolved) {
1244 					ha_alert("Internal bug in proxy %s: %sacl %s %s() makes use of unresolved userlist '%s'. Please report this.\n",
1245 						 p->id, *acl->name ? "" : "anonymous ", acl->name, expr->kw,
1246 						 expr->smp->arg_p->data.str.area);
1247 					cfgerr++;
1248 					continue;
1249 				}
1250 
1251 				if (LIST_ISEMPTY(&expr->pat.head)) {
1252 					ha_alert("proxy %s: acl %s %s(): no groups specified.\n",
1253 						 p->id, acl->name, expr->kw);
1254 					cfgerr++;
1255 					continue;
1256 				}
1257 
1258 				/* For each pattern, check if the group exists. */
1259 				list_for_each_entry(pexp, &expr->pat.head, list) {
1260 					if (LIST_ISEMPTY(&pexp->expr->patterns)) {
1261 						ha_alert("proxy %s: acl %s %s(): no groups specified.\n",
1262 							 p->id, acl->name, expr->kw);
1263 						cfgerr++;
1264 						continue;
1265 					}
1266 
1267 					list_for_each_entry(pattern, &pexp->expr->patterns, list) {
1268 						/* this keyword only has one argument */
1269 						if (!check_group(expr->smp->arg_p->data.usr, pattern->pat.ptr.str)) {
1270 							ha_alert("proxy %s: acl %s %s(): invalid group '%s'.\n",
1271 								 p->id, acl->name, expr->kw, pattern->pat.ptr.str);
1272 							cfgerr++;
1273 						}
1274 					}
1275 				}
1276 			}
1277 		}
1278 	}
1279 
1280 	return cfgerr;
1281 }
1282 
1283 /* initializes ACLs by resolving the sample fetch names they rely upon.
1284  * Returns 0 on success, otherwise an error.
1285  */
init_acl()1286 int init_acl()
1287 {
1288 	int err = 0;
1289 	int index;
1290 	const char *name;
1291 	struct acl_kw_list *kwl;
1292 	struct sample_fetch *smp;
1293 
1294 	list_for_each_entry(kwl, &acl_keywords.list, list) {
1295 		for (index = 0; kwl->kw[index].kw != NULL; index++) {
1296 			name = kwl->kw[index].fetch_kw;
1297 			if (!name)
1298 				name = kwl->kw[index].kw;
1299 
1300 			smp = find_sample_fetch(name, strlen(name));
1301 			if (!smp) {
1302 				ha_alert("Critical internal error: ACL keyword '%s' relies on sample fetch '%s' which was not registered!\n",
1303 					 kwl->kw[index].kw, name);
1304 				err++;
1305 				continue;
1306 			}
1307 			kwl->kw[index].smp = smp;
1308 		}
1309 	}
1310 	return err;
1311 }
1312 
free_acl_cond(struct acl_cond * cond)1313 void free_acl_cond(struct acl_cond *cond)
1314 {
1315 	struct acl_term_suite *suite, *suiteb;
1316 	struct acl_term *term, *termb;
1317 
1318 	if (!cond)
1319 		return;
1320 
1321 	list_for_each_entry_safe(suite, suiteb, &cond->suites, list) {
1322 		list_for_each_entry_safe(term, termb, &suite->terms, list) {
1323 			LIST_DELETE(&term->list);
1324 			free(term);
1325 		}
1326 		LIST_DELETE(&suite->list);
1327 		free(suite);
1328 	}
1329 
1330 	free(cond);
1331 }
1332 
1333 /************************************************************************/
1334 /*      All supported sample and ACL keywords must be declared here.    */
1335 /************************************************************************/
1336 
1337 /* Note: must not be declared <const> as its list will be overwritten.
1338  * Please take care of keeping this list alphabetically sorted.
1339  */
1340 static struct acl_kw_list acl_kws = {ILH, {
1341 	{ /* END */ },
1342 }};
1343 
1344 INITCALL1(STG_REGISTER, acl_register_keywords, &acl_kws);
1345 
1346 /*
1347  * Local variables:
1348  *  c-indent-level: 8
1349  *  c-basic-offset: 8
1350  * End:
1351  */
1352