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++) {
105 case T_DOUBLE_QUOTED_STRING:
106 if (!strchr(value, '%')) return value;
108 radius_xlat(buffer, sizeof_buffer, value, request, NULL);
116 static LRAD_TOKEN getregex(char **ptr, char *buffer, size_t buflen, int *pcflags)
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)) {
195 static const LRAD_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 },
208 int radius_evaluate_condition(REQUEST *request, int modreturn, int depth,
209 const char **ptr, int evaluate_it, int *presult)
211 int found_condition = FALSE;
214 int evaluate_next_condition = evaluate_it;
215 const char *p = *ptr;
216 const char *q, *start;
217 LRAD_TOKEN token, lt, rt;
218 char left[1024], right[1024], comp[4];
219 const char *pleft, *pright;
220 char xleft[1024], xright[1024];
226 if (!ptr || !*ptr || (depth >= 64)) {
227 radlog(L_ERR, "Internal sanity check failed in evaluate condition");
232 while ((*p == ' ') || (*p == '\t')) p++;
235 DEBUG4(">>> INVERT");
241 * It's a subcondition.
244 const char *end = p + 1;
247 * Evaluate the condition, bailing out on
250 DEBUG4(">>> CALLING EVALUATE %s", end);
251 if (!radius_evaluate_condition(request, modreturn,
253 evaluate_next_condition,
258 if (invert && evaluate_next_condition) {
259 DEBUG2("%.*s Converting !%s -> %s",
261 (result != FALSE) ? "TRUE" : "FALSE",
262 (result == FALSE) ? "TRUE" : "FALSE");
265 result = (result == FALSE);
270 * Start from the end of the previous
274 DEBUG4(">>> EVALUATE RETURNED ::%s::", end);
276 if (!((*p == ')') || (*p == '!') ||
277 ((p[0] == '&') && (p[1] == '&')) ||
278 ((p[0] == '|') && (p[1] == '|')))) {
280 radlog(L_ERR, "Parse error in condition at: %s", p);
283 if (*p == ')') p++; /* skip it */
284 found_condition = TRUE;
286 while ((*p == ' ') || (*p == '\t')) p++;
292 DEBUG4(">>> AT EOL");
298 * (A && B) means "evaluate B
299 * only if A was true"
301 } else if ((p[0] == '&') && (p[1] == '&')) {
302 if (result == TRUE) {
303 evaluate_next_condition = evaluate_it;
305 evaluate_next_condition = FALSE;
310 * (A || B) means "evaluate B
311 * only if A was false"
313 } else if ((p[0] == '|') && (p[1] == '|')) {
314 if (result == FALSE) {
315 evaluate_next_condition = evaluate_it;
317 evaluate_next_condition = FALSE;
321 } else if (*p == ')') {
322 DEBUG4(">>> CLOSING BRACE");
331 radlog(L_ERR, "Unexpected trailing text at: %s", p);
334 } /* else it wasn't an opening brace */
336 while ((*p == ' ') || (*p == '\t')) p++;
339 * More conditions, keep going.
341 if ((*p == '(') || (p[0] == '!')) continue;
343 DEBUG4(">>> LOOKING AT %s", p);
347 * Look for common errors.
349 if ((p[0] == '%') && (p[1] == '{')) {
350 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
355 * Look for word == value
357 lt = gettoken(&p, left, sizeof(left));
358 if ((lt != T_BARE_WORD) &&
359 (lt != T_DOUBLE_QUOTED_STRING) &&
360 (lt != T_SINGLE_QUOTED_STRING) &&
361 (lt != T_BACK_QUOTED_STRING)) {
362 radlog(L_ERR, "Expected string or numbers at: %s", p);
367 if (evaluate_next_condition) {
368 pleft = expand_string(xleft, sizeof(xleft), request,
371 radlog(L_ERR, "Failed expanding string at: %s",
378 * Peek ahead. Maybe it's just a check for
379 * existence. If so, there shouldn't be anything
383 while ((*q == ' ') || (*q == '\t')) q++;
388 if (!*q || (*q == ')') ||
389 ((*q == '!') && (q[1] != '=') && (q[1] != '~')) ||
390 ((q[0] == '&') && (q[1] == '&')) ||
391 ((q[0] == '|') && (q[1] == '|'))) {
393 * Check for truth or falsehood.
395 if (all_digits(pleft)) {
397 result = (lint != 0);
399 } else if (lt == T_BARE_WORD) {
400 result = (modreturn == lrad_str2int(modreturn_table, pleft, -1));
402 result = (*pleft != '\0');
406 DEBUG4(">>> INVERTING result");
407 result = (result == FALSE);
411 if (evaluate_next_condition) {
412 DEBUG2("%.*s Evaluating %s\"%s\" -> %s",
414 invert ? "!" : "", pleft,
415 (result != FALSE) ? "TRUE" : "FALSE");
417 } else if (request) {
418 DEBUG2("%.*s Skipping %s\"%s\"",
420 invert ? "!" : "", pleft);
423 DEBUG4(">>> I%d %d:%s", invert,
425 goto end_of_condition;
429 * Else it's a full "foo == bar" thingy.
431 token = gettoken(&p, comp, sizeof(comp));
432 if ((token < T_OP_NE) || (token > T_OP_CMP_EQ) ||
433 (token == T_OP_CMP_TRUE) ||
434 (token == T_OP_CMP_FALSE)) {
435 radlog(L_ERR, "Expected comparison at: %s", comp);
440 * Look for common errors.
442 if ((p[0] == '%') && (p[1] == '{')) {
443 radlog(L_ERR, "Bare %%{...} is invalid in condition at: %s", p);
451 if ((token == T_OP_REG_EQ) ||
452 (token == T_OP_REG_NE)) {
453 rt = getregex(&p, right, sizeof(right), &cflags);
456 rt = gettoken(&p, right, sizeof(right));
458 if ((rt != T_BARE_WORD) &&
459 (rt != T_DOUBLE_QUOTED_STRING) &&
460 (rt != T_SINGLE_QUOTED_STRING) &&
461 (rt != T_BACK_QUOTED_STRING)) {
462 radlog(L_ERR, "Expected string or numbers at: %s", p);
467 if (evaluate_next_condition) {
468 pright = expand_string(xright, sizeof(xright), request,
471 radlog(L_ERR, "Failed expanding string at: %s",
477 DEBUG4(">>> %d:%s %d %d:%s",
478 lt, pleft, token, rt, pright);
480 if (evaluate_next_condition) {
485 if (!all_digits(pleft)) {
486 radlog(L_ERR, "Left field is not a number at: %s", pleft);
489 if (!all_digits(pright)) {
490 radlog(L_ERR, "Right field is not a number at: %s", pright);
503 result = (strcmp(pleft, pright) == 0);
507 result = (strcmp(pleft, pright) != 0);
511 result = (lint >= rint);
515 result = (lint > rint);
519 result = (lint <= rint);
523 result = (lint < rint);
530 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
533 * Include substring matches.
535 regcomp(®, pright, cflags);
536 compare = regexec(®, pleft,
537 REQUEST_MAX_REGEX + 1,
542 * Free old %{0}, etc.
544 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
545 free(request_data_get(request, request,
546 REQUEST_DATA_REGEX | i));
550 * Add new %{0}, %{1}, etc.
552 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
558 * We MAY have %{2} without %{1}.
560 if (rxmatch[i].rm_so == -1) continue;
563 * Copy substring into buffer.
565 memcpy(buffer, pleft + rxmatch[i].rm_so,
566 rxmatch[i].rm_eo - rxmatch[i].rm_so);
567 buffer[rxmatch[i].rm_eo - rxmatch[i].rm_so] = '\0';
570 * Copy substring, and add it to
573 * Note that we don't check
574 * for out of memory, which is
575 * the only error we can get...
578 request_data_add(request, request,
579 REQUEST_DATA_REGEX | i,
582 result = (compare == 0);
589 regmatch_t rxmatch[REQUEST_MAX_REGEX + 1];
592 * Include substring matches.
594 regcomp(®, pright, cflags);
595 compare = regexec(®, pleft,
596 REQUEST_MAX_REGEX + 1,
600 result = (compare != 0);
606 DEBUG4(">>> NOT IMPLEMENTED %d", token);
610 DEBUG2("%.*s Evaluating %s(%.*s) -> %s",
612 invert ? "!" : "", p - start, start,
613 (result != FALSE) ? "TRUE" : "FALSE");
615 DEBUG4(">>> GOT result %d", result);
618 * Not evaluating it. We may be just
621 } else if (request) {
622 DEBUG2("%.*s Skipping %s(\"%s\" %s \"%s\")",
624 invert ? "!" : "", pleft, comp, pright);
629 DEBUG4(">>> INVERTING result");
630 result = (result == FALSE);
637 DEBUG4(">>> EVALUATE %d ::%s::",
638 evaluate_next_condition, p);
640 while ((*p == ' ') || (*p == '\t')) p++;
643 * Closing brace or EOL, return.
645 if (!*p || (*p == ')') ||
646 ((*p == '!') && (p[1] != '=') && (p[1] != '~')) ||
647 ((p[0] == '&') && (p[1] == '&')) ||
648 ((p[0] == '|') && (p[1] == '|'))) {
649 DEBUG4(">>> AT EOL2a");
651 if (evaluate_next_condition) *presult = result;
654 } /* loop over the input condition */
656 DEBUG4(">>> AT EOL2b");
658 if (evaluate_next_condition) *presult = result;
663 * The pairmove() function in src/lib/valuepair.c does all sorts of
664 * extra magic that we don't want here.
666 * FIXME: integrate this with the code calling it, so that we
667 * only paircopy() those attributes that we're really going to
670 static void my_pairmove(REQUEST *request, VALUE_PAIR **to, VALUE_PAIR *from)
672 int i, j, count, from_count, to_count, tailto;
673 VALUE_PAIR *vp, *next, **last;
674 VALUE_PAIR **from_list, **to_list;
678 * Set up arrays for editing, to remove some of the
679 * O(N^2) dependencies. This also makes it easier to
680 * insert and remove attributes.
682 * It also means that the operators apply ONLY to the
683 * attributes in the original list. With the previous
684 * implementation of pairmove(), adding two attributes
685 * via "+=" and then "=" would mean that the second one
686 * wasn't added, because of the existence of the first
687 * one in the "to" list. This implementation doesn't
690 * Also, the previous implementation did NOT implement
691 * "-=" correctly. If two of the same attributes existed
692 * in the "to" list, and you tried to subtract something
693 * matching the *second* value, then the pairdelete()
694 * function was called, and the *all* attributes of that
695 * number were deleted. With this implementation, only
696 * the matching attributes are deleted.
699 for (vp = from; vp != NULL; vp = vp->next) count++;
700 from_list = rad_malloc(sizeof(*from_list) * count);
702 for (vp = *to; vp != NULL; vp = vp->next) count++;
703 to_list = rad_malloc(sizeof(*to_list) * count);
706 * Move the lists to the arrays, and break the list
710 for (vp = from; vp != NULL; vp = next) {
712 from_list[from_count++] = vp;
717 for (vp = *to; vp != NULL; vp = next) {
719 to_list[to_count++] = vp;
723 edited = rad_malloc(sizeof(*edited) * to_count);
724 memset(edited, 0, sizeof(*edited) * to_count);
726 DEBUG4("::: FROM %d TO %d MAX %d", from_count, to_count, count);
729 * Now that we have the lists initialized, start working
732 for (i = 0; i < from_count; i++) {
735 DEBUG4("::: Examining %s", from_list[i]->name);
738 * Attribute should be appended, OR the "to" list
739 * is empty, and we're supposed to replace or
740 * "add if not existing".
742 if (from_list[i]->operator == T_OP_ADD) goto append;
745 for (j = 0; j < to_count; j++) {
746 if (edited[j]) continue;
749 * Attributes aren't the same, skip them.
751 if (from_list[i]->attribute != to_list[j]->attribute) {
756 * We don't use a "switch" statement here
757 * because we want to break out of the
758 * "for" loop over 'j' in most cases.
762 * Over-write the FIRST instance of the
763 * matching attribute name. We free the
764 * one in the "to" list, and move over
765 * the one in the "from" list.
767 if (from_list[i]->operator == T_OP_SET) {
768 DEBUG4("::: OVERWRITING %s FROM %d TO %d",
769 to_list[j]->name, i, j);
770 pairfree(&to_list[j]);
771 to_list[j] = from_list[i];
778 * Add the attribute only if it does not
779 * exist... but it exists, so we stop
782 if (from_list[i]->operator == T_OP_EQ) {
788 * Delete all matching attributes from
791 if ((from_list[i]->operator == T_OP_SUB) ||
792 (from_list[i]->operator == T_OP_LE) ||
793 (from_list[i]->operator == T_OP_GE)) {
795 int old_op = from_list[i]->operator;
798 * Check for equality.
800 from_list[i]->operator = T_OP_CMP_EQ;
803 * If equal, delete the one in
806 rcode = radius_compare_vps(NULL, from_list[i],
809 * We may want to do more
810 * subtractions, so we re-set the
811 * operator back to it's original
814 from_list[i]->operator = old_op;
819 DEBUG4("::: DELETING %s FROM %d TO %d",
820 from_list[i]->name, i, j);
821 pairfree(&to_list[j]);
827 * Enforce <=. If it's
832 DEBUG4("::: REPLACING %s FROM %d TO %d",
833 from_list[i]->name, i, j);
834 pairfree(&to_list[j]);
835 to_list[j] = from_list[i];
843 DEBUG4("::: REPLACING %s FROM %d TO %d",
844 from_list[i]->name, i, j);
845 pairfree(&to_list[j]);
846 to_list[j] = from_list[i];
856 rad_assert(0 == 1); /* panic! */
860 * We were asked to add it if it didn't exist,
861 * and it doesn't exist. Move it over to the
862 * tail of the "to" list, UNLESS it was already
863 * moved by another operator.
865 if (!found && from_list[i]) {
866 if ((from_list[i]->operator == T_OP_EQ) ||
867 (from_list[i]->operator == T_OP_LE) ||
868 (from_list[i]->operator == T_OP_GE) ||
869 (from_list[i]->operator == T_OP_SET)) {
871 DEBUG4("::: APPENDING %s FROM %d TO %d",
872 from_list[i]->name, i, tailto);
873 to_list[tailto++] = from_list[i];
880 * Delete attributes in the "from" list.
882 for (i = 0; i < from_count; i++) {
883 if (!from_list[i]) continue;
885 pairfree(&from_list[i]);
889 DEBUG4("::: TO in %d out %d", to_count, tailto);
892 * Re-chain the "to" list.
896 for (i = 0; i < tailto; i++) {
897 if (!to_list[i]) continue;
899 DEBUG4("::: to[%d] = %s", i, to_list[i]->name);
902 * Mash the operator to a simple '='. The
903 * operators in the "to" list aren't used for
904 * anything. BUT they're used in the "detail"
905 * file and debug output, where we don't want to
908 to_list[i]->operator = T_OP_EQ;
911 last = &(*last)->next;
914 * Fix dumb cache issues
916 if ((i >= to_count) || edited[i]) {
917 if (to_list[i]->attribute == PW_USER_NAME) {
918 request->username = to_list[i];
920 } else if (to_list[i]->attribute == PW_USER_PASSWORD) {
921 request->password = to_list[i];
930 * Copied shamelessly from conffile.c, to simplify the API for
933 typedef enum conf_type {
934 CONF_ITEM_INVALID = 0,
941 struct conf_item *next;
942 struct conf_part *parent;
944 const char *filename;
952 LRAD_TOKEN value_type;
956 * Add attributes to a list.
958 int radius_update_attrlist(REQUEST *request, CONF_SECTION *cs,
959 VALUE_PAIR *input_vps, const char *name)
962 VALUE_PAIR *newlist, *vp;
963 VALUE_PAIR **output_vps = NULL;
965 if (!request || !cs) return RLM_MODULE_INVALID;
967 if (strcmp(name, "request") == 0) {
968 output_vps = &request->packet->vps;
970 } else if (strcmp(name, "reply") == 0) {
971 output_vps = &request->reply->vps;
973 } else if (strcmp(name, "proxy-request") == 0) {
974 if (request->proxy) output_vps = &request->proxy->vps;
976 } else if (strcmp(name, "proxy-reply") == 0) {
977 if (request->proxy_reply) output_vps = &request->proxy_reply->vps;
979 } else if (strcmp(name, "config") == 0) {
980 output_vps = &request->config_items;
982 } else if (strcmp(name, "control") == 0) {
983 output_vps = &request->config_items;
986 return RLM_MODULE_INVALID;
989 if (!output_vps) return RLM_MODULE_NOOP; /* didn't update the list */
991 newlist = paircopy(input_vps);
993 DEBUG2("Out of memory");
994 return RLM_MODULE_FAIL;
998 for (ci=cf_item_find_next(cs, NULL);
1000 ci=cf_item_find_next(cs, ci)) {
1004 * This should never happen.
1006 if (cf_item_is_section(ci)) {
1008 return RLM_MODULE_INVALID;
1011 cp = cf_itemtopair(ci);
1014 * The VP && CF lists should be in sync. If they're
1017 if (vp->flags.do_xlat) {
1021 value = expand_string(buffer, sizeof(buffer), request,
1022 cp->value_type, cp->value);
1025 return RLM_MODULE_INVALID;
1028 if (!pairparsevalue(vp, value)) {
1029 DEBUG2("ERROR: Failed parsing value \"%s\" for attribute %s: %s",
1030 value, vp->name, librad_errstr);
1032 return RLM_MODULE_FAIL;
1034 vp->flags.do_xlat = 0;
1039 my_pairmove(request, output_vps, newlist);
1041 return RLM_MODULE_UPDATED;