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;
281 cflags = cflags; /* -Wunused */
284 rt = rt; /* -Wunused */
286 if (lt == T_BARE_WORD) {
288 * Maybe check the last return code.
290 if (token == T_OP_CMP_TRUE) {
294 * Looks like a return code, treat is as such.
296 isreturn = fr_str2int(modreturn_table, pleft, -1);
297 if (isreturn != -1) {
298 *presult = (modreturn == isreturn);
304 * Bare words on the left can be attribute names.
306 if (radius_get_vp(request, pleft, &vp)) {
310 * VP exists, and that's all we're looking for.
312 if (token == T_OP_CMP_TRUE) {
313 *presult = (vp != NULL);
318 DEBUG2(" (Attribute %s was not found)",
325 * Regex comparisons treat everything as
328 if ((token == T_OP_REG_EQ) ||
329 (token == T_OP_REG_NE)) {
330 vp_prints_value(buffer, sizeof(buffer), vp, 0);
336 memcpy(&myvp, vp, sizeof(myvp));
337 if (!pairparsevalue(&myvp, pright)) {
338 DEBUG2("Failed parsing \"%s\": %s",
339 pright, librad_errstr);
343 myvp.operator = token;
344 *presult = paircmp(&myvp, vp);
346 } /* else it's not a attribute in the dictionary */
357 if (!all_digits(pright)) {
358 DEBUG2(" (Right field is not a number at: %s)", pright);
362 if (!all_digits(pleft)) {
363 DEBUG2(" (Left field is not a number at: %s)", pleft);
370 lint = rint = 0; /* quiet the compiler */
377 * Check for truth or falsehood.
379 if (all_digits(pleft)) {
381 result = (lint != 0);
384 result = (*pleft != '\0');
390 result = (strcmp(pleft, pright) == 0);
394 result = (strcmp(pleft, pright) != 0);
398 result = (lint >= rint);
402 result = (lint > rint);
406 result = (lint <= rint);
410 result = (lint < rint);
417 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
420 * Include substring matches.
422 regcomp(®, pright, cflags);
423 compare = regexec(®, pleft,
424 REQUEST_MAX_REGEX + 1,
429 * Add new %{0}, %{1}, etc.
431 if (compare == 0) for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
434 free(request_data_get(request, request,
435 REQUEST_DATA_REGEX | i));
438 * We MAY have %{2} without %{1}.
440 if (rxmatch[i].rm_so == -1) continue;
443 * Copy substring into buffer.
445 memcpy(buffer, pleft + rxmatch[i].rm_so,
446 rxmatch[i].rm_eo - rxmatch[i].rm_so);
447 buffer[rxmatch[i].rm_eo - rxmatch[i].rm_so] = '\0';
450 * Copy substring, and add it to
453 * Note that we don't check
454 * for out of memory, which is
455 * the only error we can get...
458 request_data_add(request, request,
459 REQUEST_DATA_REGEX | i,
462 result = (compare == 0);
469 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
472 * Include substring matches.
474 regcomp(®, pright, cflags);
475 compare = regexec(®, pleft,
476 REQUEST_MAX_REGEX + 1,
480 result = (compare != 0);
486 DEBUG4(">>> NOT IMPLEMENTED %d", token);
495 int radius_evaluate_condition(REQUEST *request, int modreturn, int depth,
496 const char **ptr, int evaluate_it, int *presult)
498 int found_condition = FALSE;
501 int evaluate_next_condition = evaluate_it;
502 const char *p = *ptr;
503 const char *q, *start;
504 FR_TOKEN token, lt, rt;
505 char left[1024], right[1024], comp[4];
506 const char *pleft, *pright;
507 char xleft[1024], xright[1024];
510 if (!ptr || !*ptr || (depth >= 64)) {
511 radlog(L_ERR, "Internal sanity check failed in evaluate condition");
516 while ((*p == ' ') || (*p == '\t')) p++;
519 DEBUG4(">>> INVERT");
525 * It's a subcondition.
528 const char *end = p + 1;
531 * Evaluate the condition, bailing out on
534 DEBUG4(">>> CALLING EVALUATE %s", end);
535 if (!radius_evaluate_condition(request, modreturn,
537 evaluate_next_condition,
542 if (invert && evaluate_next_condition) {
543 DEBUG2("%.*s Converting !%s -> %s",
545 (result != FALSE) ? "TRUE" : "FALSE",
546 (result == FALSE) ? "TRUE" : "FALSE");
549 result = (result == FALSE);
554 * Start from the end of the previous
558 DEBUG4(">>> EVALUATE RETURNED ::%s::", end);
560 if (!((*p == ')') || (*p == '!') ||
561 ((p[0] == '&') && (p[1] == '&')) ||
562 ((p[0] == '|') && (p[1] == '|')))) {
564 radlog(L_ERR, "Parse error in condition at: %s", p);
567 if (*p == ')') p++; /* skip it */
568 found_condition = TRUE;
570 while ((*p == ' ') || (*p == '\t')) p++;
576 DEBUG4(">>> AT EOL");
582 * (A && B) means "evaluate B
583 * only if A was true"
585 } else if ((p[0] == '&') && (p[1] == '&')) {
586 if (result == TRUE) {
587 evaluate_next_condition = evaluate_it;
589 evaluate_next_condition = FALSE;
594 * (A || B) means "evaluate B
595 * only if A was false"
597 } else if ((p[0] == '|') && (p[1] == '|')) {
598 if (result == FALSE) {
599 evaluate_next_condition = evaluate_it;
601 evaluate_next_condition = FALSE;
605 } else if (*p == ')') {
606 DEBUG4(">>> CLOSING BRACE");
615 radlog(L_ERR, "Unexpected trailing text at: %s", p);
618 } /* else it wasn't an opening brace */
620 while ((*p == ' ') || (*p == '\t')) p++;
623 * More conditions, keep going.
625 if ((*p == '(') || (p[0] == '!')) continue;
627 DEBUG4(">>> LOOKING AT %s", p);
631 * Look for common errors.
633 if ((p[0] == '%') && (p[1] == '{')) {
634 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
639 * Look for word == value
641 lt = gettoken(&p, left, sizeof(left));
642 if ((lt != T_BARE_WORD) &&
643 (lt != T_DOUBLE_QUOTED_STRING) &&
644 (lt != T_SINGLE_QUOTED_STRING) &&
645 (lt != T_BACK_QUOTED_STRING)) {
646 radlog(L_ERR, "Expected string or numbers at: %s", p);
651 if (evaluate_next_condition) {
652 pleft = expand_string(xleft, sizeof(xleft), request,
655 radlog(L_ERR, "Failed expanding string at: %s",
662 * Peek ahead. Maybe it's just a check for
663 * existence. If so, there shouldn't be anything
667 while ((*q == ' ') || (*q == '\t')) q++;
672 if (!*q || (*q == ')') ||
673 ((*q == '!') && (q[1] != '=') && (q[1] != '~')) ||
674 ((q[0] == '&') && (q[1] == '&')) ||
675 ((q[0] == '|') && (q[1] == '|'))) {
679 token = T_OP_CMP_TRUE;
686 * Else it's a full "foo == bar" thingy.
688 token = gettoken(&p, comp, sizeof(comp));
689 if ((token < T_OP_NE) || (token > T_OP_CMP_EQ) ||
690 (token == T_OP_CMP_TRUE) ||
691 (token == T_OP_CMP_FALSE)) {
692 radlog(L_ERR, "Expected comparison at: %s", comp);
697 * Look for common errors.
699 if ((p[0] == '%') && (p[1] == '{')) {
700 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
708 if ((token == T_OP_REG_EQ) ||
709 (token == T_OP_REG_NE)) {
710 rt = getregex(&p, right, sizeof(right), &cflags);
711 if (rt != T_DOUBLE_QUOTED_STRING) {
712 radlog(L_ERR, "Expected regular expression at: %s", p);
717 rt = gettoken(&p, right, sizeof(right));
719 if ((rt != T_BARE_WORD) &&
720 (rt != T_DOUBLE_QUOTED_STRING) &&
721 (rt != T_SINGLE_QUOTED_STRING) &&
722 (rt != T_BACK_QUOTED_STRING)) {
723 radlog(L_ERR, "Expected string or numbers at: %s", p);
728 if (evaluate_next_condition) {
729 pright = expand_string(xright, sizeof(xright), request,
732 radlog(L_ERR, "Failed expanding string at: %s",
738 DEBUG4(">>> %d:%s %d %d:%s",
739 lt, pleft, token, rt, pright);
742 if (evaluate_next_condition) {
746 if (!radius_do_cmp(request, &result, lt, pleft, token,
747 rt, pright, cflags, modreturn)) {
751 DEBUG2("%.*s Evaluating %s(%.*s) -> %s",
753 invert ? "!" : "", p - start, start,
754 (result != FALSE) ? "TRUE" : "FALSE");
756 DEBUG4(">>> GOT result %d", result);
759 * Not evaluating it. We may be just
762 } else if (request) {
763 DEBUG2("%.*s Skipping %s(%.*s)",
765 invert ? "!" : "", p - start, start);
769 DEBUG4(">>> INVERTING result");
770 result = (result == FALSE);
777 DEBUG4(">>> EVALUATE %d ::%s::",
778 evaluate_next_condition, p);
780 while ((*p == ' ') || (*p == '\t')) p++;
783 * Closing brace or EOL, return.
785 if (!*p || (*p == ')') ||
786 ((*p == '!') && (p[1] != '=') && (p[1] != '~')) ||
787 ((p[0] == '&') && (p[1] == '&')) ||
788 ((p[0] == '|') && (p[1] == '|'))) {
789 DEBUG4(">>> AT EOL2a");
791 if (evaluate_next_condition) *presult = result;
794 } /* loop over the input condition */
796 DEBUG4(">>> AT EOL2b");
798 if (evaluate_next_condition) *presult = result;
803 static void fix_up(REQUEST *request)
807 request->username = NULL;
808 request->password = NULL;
810 for (vp = request->packet->vps; vp != NULL; vp = vp->next) {
811 if ((vp->attribute == PW_USER_NAME) &&
812 !request->username) {
813 request->username = vp;
815 } else if (vp->attribute == PW_STRIPPED_USER_NAME) {
816 request->username = vp;
818 } else if (vp->attribute == PW_USER_PASSWORD) {
819 request->password = vp;
826 * The pairmove() function in src/lib/valuepair.c does all sorts of
827 * extra magic that we don't want here.
829 * FIXME: integrate this with the code calling it, so that we
830 * only paircopy() those attributes that we're really going to
833 void radius_pairmove(REQUEST *request, VALUE_PAIR **to, VALUE_PAIR *from)
835 int i, j, count, from_count, to_count, tailto;
836 VALUE_PAIR *vp, *next, **last;
837 VALUE_PAIR **from_list, **to_list;
841 * Set up arrays for editing, to remove some of the
842 * O(N^2) dependencies. This also makes it easier to
843 * insert and remove attributes.
845 * It also means that the operators apply ONLY to the
846 * attributes in the original list. With the previous
847 * implementation of pairmove(), adding two attributes
848 * via "+=" and then "=" would mean that the second one
849 * wasn't added, because of the existence of the first
850 * one in the "to" list. This implementation doesn't
853 * Also, the previous implementation did NOT implement
854 * "-=" correctly. If two of the same attributes existed
855 * in the "to" list, and you tried to subtract something
856 * matching the *second* value, then the pairdelete()
857 * function was called, and the *all* attributes of that
858 * number were deleted. With this implementation, only
859 * the matching attributes are deleted.
862 for (vp = from; vp != NULL; vp = vp->next) count++;
863 from_list = rad_malloc(sizeof(*from_list) * count);
865 for (vp = *to; vp != NULL; vp = vp->next) count++;
866 to_list = rad_malloc(sizeof(*to_list) * count);
869 * Move the lists to the arrays, and break the list
873 for (vp = from; vp != NULL; vp = next) {
875 from_list[from_count++] = vp;
880 for (vp = *to; vp != NULL; vp = next) {
882 to_list[to_count++] = vp;
886 edited = rad_malloc(sizeof(*edited) * to_count);
887 memset(edited, 0, sizeof(*edited) * to_count);
889 DEBUG4("::: FROM %d TO %d MAX %d", from_count, to_count, count);
892 * Now that we have the lists initialized, start working
895 for (i = 0; i < from_count; i++) {
898 DEBUG4("::: Examining %s", from_list[i]->name);
901 * Attribute should be appended, OR the "to" list
902 * is empty, and we're supposed to replace or
903 * "add if not existing".
905 if (from_list[i]->operator == T_OP_ADD) goto append;
908 for (j = 0; j < to_count; j++) {
909 if (edited[j]) continue;
912 * Attributes aren't the same, skip them.
914 if (from_list[i]->attribute != to_list[j]->attribute) {
919 * We don't use a "switch" statement here
920 * because we want to break out of the
921 * "for" loop over 'j' in most cases.
925 * Over-write the FIRST instance of the
926 * matching attribute name. We free the
927 * one in the "to" list, and move over
928 * the one in the "from" list.
930 if (from_list[i]->operator == T_OP_SET) {
931 DEBUG4("::: OVERWRITING %s FROM %d TO %d",
932 to_list[j]->name, i, j);
933 pairfree(&to_list[j]);
934 to_list[j] = from_list[i];
941 * Add the attribute only if it does not
942 * exist... but it exists, so we stop
945 if (from_list[i]->operator == T_OP_EQ) {
951 * Delete all matching attributes from
954 if ((from_list[i]->operator == T_OP_SUB) ||
955 (from_list[i]->operator == T_OP_CMP_EQ) ||
956 (from_list[i]->operator == T_OP_LE) ||
957 (from_list[i]->operator == T_OP_GE)) {
959 int old_op = from_list[i]->operator;
962 * Check for equality.
964 from_list[i]->operator = T_OP_CMP_EQ;
967 * If equal, delete the one in
970 rcode = radius_compare_vps(NULL, from_list[i],
973 * We may want to do more
974 * subtractions, so we re-set the
975 * operator back to it's original
978 from_list[i]->operator = old_op;
982 if (rcode != 0) goto delete;
988 DEBUG4("::: DELETING %s FROM %d TO %d",
989 from_list[i]->name, i, j);
990 pairfree(&to_list[j]);
996 * Enforce <=. If it's
1001 DEBUG4("::: REPLACING %s FROM %d TO %d",
1002 from_list[i]->name, i, j);
1003 pairfree(&to_list[j]);
1004 to_list[j] = from_list[i];
1005 from_list[i] = NULL;
1012 DEBUG4("::: REPLACING %s FROM %d TO %d",
1013 from_list[i]->name, i, j);
1014 pairfree(&to_list[j]);
1015 to_list[j] = from_list[i];
1016 from_list[i] = NULL;
1025 rad_assert(0 == 1); /* panic! */
1029 * We were asked to add it if it didn't exist,
1030 * and it doesn't exist. Move it over to the
1031 * tail of the "to" list, UNLESS it was already
1032 * moved by another operator.
1034 if (!found && from_list[i]) {
1035 if ((from_list[i]->operator == T_OP_EQ) ||
1036 (from_list[i]->operator == T_OP_LE) ||
1037 (from_list[i]->operator == T_OP_GE) ||
1038 (from_list[i]->operator == T_OP_SET)) {
1040 DEBUG4("::: APPENDING %s FROM %d TO %d",
1041 from_list[i]->name, i, tailto);
1042 to_list[tailto++] = from_list[i];
1043 from_list[i] = NULL;
1049 * Delete attributes in the "from" list.
1051 for (i = 0; i < from_count; i++) {
1052 if (!from_list[i]) continue;
1054 pairfree(&from_list[i]);
1058 DEBUG4("::: TO in %d out %d", to_count, tailto);
1061 * Re-chain the "to" list.
1066 for (i = 0; i < tailto; i++) {
1067 if (!to_list[i]) continue;
1069 DEBUG4("::: to[%d] = %s", i, to_list[i]->name);
1072 * Mash the operator to a simple '='. The
1073 * operators in the "to" list aren't used for
1074 * anything. BUT they're used in the "detail"
1075 * file and debug output, where we don't want to
1076 * see the operators.
1078 to_list[i]->operator = T_OP_EQ;
1081 last = &(*last)->next;
1085 * Fix dumb cache issues
1087 if (to == &request->packet->vps) {
1089 } else if (request->parent && (to == &request->parent->packet->vps)) {
1090 fix_up(request->parent);
1099 * Copied shamelessly from conffile.c, to simplify the API for
1102 typedef enum conf_type {
1103 CONF_ITEM_INVALID = 0,
1110 struct conf_item *next;
1111 struct conf_part *parent;
1113 const char *filename;
1114 CONF_ITEM_TYPE type;
1121 FR_TOKEN value_type;
1125 * Add attributes to a list.
1127 int radius_update_attrlist(REQUEST *request, CONF_SECTION *cs,
1128 VALUE_PAIR *input_vps, const char *name)
1131 VALUE_PAIR *newlist, *vp;
1132 VALUE_PAIR **output_vps = NULL;
1133 REQUEST *request_vps = request;
1135 if (!request || !cs) return RLM_MODULE_INVALID;
1138 * If we are an inner tunnel session, permit the
1139 * policy to update the outer lists directly.
1141 if (strncmp(name, "outer.", 6) == 0) {
1142 if (!request->parent) return RLM_MODULE_NOOP;
1144 request_vps = request->parent;
1148 if (strcmp(name, "request") == 0) {
1149 output_vps = &request_vps->packet->vps;
1151 } else if (strcmp(name, "reply") == 0) {
1152 output_vps = &request_vps->reply->vps;
1154 } else if (strcmp(name, "proxy-request") == 0) {
1155 if (request->proxy) output_vps = &request_vps->proxy->vps;
1157 } else if (strcmp(name, "proxy-reply") == 0) {
1158 if (request->proxy_reply) output_vps = &request->proxy_reply->vps;
1160 } else if (strcmp(name, "config") == 0) {
1161 output_vps = &request_vps->config_items;
1163 } else if (strcmp(name, "control") == 0) {
1164 output_vps = &request_vps->config_items;
1167 return RLM_MODULE_INVALID;
1170 if (!output_vps) return RLM_MODULE_NOOP; /* didn't update the list */
1172 newlist = paircopy(input_vps);
1174 DEBUG2("Out of memory");
1175 return RLM_MODULE_FAIL;
1179 for (ci=cf_item_find_next(cs, NULL);
1181 ci=cf_item_find_next(cs, ci)) {
1185 * This should never happen.
1187 if (cf_item_is_section(ci)) {
1189 return RLM_MODULE_INVALID;
1192 cp = cf_itemtopair(ci);
1195 * The VP && CF lists should be in sync. If they're
1198 if (vp->flags.do_xlat) {
1202 value = expand_string(buffer, sizeof(buffer), request,
1203 cp->value_type, cp->value);
1206 return RLM_MODULE_INVALID;
1209 if (!pairparsevalue(vp, value)) {
1210 DEBUG2("ERROR: Failed parsing value \"%s\" for attribute %s: %s",
1211 value, vp->name, librad_errstr);
1213 return RLM_MODULE_FAIL;
1215 vp->flags.do_xlat = 0;
1220 radius_pairmove(request, output_vps, newlist);
1222 return RLM_MODULE_UPDATED;