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 FR_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 FR_TOKEN getregex(const char **ptr, char *buffer, size_t buflen,
118 const char *p = *ptr;
121 if (*p != '/') return T_OP_INVALID;
123 *pcflags = REG_EXTENDED;
127 if (buflen <= 1) break;
133 * Check for case insensitivity
137 *pcflags |= REG_ICASE;
167 * FIXME: add 'x' and 'u'
171 if ((p[1] >= '0') && (p[1] <= '9') &&
172 (sscanf(p, "%3o", &x) == 1)) {
191 return T_DOUBLE_QUOTED_STRING;
195 static const FR_NAME_NUMBER modreturn_table[] = {
196 { "reject", RLM_MODULE_REJECT },
197 { "fail", RLM_MODULE_FAIL },
198 { "ok", RLM_MODULE_OK },
199 { "handled", RLM_MODULE_HANDLED },
200 { "invalid", RLM_MODULE_INVALID },
201 { "userlock", RLM_MODULE_USERLOCK },
202 { "notfound", RLM_MODULE_NOTFOUND },
203 { "noop", RLM_MODULE_NOOP },
204 { "updated", RLM_MODULE_UPDATED },
209 static int radius_get_vp(REQUEST *request, const char *name, VALUE_PAIR **vp_p)
212 const char *vp_name = name;
213 REQUEST *myrequest = request;
215 VALUE_PAIR *vps = NULL;
220 * Allow for tunneled sessions.
222 if (strncmp(vp_name, "outer.", 6) == 0) {
223 if (!myrequest->parent) return TRUE;
225 myrequest = myrequest->parent;
228 if (strncmp(vp_name, "request:", 8) == 0) {
230 vps = myrequest->packet->vps;
232 } else if (strncmp(vp_name, "reply:", 6) == 0) {
234 vps = myrequest->reply->vps;
236 } else if (strncmp(vp_name, "proxy-request:", 14) == 0) {
238 if (request->proxy) vps = myrequest->proxy->vps;
240 } else if (strncmp(vp_name, "proxy-reply:", 12) == 0) {
242 if (request->proxy_reply) vps = myrequest->proxy_reply->vps;
244 } else if (strncmp(vp_name, "config:", 7) == 0) {
246 vps = myrequest->config_items;
248 } else if (strncmp(vp_name, "control:", 8) == 0) {
250 vps = myrequest->config_items;
253 vps = myrequest->packet->vps;
256 da = dict_attrbyname(vp_name);
257 if (!da) return FALSE; /* not a dictionary name */
260 * May not may not be found, but it *is* a known name.
262 *vp_p = pairfind(vps, da->attr);
268 * *presult is "did comparison match or not"
270 static int radius_do_cmp(REQUEST *request, int *presult,
271 FR_TOKEN lt, const char *pleft, FR_TOKEN token,
272 FR_TOKEN rt, const char *pright,
273 int cflags, int modreturn)
277 VALUE_PAIR *vp = NULL;
280 rt = rt; /* -Wunused */
282 if (lt == T_BARE_WORD) {
284 * Maybe check the last return code.
286 if (token == T_OP_CMP_TRUE) {
290 * Looks like a return code, treat is as such.
292 isreturn = fr_str2int(modreturn_table, pleft, -1);
293 if (isreturn != -1) {
294 *presult = (modreturn == isreturn);
300 * Bare words on the left can be attribute names.
302 if (radius_get_vp(request, pleft, &vp)) {
306 * VP exists, and that's all we're looking for.
308 if (token == T_OP_CMP_TRUE) {
309 *presult = (vp != NULL);
314 DEBUG2(" (Attribute %s was not found)",
321 * Regex comparisons treat everything as
324 if ((token == T_OP_REG_EQ) ||
325 (token == T_OP_REG_NE)) {
326 vp_prints_value(buffer, sizeof(buffer), vp, 0);
332 memcpy(&myvp, vp, sizeof(myvp));
333 if (!pairparsevalue(&myvp, pright)) {
334 DEBUG2("Failed parsing \"%s\": %s",
335 pright, librad_errstr);
339 myvp.operator = token;
340 *presult = paircmp(&myvp, vp);
342 } /* else it's not a attribute in the dictionary */
351 if (!all_digits(pright)) {
352 DEBUG2(" (Right field is not a number at: %s)", pright);
356 if (!all_digits(pleft)) {
357 DEBUG2(" (Left field is not a number at: %s)", pleft);
364 lint = rint = 0; /* quiet the compiler */
371 * Check for truth or falsehood.
373 if (all_digits(pleft)) {
375 result = (lint != 0);
378 result = (*pleft != '\0');
384 result = (strcmp(pleft, pright) == 0);
388 result = (strcmp(pleft, pright) != 0);
392 result = (lint >= rint);
396 result = (lint > rint);
400 result = (lint <= rint);
404 result = (lint < rint);
411 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
414 * Include substring matches.
416 regcomp(®, pright, cflags);
417 compare = regexec(®, pleft,
418 REQUEST_MAX_REGEX + 1,
423 * Add new %{0}, %{1}, etc.
425 if (compare == 0) for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
428 free(request_data_get(request, request,
429 REQUEST_DATA_REGEX | i));
432 * We MAY have %{2} without %{1}.
434 if (rxmatch[i].rm_so == -1) continue;
437 * Copy substring into buffer.
439 memcpy(buffer, pleft + rxmatch[i].rm_so,
440 rxmatch[i].rm_eo - rxmatch[i].rm_so);
441 buffer[rxmatch[i].rm_eo - rxmatch[i].rm_so] = '\0';
444 * Copy substring, and add it to
447 * Note that we don't check
448 * for out of memory, which is
449 * the only error we can get...
452 request_data_add(request, request,
453 REQUEST_DATA_REGEX | i,
456 result = (compare == 0);
463 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
466 * Include substring matches.
468 regcomp(®, pright, cflags);
469 compare = regexec(®, pleft,
470 REQUEST_MAX_REGEX + 1,
474 result = (compare != 0);
480 DEBUG4(">>> NOT IMPLEMENTED %d", token);
489 int radius_evaluate_condition(REQUEST *request, int modreturn, int depth,
490 const char **ptr, int evaluate_it, int *presult)
492 int found_condition = FALSE;
495 int evaluate_next_condition = evaluate_it;
496 const char *p = *ptr;
497 const char *q, *start;
498 FR_TOKEN token, lt, rt;
499 char left[1024], right[1024], comp[4];
500 const char *pleft, *pright;
501 char xleft[1024], xright[1024];
506 if (!ptr || !*ptr || (depth >= 64)) {
507 radlog(L_ERR, "Internal sanity check failed in evaluate condition");
512 while ((*p == ' ') || (*p == '\t')) p++;
515 DEBUG4(">>> INVERT");
521 * It's a subcondition.
524 const char *end = p + 1;
527 * Evaluate the condition, bailing out on
530 DEBUG4(">>> CALLING EVALUATE %s", end);
531 if (!radius_evaluate_condition(request, modreturn,
533 evaluate_next_condition,
538 if (invert && evaluate_next_condition) {
539 DEBUG2("%.*s Converting !%s -> %s",
541 (result != FALSE) ? "TRUE" : "FALSE",
542 (result == FALSE) ? "TRUE" : "FALSE");
545 result = (result == FALSE);
550 * Start from the end of the previous
554 DEBUG4(">>> EVALUATE RETURNED ::%s::", end);
556 if (!((*p == ')') || (*p == '!') ||
557 ((p[0] == '&') && (p[1] == '&')) ||
558 ((p[0] == '|') && (p[1] == '|')))) {
560 radlog(L_ERR, "Parse error in condition at: %s", p);
563 if (*p == ')') p++; /* skip it */
564 found_condition = TRUE;
566 while ((*p == ' ') || (*p == '\t')) p++;
572 DEBUG4(">>> AT EOL");
578 * (A && B) means "evaluate B
579 * only if A was true"
581 } else if ((p[0] == '&') && (p[1] == '&')) {
582 if (result == TRUE) {
583 evaluate_next_condition = evaluate_it;
585 evaluate_next_condition = FALSE;
590 * (A || B) means "evaluate B
591 * only if A was false"
593 } else if ((p[0] == '|') && (p[1] == '|')) {
594 if (result == FALSE) {
595 evaluate_next_condition = evaluate_it;
597 evaluate_next_condition = FALSE;
601 } else if (*p == ')') {
602 DEBUG4(">>> CLOSING BRACE");
611 radlog(L_ERR, "Unexpected trailing text at: %s", p);
614 } /* else it wasn't an opening brace */
616 while ((*p == ' ') || (*p == '\t')) p++;
619 * More conditions, keep going.
621 if ((*p == '(') || (p[0] == '!')) continue;
623 DEBUG4(">>> LOOKING AT %s", p);
627 * Look for common errors.
629 if ((p[0] == '%') && (p[1] == '{')) {
630 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
635 * Look for word == value
637 lt = gettoken(&p, left, sizeof(left));
638 if ((lt != T_BARE_WORD) &&
639 (lt != T_DOUBLE_QUOTED_STRING) &&
640 (lt != T_SINGLE_QUOTED_STRING) &&
641 (lt != T_BACK_QUOTED_STRING)) {
642 radlog(L_ERR, "Expected string or numbers at: %s", p);
647 if (evaluate_next_condition) {
648 pleft = expand_string(xleft, sizeof(xleft), request,
651 radlog(L_ERR, "Failed expanding string at: %s",
658 * Peek ahead. Maybe it's just a check for
659 * existence. If so, there shouldn't be anything
663 while ((*q == ' ') || (*q == '\t')) q++;
668 if (!*q || (*q == ')') ||
669 ((*q == '!') && (q[1] != '=') && (q[1] != '~')) ||
670 ((q[0] == '&') && (q[1] == '&')) ||
671 ((q[0] == '|') && (q[1] == '|'))) {
675 token = T_OP_CMP_TRUE;
682 * Else it's a full "foo == bar" thingy.
684 token = gettoken(&p, comp, sizeof(comp));
685 if ((token < T_OP_NE) || (token > T_OP_CMP_EQ) ||
686 (token == T_OP_CMP_TRUE) ||
687 (token == T_OP_CMP_FALSE)) {
688 radlog(L_ERR, "Expected comparison at: %s", comp);
693 * Look for common errors.
695 if ((p[0] == '%') && (p[1] == '{')) {
696 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
704 if ((token == T_OP_REG_EQ) ||
705 (token == T_OP_REG_NE)) {
706 rt = getregex(&p, right, sizeof(right), &cflags);
707 if (rt != T_DOUBLE_QUOTED_STRING) {
708 radlog(L_ERR, "Expected regular expression at: %s", p);
713 rt = gettoken(&p, right, sizeof(right));
715 if ((rt != T_BARE_WORD) &&
716 (rt != T_DOUBLE_QUOTED_STRING) &&
717 (rt != T_SINGLE_QUOTED_STRING) &&
718 (rt != T_BACK_QUOTED_STRING)) {
719 radlog(L_ERR, "Expected string or numbers at: %s", p);
724 if (evaluate_next_condition) {
725 pright = expand_string(xright, sizeof(xright), request,
728 radlog(L_ERR, "Failed expanding string at: %s",
734 DEBUG4(">>> %d:%s %d %d:%s",
735 lt, pleft, token, rt, pright);
738 if (evaluate_next_condition) {
742 if (!radius_do_cmp(request, &result, lt, pleft, token,
743 rt, pright, cflags, modreturn)) {
747 DEBUG2("%.*s Evaluating %s(%.*s) -> %s",
749 invert ? "!" : "", p - start, start,
750 (result != FALSE) ? "TRUE" : "FALSE");
752 DEBUG4(">>> GOT result %d", result);
755 * Not evaluating it. We may be just
758 } else if (request) {
759 DEBUG2("%.*s Skipping %s(%.*s)",
761 invert ? "!" : "", p - start, start);
765 DEBUG4(">>> INVERTING result");
766 result = (result == FALSE);
773 DEBUG4(">>> EVALUATE %d ::%s::",
774 evaluate_next_condition, p);
776 while ((*p == ' ') || (*p == '\t')) p++;
779 * Closing brace or EOL, return.
781 if (!*p || (*p == ')') ||
782 ((*p == '!') && (p[1] != '=') && (p[1] != '~')) ||
783 ((p[0] == '&') && (p[1] == '&')) ||
784 ((p[0] == '|') && (p[1] == '|'))) {
785 DEBUG4(">>> AT EOL2a");
787 if (evaluate_next_condition) *presult = result;
790 } /* loop over the input condition */
792 DEBUG4(">>> AT EOL2b");
794 if (evaluate_next_condition) *presult = result;
799 static void fix_up(REQUEST *request)
803 request->username = NULL;
804 request->password = NULL;
806 for (vp = request->packet->vps; vp != NULL; vp = vp->next) {
807 if ((vp->attribute == PW_USER_NAME) &&
808 !request->username) {
809 request->username = vp;
811 } else if (vp->attribute == PW_STRIPPED_USER_NAME) {
812 request->username = vp;
814 } else if (vp->attribute == PW_USER_PASSWORD) {
815 request->password = vp;
822 * The pairmove() function in src/lib/valuepair.c does all sorts of
823 * extra magic that we don't want here.
825 * FIXME: integrate this with the code calling it, so that we
826 * only paircopy() those attributes that we're really going to
829 void radius_pairmove(REQUEST *request, VALUE_PAIR **to, VALUE_PAIR *from)
831 int i, j, count, from_count, to_count, tailto;
832 VALUE_PAIR *vp, *next, **last;
833 VALUE_PAIR **from_list, **to_list;
837 * Set up arrays for editing, to remove some of the
838 * O(N^2) dependencies. This also makes it easier to
839 * insert and remove attributes.
841 * It also means that the operators apply ONLY to the
842 * attributes in the original list. With the previous
843 * implementation of pairmove(), adding two attributes
844 * via "+=" and then "=" would mean that the second one
845 * wasn't added, because of the existence of the first
846 * one in the "to" list. This implementation doesn't
849 * Also, the previous implementation did NOT implement
850 * "-=" correctly. If two of the same attributes existed
851 * in the "to" list, and you tried to subtract something
852 * matching the *second* value, then the pairdelete()
853 * function was called, and the *all* attributes of that
854 * number were deleted. With this implementation, only
855 * the matching attributes are deleted.
858 for (vp = from; vp != NULL; vp = vp->next) count++;
859 from_list = rad_malloc(sizeof(*from_list) * count);
861 for (vp = *to; vp != NULL; vp = vp->next) count++;
862 to_list = rad_malloc(sizeof(*to_list) * count);
865 * Move the lists to the arrays, and break the list
869 for (vp = from; vp != NULL; vp = next) {
871 from_list[from_count++] = vp;
876 for (vp = *to; vp != NULL; vp = next) {
878 to_list[to_count++] = vp;
882 edited = rad_malloc(sizeof(*edited) * to_count);
883 memset(edited, 0, sizeof(*edited) * to_count);
885 DEBUG4("::: FROM %d TO %d MAX %d", from_count, to_count, count);
888 * Now that we have the lists initialized, start working
891 for (i = 0; i < from_count; i++) {
894 DEBUG4("::: Examining %s", from_list[i]->name);
897 * Attribute should be appended, OR the "to" list
898 * is empty, and we're supposed to replace or
899 * "add if not existing".
901 if (from_list[i]->operator == T_OP_ADD) goto append;
904 for (j = 0; j < to_count; j++) {
905 if (edited[j]) continue;
908 * Attributes aren't the same, skip them.
910 if (from_list[i]->attribute != to_list[j]->attribute) {
915 * We don't use a "switch" statement here
916 * because we want to break out of the
917 * "for" loop over 'j' in most cases.
921 * Over-write the FIRST instance of the
922 * matching attribute name. We free the
923 * one in the "to" list, and move over
924 * the one in the "from" list.
926 if (from_list[i]->operator == T_OP_SET) {
927 DEBUG4("::: OVERWRITING %s FROM %d TO %d",
928 to_list[j]->name, i, j);
929 pairfree(&to_list[j]);
930 to_list[j] = from_list[i];
937 * Add the attribute only if it does not
938 * exist... but it exists, so we stop
941 if (from_list[i]->operator == T_OP_EQ) {
947 * Delete all matching attributes from
950 if ((from_list[i]->operator == T_OP_SUB) ||
951 (from_list[i]->operator == T_OP_CMP_EQ) ||
952 (from_list[i]->operator == T_OP_LE) ||
953 (from_list[i]->operator == T_OP_GE)) {
955 int old_op = from_list[i]->operator;
958 * Check for equality.
960 from_list[i]->operator = T_OP_CMP_EQ;
963 * If equal, delete the one in
966 rcode = radius_compare_vps(NULL, from_list[i],
969 * We may want to do more
970 * subtractions, so we re-set the
971 * operator back to it's original
974 from_list[i]->operator = old_op;
978 if (rcode != 0) goto delete;
984 DEBUG4("::: DELETING %s FROM %d TO %d",
985 from_list[i]->name, i, j);
986 pairfree(&to_list[j]);
992 * Enforce <=. If it's
997 DEBUG4("::: REPLACING %s FROM %d TO %d",
998 from_list[i]->name, i, j);
999 pairfree(&to_list[j]);
1000 to_list[j] = from_list[i];
1001 from_list[i] = NULL;
1008 DEBUG4("::: REPLACING %s FROM %d TO %d",
1009 from_list[i]->name, i, j);
1010 pairfree(&to_list[j]);
1011 to_list[j] = from_list[i];
1012 from_list[i] = NULL;
1021 rad_assert(0 == 1); /* panic! */
1025 * We were asked to add it if it didn't exist,
1026 * and it doesn't exist. Move it over to the
1027 * tail of the "to" list, UNLESS it was already
1028 * moved by another operator.
1030 if (!found && from_list[i]) {
1031 if ((from_list[i]->operator == T_OP_EQ) ||
1032 (from_list[i]->operator == T_OP_LE) ||
1033 (from_list[i]->operator == T_OP_GE) ||
1034 (from_list[i]->operator == T_OP_SET)) {
1036 DEBUG4("::: APPENDING %s FROM %d TO %d",
1037 from_list[i]->name, i, tailto);
1038 to_list[tailto++] = from_list[i];
1039 from_list[i] = NULL;
1045 * Delete attributes in the "from" list.
1047 for (i = 0; i < from_count; i++) {
1048 if (!from_list[i]) continue;
1050 pairfree(&from_list[i]);
1054 DEBUG4("::: TO in %d out %d", to_count, tailto);
1057 * Re-chain the "to" list.
1062 for (i = 0; i < tailto; i++) {
1063 if (!to_list[i]) continue;
1065 DEBUG4("::: to[%d] = %s", i, to_list[i]->name);
1068 * Mash the operator to a simple '='. The
1069 * operators in the "to" list aren't used for
1070 * anything. BUT they're used in the "detail"
1071 * file and debug output, where we don't want to
1072 * see the operators.
1074 to_list[i]->operator = T_OP_EQ;
1077 last = &(*last)->next;
1081 * Fix dumb cache issues
1083 if (to == &request->packet->vps) {
1085 } else if (request->parent && (to == &request->parent->packet->vps)) {
1086 fix_up(request->parent);
1095 * Copied shamelessly from conffile.c, to simplify the API for
1098 typedef enum conf_type {
1099 CONF_ITEM_INVALID = 0,
1106 struct conf_item *next;
1107 struct conf_part *parent;
1109 const char *filename;
1110 CONF_ITEM_TYPE type;
1117 FR_TOKEN value_type;
1121 * Add attributes to a list.
1123 int radius_update_attrlist(REQUEST *request, CONF_SECTION *cs,
1124 VALUE_PAIR *input_vps, const char *name)
1127 VALUE_PAIR *newlist, *vp;
1128 VALUE_PAIR **output_vps = NULL;
1129 REQUEST *request_vps = request;
1131 if (!request || !cs) return RLM_MODULE_INVALID;
1134 * If we are an inner tunnel session, permit the
1135 * policy to update the outer lists directly.
1137 if (strncmp(name, "outer.", 6) == 0) {
1138 if (!request->parent) return RLM_MODULE_NOOP;
1140 request_vps = request->parent;
1144 if (strcmp(name, "request") == 0) {
1145 output_vps = &request_vps->packet->vps;
1147 } else if (strcmp(name, "reply") == 0) {
1148 output_vps = &request_vps->reply->vps;
1150 } else if (strcmp(name, "proxy-request") == 0) {
1151 if (request->proxy) output_vps = &request_vps->proxy->vps;
1153 } else if (strcmp(name, "proxy-reply") == 0) {
1154 if (request->proxy_reply) output_vps = &request->proxy_reply->vps;
1156 } else if (strcmp(name, "config") == 0) {
1157 output_vps = &request_vps->config_items;
1159 } else if (strcmp(name, "control") == 0) {
1160 output_vps = &request_vps->config_items;
1163 return RLM_MODULE_INVALID;
1166 if (!output_vps) return RLM_MODULE_NOOP; /* didn't update the list */
1168 newlist = paircopy(input_vps);
1170 DEBUG2("Out of memory");
1171 return RLM_MODULE_FAIL;
1175 for (ci=cf_item_find_next(cs, NULL);
1177 ci=cf_item_find_next(cs, ci)) {
1181 * This should never happen.
1183 if (cf_item_is_section(ci)) {
1185 return RLM_MODULE_INVALID;
1188 cp = cf_itemtopair(ci);
1191 * The VP && CF lists should be in sync. If they're
1194 if (vp->flags.do_xlat) {
1198 value = expand_string(buffer, sizeof(buffer), request,
1199 cp->value_type, cp->value);
1202 return RLM_MODULE_INVALID;
1205 if (!pairparsevalue(vp, value)) {
1206 DEBUG2("ERROR: Failed parsing value \"%s\" for attribute %s: %s",
1207 value, vp->name, librad_errstr);
1209 return RLM_MODULE_FAIL;
1211 vp->flags.do_xlat = 0;
1216 radius_pairmove(request, output_vps, newlist);
1218 return RLM_MODULE_UPDATED;