2 * evaluate.c Evaluate complex conditions
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2007 The FreeRADIUS server project
21 * Copyright 2007 Alan DeKok <aland@deployingradius.com>
24 #include <freeradius-devel/ident.h>
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
37 * For POSIX Regular expressions.
38 * (0) Means no extended regular expressions.
39 * REG_EXTENDED means use extended regular expressions.
42 #define REG_EXTENDED (0)
51 static int all_digits(const char *string)
53 const char *p = string;
57 while (isdigit((int) *p)) p++;
64 #define DEBUG4 if (debug_flag > 4)log_debug
67 #define DEBUG4 if (0) log_debug
70 static const char *filler = "????????????????????????????????????????????????????????????????";
72 static const char *expand_string(char *buffer, size_t sizeof_buffer,
74 LRAD_TOKEN value_type, const char *value)
82 case T_SINGLE_QUOTED_STRING:
85 case T_BACK_QUOTED_STRING:
86 result = radius_exec_program(value, request, 1,
87 buffer, sizeof_buffer, NULL,
94 * The result should be ASCII.
96 for (p = buffer; *p != '\0'; p++) {
104 case T_DOUBLE_QUOTED_STRING:
105 if (!strchr(value, '%')) return value;
107 radius_xlat(buffer, sizeof_buffer, value, request, NULL);
115 static LRAD_TOKEN getregex(char **ptr, char *buffer, size_t buflen, int *pcflags)
120 if (*p != '/') return T_OP_INVALID;
122 *pcflags = REG_EXTENDED;
126 if (buflen <= 1) break;
132 * Check for case insensitivity
136 *pcflags |= REG_ICASE;
166 * FIXME: add 'x' and 'u'
170 if ((p[1] >= '0') && (p[1] <= '9') &&
171 (sscanf(p, "%3o", &x) == 1)) {
190 return T_DOUBLE_QUOTED_STRING;
194 static const LRAD_NAME_NUMBER modreturn_table[] = {
195 { "reject", RLM_MODULE_REJECT },
196 { "fail", RLM_MODULE_FAIL },
197 { "ok", RLM_MODULE_OK },
198 { "handled", RLM_MODULE_HANDLED },
199 { "invalid", RLM_MODULE_INVALID },
200 { "userlock", RLM_MODULE_USERLOCK },
201 { "notfound", RLM_MODULE_NOTFOUND },
202 { "noop", RLM_MODULE_NOOP },
203 { "updated", RLM_MODULE_UPDATED },
207 int radius_evaluate_condition(REQUEST *request, int modreturn, int depth,
208 const char **ptr, int evaluate_it, int *presult)
210 int found_condition = FALSE;
213 int evaluate_next_condition = evaluate_it;
214 const char *p = *ptr;
215 const char *q, *start;
216 LRAD_TOKEN token, lt, rt;
217 char left[1024], right[1024], comp[4];
218 const char *pleft, *pright;
219 char xleft[1024], xright[1024];
225 if (!ptr || !*ptr || (depth >= 64)) {
226 radlog(L_ERR, "Internal sanity check failed in evaluate condition");
231 while ((*p == ' ') || (*p == '\t')) p++;
234 DEBUG4(">>> INVERT");
240 * It's a subcondition.
243 const char *end = p + 1;
246 * Evaluate the condition, bailing out on
249 DEBUG4(">>> CALLING EVALUATE %s", end);
250 if (!radius_evaluate_condition(request, modreturn,
252 evaluate_next_condition,
257 if (invert && evaluate_next_condition) {
258 DEBUG2("%.*s Converting !%s -> %s",
260 (result != FALSE) ? "TRUE" : "FALSE",
261 (result == FALSE) ? "TRUE" : "FALSE");
264 result = (result == FALSE);
269 * Start from the end of the previous
273 DEBUG4(">>> EVALUATE RETURNED ::%s::", end);
275 if (!((*p == ')') || (*p == '!') ||
276 ((p[0] == '&') && (p[1] == '&')) ||
277 ((p[0] == '|') && (p[1] == '|')))) {
279 radlog(L_ERR, "Parse error in condition at: %s", p);
282 if (*p == ')') p++; /* skip it */
283 found_condition = TRUE;
285 while ((*p == ' ') || (*p == '\t')) p++;
291 DEBUG4(">>> AT EOL");
297 * (A && B) means "evaluate B
298 * only if A was true"
300 } else if ((p[0] == '&') && (p[1] == '&')) {
301 if (result == TRUE) {
302 evaluate_next_condition = evaluate_it;
304 evaluate_next_condition = FALSE;
309 * (A || B) means "evaluate B
310 * only if A was false"
312 } else if ((p[0] == '|') && (p[1] == '|')) {
313 if (result == FALSE) {
314 evaluate_next_condition = evaluate_it;
316 evaluate_next_condition = FALSE;
320 } else if (*p == ')') {
321 DEBUG4(">>> CLOSING BRACE");
330 radlog(L_ERR, "Unexpected trailing text at: %s", p);
333 } /* else it wasn't an opening brace */
335 while ((*p == ' ') || (*p == '\t')) p++;
338 * More conditions, keep going.
340 if ((*p == '(') || (p[0] == '!')) continue;
342 DEBUG4(">>> LOOKING AT %s", p);
346 * Look for common errors.
348 if ((p[0] == '%') && (p[1] == '{')) {
349 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
354 * Look for word == value
356 lt = gettoken(&p, left, sizeof(left));
357 if ((lt != T_BARE_WORD) &&
358 (lt != T_DOUBLE_QUOTED_STRING) &&
359 (lt != T_SINGLE_QUOTED_STRING) &&
360 (lt != T_BACK_QUOTED_STRING)) {
361 radlog(L_ERR, "Expected string or numbers at: %s", p);
366 if (evaluate_next_condition) {
367 pleft = expand_string(xleft, sizeof(xleft), request,
370 radlog(L_ERR, "Failed expanding string at: %s",
377 * Peek ahead. Maybe it's just a check for
378 * existence. If so, there shouldn't be anything
382 while ((*q == ' ') || (*q == '\t')) q++;
387 if (!*q || (*q == ')') ||
388 ((*q == '!') && (q[1] != '=') && (q[1] != '~')) ||
389 ((q[0] == '&') && (q[1] == '&')) ||
390 ((q[0] == '|') && (q[1] == '|'))) {
392 * Check for truth or falsehood.
394 if (all_digits(pleft)) {
396 result = (lint != 0);
398 } else if (lt == T_BARE_WORD) {
399 result = (modreturn == lrad_str2int(modreturn_table, pleft, -1));
401 result = (*pleft != '\0');
405 DEBUG4(">>> INVERTING result");
406 result = (result == FALSE);
410 if (evaluate_next_condition) {
411 DEBUG2("%.*s Evaluating %s\"%s\" -> %s",
413 invert ? "!" : "", pleft,
414 (result != FALSE) ? "TRUE" : "FALSE");
416 } else if (request) {
417 DEBUG2("%.*s Skipping %s\"%s\"",
419 invert ? "!" : "", pleft);
422 DEBUG4(">>> I%d %d:%s", invert,
424 goto end_of_condition;
428 * Else it's a full "foo == bar" thingy.
430 token = gettoken(&p, comp, sizeof(comp));
431 if ((token < T_OP_NE) || (token > T_OP_CMP_EQ) ||
432 (token == T_OP_CMP_TRUE) ||
433 (token == T_OP_CMP_FALSE)) {
434 radlog(L_ERR, "Expected comparison at: %s", comp);
439 * Look for common errors.
441 if ((p[0] == '%') && (p[1] == '{')) {
442 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
450 if ((token == T_OP_REG_EQ) ||
451 (token == T_OP_REG_NE)) {
452 rt = getregex(&p, right, sizeof(right), &cflags);
455 rt = gettoken(&p, right, sizeof(right));
457 if ((rt != T_BARE_WORD) &&
458 (rt != T_DOUBLE_QUOTED_STRING) &&
459 (rt != T_SINGLE_QUOTED_STRING) &&
460 (rt != T_BACK_QUOTED_STRING)) {
461 radlog(L_ERR, "Expected string or numbers at: %s", p);
466 if (evaluate_next_condition) {
467 pright = expand_string(xright, sizeof(xright), request,
470 radlog(L_ERR, "Failed expanding string at: %s",
476 DEBUG4(">>> %d:%s %d %d:%s",
477 lt, pleft, token, rt, pright);
479 if (evaluate_next_condition) {
484 if (!all_digits(pleft)) {
485 radlog(L_ERR, "Left field is not a number at: %s", pleft);
488 if (!all_digits(pright)) {
489 radlog(L_ERR, "Right field is not a number at: %s", pright);
502 result = (strcmp(pleft, pright) == 0);
506 result = (strcmp(pleft, pright) != 0);
510 result = (lint >= rint);
514 result = (lint > rint);
518 result = (lint <= rint);
522 result = (lint < rint);
529 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
532 * Include substring matches.
534 regcomp(®, pright, cflags);
535 compare = regexec(®, pleft,
536 REQUEST_MAX_REGEX + 1,
541 * Add new %{0}, %{1}, etc.
543 if (compare == 0) for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
547 free(request_data_get(request, request,
548 REQUEST_DATA_REGEX | i));
551 * We MAY have %{2} without %{1}.
553 if (rxmatch[i].rm_so == -1) continue;
556 * Copy substring into buffer.
558 memcpy(buffer, pleft + rxmatch[i].rm_so,
559 rxmatch[i].rm_eo - rxmatch[i].rm_so);
560 buffer[rxmatch[i].rm_eo - rxmatch[i].rm_so] = '\0';
563 * Copy substring, and add it to
566 * Note that we don't check
567 * for out of memory, which is
568 * the only error we can get...
571 request_data_add(request, request,
572 REQUEST_DATA_REGEX | i,
575 result = (compare == 0);
582 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
585 * Include substring matches.
587 regcomp(®, pright, cflags);
588 compare = regexec(®, pleft,
589 REQUEST_MAX_REGEX + 1,
593 result = (compare != 0);
599 DEBUG4(">>> NOT IMPLEMENTED %d", token);
603 DEBUG2("%.*s Evaluating %s(%.*s) -> %s",
605 invert ? "!" : "", p - start, start,
606 (result != FALSE) ? "TRUE" : "FALSE");
608 DEBUG4(">>> GOT result %d", result);
611 * Not evaluating it. We may be just
614 } else if (request) {
615 DEBUG2("%.*s Skipping %s(\"%s\" %s \"%s\")",
617 invert ? "!" : "", pleft, comp, pright);
622 DEBUG4(">>> INVERTING result");
623 result = (result == FALSE);
630 DEBUG4(">>> EVALUATE %d ::%s::",
631 evaluate_next_condition, p);
633 while ((*p == ' ') || (*p == '\t')) p++;
636 * Closing brace or EOL, return.
638 if (!*p || (*p == ')') ||
639 ((*p == '!') && (p[1] != '=') && (p[1] != '~')) ||
640 ((p[0] == '&') && (p[1] == '&')) ||
641 ((p[0] == '|') && (p[1] == '|'))) {
642 DEBUG4(">>> AT EOL2a");
644 if (evaluate_next_condition) *presult = result;
647 } /* loop over the input condition */
649 DEBUG4(">>> AT EOL2b");
651 if (evaluate_next_condition) *presult = result;
656 * The pairmove() function in src/lib/valuepair.c does all sorts of
657 * extra magic that we don't want here.
659 * FIXME: integrate this with the code calling it, so that we
660 * only paircopy() those attributes that we're really going to
663 static void my_pairmove(REQUEST *request, VALUE_PAIR **to, VALUE_PAIR *from)
665 int i, j, count, from_count, to_count, tailto;
666 VALUE_PAIR *vp, *next, **last;
667 VALUE_PAIR **from_list, **to_list;
671 * Set up arrays for editing, to remove some of the
672 * O(N^2) dependencies. This also makes it easier to
673 * insert and remove attributes.
675 * It also means that the operators apply ONLY to the
676 * attributes in the original list. With the previous
677 * implementation of pairmove(), adding two attributes
678 * via "+=" and then "=" would mean that the second one
679 * wasn't added, because of the existence of the first
680 * one in the "to" list. This implementation doesn't
683 * Also, the previous implementation did NOT implement
684 * "-=" correctly. If two of the same attributes existed
685 * in the "to" list, and you tried to subtract something
686 * matching the *second* value, then the pairdelete()
687 * function was called, and the *all* attributes of that
688 * number were deleted. With this implementation, only
689 * the matching attributes are deleted.
692 for (vp = from; vp != NULL; vp = vp->next) count++;
693 from_list = rad_malloc(sizeof(*from_list) * count);
695 for (vp = *to; vp != NULL; vp = vp->next) count++;
696 to_list = rad_malloc(sizeof(*to_list) * count);
699 * Move the lists to the arrays, and break the list
703 for (vp = from; vp != NULL; vp = next) {
705 from_list[from_count++] = vp;
710 for (vp = *to; vp != NULL; vp = next) {
712 to_list[to_count++] = vp;
716 edited = rad_malloc(sizeof(*edited) * to_count);
717 memset(edited, 0, sizeof(*edited) * to_count);
719 DEBUG4("::: FROM %d TO %d MAX %d", from_count, to_count, count);
722 * Now that we have the lists initialized, start working
725 for (i = 0; i < from_count; i++) {
728 DEBUG4("::: Examining %s", from_list[i]->name);
731 * Attribute should be appended, OR the "to" list
732 * is empty, and we're supposed to replace or
733 * "add if not existing".
735 if (from_list[i]->operator == T_OP_ADD) goto append;
738 for (j = 0; j < to_count; j++) {
739 if (edited[j]) continue;
742 * Attributes aren't the same, skip them.
744 if (from_list[i]->attribute != to_list[j]->attribute) {
749 * We don't use a "switch" statement here
750 * because we want to break out of the
751 * "for" loop over 'j' in most cases.
755 * Over-write the FIRST instance of the
756 * matching attribute name. We free the
757 * one in the "to" list, and move over
758 * the one in the "from" list.
760 if (from_list[i]->operator == T_OP_SET) {
761 DEBUG4("::: OVERWRITING %s FROM %d TO %d",
762 to_list[j]->name, i, j);
763 pairfree(&to_list[j]);
764 to_list[j] = from_list[i];
771 * Add the attribute only if it does not
772 * exist... but it exists, so we stop
775 if (from_list[i]->operator == T_OP_EQ) {
781 * Delete all matching attributes from
784 if ((from_list[i]->operator == T_OP_SUB) ||
785 (from_list[i]->operator == T_OP_LE) ||
786 (from_list[i]->operator == T_OP_GE)) {
788 int old_op = from_list[i]->operator;
791 * Check for equality.
793 from_list[i]->operator = T_OP_CMP_EQ;
796 * If equal, delete the one in
799 rcode = radius_compare_vps(NULL, from_list[i],
802 * We may want to do more
803 * subtractions, so we re-set the
804 * operator back to it's original
807 from_list[i]->operator = old_op;
812 DEBUG4("::: DELETING %s FROM %d TO %d",
813 from_list[i]->name, i, j);
814 pairfree(&to_list[j]);
820 * Enforce <=. If it's
825 DEBUG4("::: REPLACING %s FROM %d TO %d",
826 from_list[i]->name, i, j);
827 pairfree(&to_list[j]);
828 to_list[j] = from_list[i];
836 DEBUG4("::: REPLACING %s FROM %d TO %d",
837 from_list[i]->name, i, j);
838 pairfree(&to_list[j]);
839 to_list[j] = from_list[i];
849 rad_assert(0 == 1); /* panic! */
853 * We were asked to add it if it didn't exist,
854 * and it doesn't exist. Move it over to the
855 * tail of the "to" list, UNLESS it was already
856 * moved by another operator.
858 if (!found && from_list[i]) {
859 if ((from_list[i]->operator == T_OP_EQ) ||
860 (from_list[i]->operator == T_OP_LE) ||
861 (from_list[i]->operator == T_OP_GE) ||
862 (from_list[i]->operator == T_OP_SET)) {
864 DEBUG4("::: APPENDING %s FROM %d TO %d",
865 from_list[i]->name, i, tailto);
866 to_list[tailto++] = from_list[i];
873 * Delete attributes in the "from" list.
875 for (i = 0; i < from_count; i++) {
876 if (!from_list[i]) continue;
878 pairfree(&from_list[i]);
882 DEBUG4("::: TO in %d out %d", to_count, tailto);
885 * Re-chain the "to" list.
889 for (i = 0; i < tailto; i++) {
890 if (!to_list[i]) continue;
892 DEBUG4("::: to[%d] = %s", i, to_list[i]->name);
895 * Mash the operator to a simple '='. The
896 * operators in the "to" list aren't used for
897 * anything. BUT they're used in the "detail"
898 * file and debug output, where we don't want to
901 to_list[i]->operator = T_OP_EQ;
904 last = &(*last)->next;
907 * Fix dumb cache issues
909 if ((i >= to_count) || edited[i]) {
910 if (to_list[i]->attribute == PW_USER_NAME) {
911 request->username = to_list[i];
913 } else if (to_list[i]->attribute == PW_USER_PASSWORD) {
914 request->password = to_list[i];
923 * Copied shamelessly from conffile.c, to simplify the API for
926 typedef enum conf_type {
927 CONF_ITEM_INVALID = 0,
934 struct conf_item *next;
935 struct conf_part *parent;
937 const char *filename;
945 LRAD_TOKEN value_type;
949 * Add attributes to a list.
951 int radius_update_attrlist(REQUEST *request, CONF_SECTION *cs,
952 VALUE_PAIR *input_vps, const char *name)
955 VALUE_PAIR *newlist, *vp;
956 VALUE_PAIR **output_vps = NULL;
958 if (!request || !cs) return RLM_MODULE_INVALID;
960 if (strcmp(name, "request") == 0) {
961 output_vps = &request->packet->vps;
963 } else if (strcmp(name, "reply") == 0) {
964 output_vps = &request->reply->vps;
966 } else if (strcmp(name, "proxy-request") == 0) {
967 if (request->proxy) output_vps = &request->proxy->vps;
969 } else if (strcmp(name, "proxy-reply") == 0) {
970 if (request->proxy_reply) output_vps = &request->proxy_reply->vps;
972 } else if (strcmp(name, "config") == 0) {
973 output_vps = &request->config_items;
975 } else if (strcmp(name, "control") == 0) {
976 output_vps = &request->config_items;
979 return RLM_MODULE_INVALID;
982 if (!output_vps) return RLM_MODULE_NOOP; /* didn't update the list */
984 newlist = paircopy(input_vps);
986 DEBUG2("Out of memory");
987 return RLM_MODULE_FAIL;
991 for (ci=cf_item_find_next(cs, NULL);
993 ci=cf_item_find_next(cs, ci)) {
997 * This should never happen.
999 if (cf_item_is_section(ci)) {
1001 return RLM_MODULE_INVALID;
1004 cp = cf_itemtopair(ci);
1007 * The VP && CF lists should be in sync. If they're
1010 if (vp->flags.do_xlat) {
1014 value = expand_string(buffer, sizeof(buffer), request,
1015 cp->value_type, cp->value);
1018 return RLM_MODULE_INVALID;
1021 if (!pairparsevalue(vp, value)) {
1022 DEBUG2("ERROR: Failed parsing value \"%s\" for attribute %s: %s",
1023 value, vp->name, librad_errstr);
1025 return RLM_MODULE_FAIL;
1027 vp->flags.do_xlat = 0;
1032 my_pairmove(request, output_vps, newlist);
1034 return RLM_MODULE_UPDATED;