Allow delayed references to attributes. Helps with #711
[freeradius.git] / src / main / parser.c
1 /*
2  * parser.c     Parse various things
3  *
4  * Version:     $Id$
5  *
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.
10  *
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.
15  *
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
19  *
20  * Copyright 2013  Alan DeKok <aland@freeradius.org>
21  */
22
23 RCSID("$Id$")
24
25 #include <freeradius-devel/radiusd.h>
26 #include <freeradius-devel/parser.h>
27 #include <freeradius-devel/rad_assert.h>
28
29 #include <ctype.h>
30
31 #define PW_CAST_BASE (1850)
32
33 static const FR_NAME_NUMBER allowed_return_codes[] = {
34         { "reject",     1 },
35         { "fail",       1 },
36         { "ok",         1 },
37         { "handled",    1 },
38         { "invalid",    1 },
39         { "userlock",   1 },
40         { "notfound",   1 },
41         { "noop",       1 },
42         { "updated",    1 },
43         { NULL, 0 }
44 };
45
46 /*
47  *      This file shouldn't use any functions from the server core.
48  */
49
50 size_t fr_cond_sprint(char *buffer, size_t bufsize, fr_cond_t const *in)
51 {
52         size_t len;
53         char *p = buffer;
54         char *end = buffer + bufsize - 1;
55         fr_cond_t const *c = in;
56
57 next:
58         if (c->negate) {
59                 *(p++) = '!';   /* FIXME: only allow for child? */
60         }
61
62         switch (c->type) {
63         case COND_TYPE_EXISTS:
64                 rad_assert(c->data.vpt != NULL);
65                 if (c->cast) {
66                         len = snprintf(p, end - p, "<%s>", fr_int2str(dict_attr_types,
67                                                                       c->cast->type, "??"));
68                         p += len;
69                 }
70
71                 len = radius_tmpl2str(p, end - p, c->data.vpt);
72                 p += len;
73                 break;
74
75         case COND_TYPE_MAP:
76                 rad_assert(c->data.map != NULL);
77 #if 0
78                 *(p++) = '[';   /* for extra-clear debugging */
79 #endif
80                 if (c->cast) {
81                         len = snprintf(p, end - p, "<%s>", fr_int2str(dict_attr_types,
82                                                                       c->cast->type, "??"));
83                         p += len;
84                 }
85
86                 len = radius_map2str(p, end - p, c->data.map);
87                 p += len;
88 #if 0
89                 *(p++) = ']';
90 #endif
91                 break;
92
93         case COND_TYPE_CHILD:
94                 rad_assert(c->data.child != NULL);
95                 *(p++) = '(';
96                 len = fr_cond_sprint(p, end - p, c->data.child);
97                 p += len;
98                 *(p++) = ')';
99                 break;
100
101         case COND_TYPE_TRUE:
102                 strlcpy(buffer, "true", bufsize);
103                 return strlen(buffer);
104
105         case COND_TYPE_FALSE:
106                 strlcpy(buffer, "false", bufsize);
107                 return strlen(buffer);
108
109         default:
110                 *buffer = '\0';
111                 return 0;
112         }
113
114         if (c->next_op == COND_NONE) {
115                 rad_assert(c->next == NULL);
116                 *p = '\0';
117                 return p - buffer;
118         }
119
120         if (c->next_op == COND_AND) {
121                 strlcpy(p, " && ", end - p);
122                 p += strlen(p);
123
124         } else if (c->next_op == COND_OR) {
125                 strlcpy(p, " || ", end - p);
126                 p += strlen(p);
127
128         } else {
129                 rad_assert(0 == 1);
130         }
131
132         c = c->next;
133         goto next;
134 }
135
136
137 static ssize_t condition_tokenize_string(TALLOC_CTX *ctx, char const *start, char **out,
138                                          FR_TOKEN *op, char const **error)
139 {
140         char const *p = start;
141         char *q;
142
143         switch (*p++) {
144         default:
145                 return -1;
146
147         case '"':
148                 *op = T_DOUBLE_QUOTED_STRING;
149                 break;
150
151         case '\'':
152                 *op = T_SINGLE_QUOTED_STRING;
153                 break;
154
155         case '`':
156                 *op = T_BACK_QUOTED_STRING;
157                 break;
158
159         case '/':
160                 *op = T_OP_REG_EQ; /* a bit of a hack. */
161                 break;
162
163         }
164
165         *out = talloc_array(ctx, char, strlen(start) - 1); /* + 2 - 1 */
166         if (!*out) return -1;
167
168         q = *out;
169
170         while (*p) {
171                 if (*p == *start) {
172                         *q = '\0';
173                         p++;
174                         return (p - start);
175                 }
176
177                 if (*p == '\\') {
178                         p++;
179                         if (!*p) {
180                                 *error = "End of string after escape";
181                                 return -(p - start);
182                         }
183
184                         switch (*p) {
185                         case 'r':
186                                 *q++ = '\r';
187                                 break;
188                         case 'n':
189                                 *q++ = '\n';
190                                 break;
191                         case 't':
192                                 *q++ = '\t';
193                                 break;
194                         default:
195                                 *q++ = *p;
196                                 break;
197                         }
198                         p++;
199                         continue;
200                 }
201
202                 *(q++) = *(p++);
203         }
204
205         *error = "Unterminated string";
206         return -1;
207 }
208
209 static ssize_t condition_tokenize_word(TALLOC_CTX *ctx, char const *start, char **out,
210                                        FR_TOKEN *op, char const **error)
211 {
212         size_t len;
213         char const *p = start;
214
215         if ((*p == '"') || (*p == '\'') || (*p == '`') || (*p == '/')) {
216                 return condition_tokenize_string(ctx, start, out, op, error);
217         }
218
219         *op = T_BARE_WORD;
220         if (*p == '&') p++;     /* special-case &User-Name */
221
222         while (*p) {
223                 /*
224                  *      The LHS should really be limited to only a few
225                  *      things.  For now, we allow pretty much anything.
226                  */
227                 if (*p == '\\') {
228                         *error = "Unexpected escape";
229                         return -(p - start);
230                 }
231
232                 /*
233                  *      ("foo") is valid.
234                  */
235                 if (*p == ')') {
236                         break;
237                 }
238
239                 /*
240                  *      Spaces or special characters delineate the word
241                  */
242                 if (isspace((int) *p) || (*p == '&') || (*p == '|') ||
243                     (*p == '!') || (*p == '=') || (*p == '<') || (*p == '>')) {
244                         break;
245                 }
246
247                 if ((*p == '"') || (*p == '\'') || (*p == '`')) {
248                         *error = "Unexpected start of string";
249                         return -(p - start);
250                 }
251
252                 p++;
253         }
254
255         len = p - start;
256         if (!len) {
257                 *error = "Empty string is invalid";
258                 return 0;
259         }
260
261         *out = talloc_array(ctx, char, len + 1);
262         memcpy(*out, start, len);
263         (*out)[len] = '\0';
264         return len;
265 }
266
267
268 static ssize_t condition_tokenize_cast(char const *start, DICT_ATTR const **pda, char const **error)
269 {
270         char const *p = start;
271         char const *q;
272         PW_TYPE cast;
273
274         while (isspace((int) *p)) p++; /* skip spaces before condition */
275
276         if (*p != '<') return 0;
277         p++;
278
279         q = p;
280         while (*q && *q != '>') q++;
281
282         cast = fr_substr2int(dict_attr_types, p, PW_TYPE_INVALID, q - p);
283         if (cast == PW_TYPE_INVALID) {
284                 *error = "Invalid data type in cast";
285                 return -(p - start);
286         }
287
288         /*
289          *      We can only cast to basic data types.  Complex ones
290          *      are forbidden.
291          */
292         switch (cast) {
293 #ifdef WITH_ASCEND_BINARY
294         case PW_TYPE_ABINARY:
295 #endif
296         case PW_TYPE_IP_ADDR:
297         case PW_TYPE_TLV:
298         case PW_TYPE_EXTENDED:
299         case PW_TYPE_LONG_EXTENDED:
300         case PW_TYPE_EVS:
301         case PW_TYPE_VSA:
302                 *error = "Forbidden data type in cast";
303                 return -(p - start);
304
305         default:
306                 break;
307         }
308
309         *pda = dict_attrbyvalue(PW_CAST_BASE + cast, 0);
310         if (!*pda) {
311                 *error = "Cannot cast to this data type";
312                 return -(p - start);
313         }
314
315         q++;
316
317         while (isspace((int) *q)) q++; /* skip spaces after cast */
318
319         return q - start;
320 }
321
322 /*
323  *      Less code means less bugs
324  */
325 #define return_P(_x) *error = _x;goto return_p
326 #define return_0(_x) *error = _x;goto return_0
327 #define return_lhs(_x) *error = _x;goto return_lhs
328 #define return_rhs(_x) *error = _x;goto return_rhs
329 #define return_SLEN goto return_slen
330
331
332 /** Tokenize a conditional check
333  *
334  *  @param[in] ctx for talloc
335  *  @param[in] ci for CONF_ITEM
336  *  @param[in] start the start of the string to process.  Should be "(..."
337  *  @param[in] brace look for a closing brace
338  *  @param[in] flags do one/two pass
339  *  @param[out] pcond pointer to the returned condition structure
340  *  @param[out] error the parse error (if any)
341  *  @return length of the string skipped, or when negative, the offset to the offending error
342  */
343 static ssize_t condition_tokenize(TALLOC_CTX *ctx, CONF_ITEM *ci, char const *start, int brace,
344                                   fr_cond_t **pcond, char const **error, int flags)
345 {
346         ssize_t slen;
347         char const *p = start;
348         char const *lhs_p, *rhs_p;
349         fr_cond_t *c;
350         char *lhs, *rhs;
351         FR_TOKEN op, lhs_type, rhs_type;
352
353         c = talloc_zero(ctx, fr_cond_t);
354
355         rad_assert(c != NULL);
356         lhs = rhs = NULL;
357         lhs_type = rhs_type = T_OP_INVALID;
358
359         while (isspace((int) *p)) p++; /* skip spaces before condition */
360
361         if (!*p) {
362                 return_P("Empty condition is invalid");
363         }
364
365         /*
366          *      !COND
367          */
368         if (*p == '!') {
369                 p++;
370                 c->negate = true;
371                 while (isspace((int) *p)) p++; /* skip spaces after negation */
372
373                 /*
374                  *  Just for stupidity
375                  */
376                 if (*p == '!') {
377                         return_P("Double negation is invalid");
378                 }
379         }
380
381         /*
382          *      (COND)
383          */
384         if (*p == '(') {
385                 p++;
386
387                 /*
388                  *      We've already eaten one layer of
389                  *      brackets.  Go recurse to get more.
390                  */
391                 c->type = COND_TYPE_CHILD;
392                 c->ci = ci;
393                 slen = condition_tokenize(c, ci, p, true, &c->data.child, error, flags);
394                 if (slen <= 0) {
395                         return_SLEN;
396                 }
397
398                 if (!c->data.child) {
399                         return_P("Empty condition is invalid");
400                 }
401
402                 p += slen;
403                 while (isspace((int) *p)) p++; /* skip spaces after (COND)*/
404
405         } else { /* it's a bare FOO==BAR */
406                 /*
407                  *      We didn't see anything special.  The condition must be one of
408                  *
409                  *      FOO
410                  *      FOO OP BAR
411                  */
412
413                 /*
414                  *      Grab the LHS
415                  */
416                 if (*p == '/') {
417                         return_P("Conditional check cannot begin with a regular expression");
418                 }
419
420                 slen = condition_tokenize_cast(p, &c->cast, error);
421                 if (slen < 0) {
422                         return_SLEN;
423                 }
424                 p += slen;
425
426                 lhs_p = p;
427                 slen = condition_tokenize_word(c, p, &lhs, &lhs_type, error);
428                 if (slen <= 0) {
429                         return_SLEN;
430                 }
431                 p += slen;
432
433                 while (isspace((int)*p)) p++; /* skip spaces after LHS */
434
435                 /*
436                  *      We may (or not) have an operator
437                  */
438
439
440                 /*
441                  *      (FOO)
442                  */
443                 if (*p == ')') {
444                         /*
445                          *      don't skip the brace.  We'll look for it later.
446                          */
447                         goto exists;
448
449                         /*
450                          *      FOO
451                          */
452                 } else if (!*p) {
453                         if (brace) {
454                                 return_P("No closing brace at end of string");
455                         }
456
457                         goto exists;
458
459                         /*
460                          *      FOO && ...
461                          */
462                 } else if (((p[0] == '&') && (p[1] == '&')) ||
463                            ((p[0] == '|') && (p[1] == '|'))) {
464
465                 exists:
466                         if (c->cast) {
467                                 return_0("Cannot do cast for existence check");
468                         }
469
470                         c->type = COND_TYPE_EXISTS;
471                         c->ci = ci;
472
473                         c->data.vpt = radius_str2tmpl(c, lhs, lhs_type, REQUEST_CURRENT, PAIR_LIST_REQUEST);
474                         if (!c->data.vpt) {
475                                 return_P("Failed creating exists");
476                         }
477
478                         rad_assert(c->data.vpt->type != VPT_TYPE_REGEX);
479
480                 } else { /* it's an operator */
481                         bool regex;
482                         bool i_flag = false;
483
484                         /*
485                          *      The next thing should now be a comparison operator.
486                          */
487                         regex = false;
488                         c->type = COND_TYPE_MAP;
489                         c->ci = ci;
490
491                         switch (*p) {
492                         default:
493                                 return_P("Invalid text. Expected comparison operator");
494
495                         case '!':
496                                 if (p[1] == '=') {
497                                         op = T_OP_NE;
498                                         p += 2;
499
500                                 } else if (p[1] == '~') {
501                                 regex = true;
502
503                                 op = T_OP_REG_NE;
504                                 p += 2;
505
506                                 } else if (p[1] == '*') {
507                                         if (lhs_type != T_BARE_WORD) {
508                                                 return_P("Cannot use !* on a string");
509                                         }
510
511                                         op = T_OP_CMP_FALSE;
512                                         p += 2;
513
514                                 } else {
515                                         goto invalid_operator;
516                                 }
517                                 break;
518
519                         case '=':
520                                 if (p[1] == '=') {
521                                         op = T_OP_CMP_EQ;
522                                         p += 2;
523
524                                 } else if (p[1] == '~') {
525                                         regex = true;
526
527                                         op = T_OP_REG_EQ;
528                                         p += 2;
529
530                                 } else if (p[1] == '*') {
531                                         if (lhs_type != T_BARE_WORD) {
532                                                 return_P("Cannot use =* on a string");
533                                         }
534
535                                         op = T_OP_CMP_TRUE;
536                                         p += 2;
537
538                                 } else {
539                                 invalid_operator:
540                                         return_P("Invalid operator");
541                                 }
542
543                                 break;
544
545                         case '<':
546                                 if (p[1] == '=') {
547                                         op = T_OP_LE;
548                                         p += 2;
549
550                                 } else {
551                                         op = T_OP_LT;
552                                         p++;
553                                 }
554                                 break;
555
556                         case '>':
557                                 if (p[1] == '=') {
558                                         op = T_OP_GE;
559                                         p += 2;
560
561                                 } else {
562                                         op = T_OP_GT;
563                                         p++;
564                                 }
565                                 break;
566                         }
567
568                         while (isspace((int) *p)) p++; /* skip spaces after operator */
569
570                         if (!*p) {
571                                 return_P("Expected text after operator");
572                         }
573
574                         /*
575                          *      Cannot have a cast on the RHS.
576                          *      But produce good errors, too.
577                          */
578                         if (*p == '<') {
579                                 DICT_ATTR const *cast_da;
580
581                                 slen = condition_tokenize_cast(p, &cast_da, error);
582                                 if (slen < 0) {
583                                         return_SLEN;
584                                 }
585
586                                 if (!c->cast) {
587                                         return_P("Unexpected cast");
588                                 }
589
590                                 if (c->cast != cast_da) {
591                                         return_P("Cannot cast to a different data type");
592                                 }
593
594                                 return_P("Unnecessary cast");
595                         }
596
597                         /*
598                          *      Grab the RHS
599                          */
600                         rhs_p = p;
601                         slen = condition_tokenize_word(c, p, &rhs, &rhs_type, error);
602                         if (slen <= 0) {
603                                 return_SLEN;
604                         }
605
606                         /*
607                          *      Sanity checks for regexes.
608                          */
609                         if (regex) {
610                                 if (*p != '/') {
611                                         return_P("Expected regular expression");
612                                 }
613
614                                 /*
615                                  *      Allow /foo/i
616                                  */
617                                 if (p[slen] == 'i') {
618                                         i_flag = true;
619                                         slen++;
620                                 }
621
622                         } else if (!regex && (*p == '/')) {
623                                 return_P("Unexpected regular expression");
624                         }
625
626                         c->data.map = radius_str2map(c, lhs, lhs_type, op, rhs, rhs_type,
627                                                      REQUEST_CURRENT, PAIR_LIST_REQUEST,
628                                                      REQUEST_CURRENT, PAIR_LIST_REQUEST);
629                         if (!c->data.map) {
630                                 /*
631                                  *      FIXME: if strings are T_BARE_WORD and they start with '&',
632                                  *      then they refer to attributes which have not yet been
633                                  *      defined.  Create the template(s) as literals, and
634                                  *      fix them up in pass2.
635                                  */
636                                 if ((*lhs != '&') ||
637                                     (lhs_type != T_BARE_WORD)) {
638                                         return_0("Syntax error");
639                                 }
640                                 c->data.map = radius_str2map(c, lhs, lhs_type + 1, op, rhs, rhs_type,
641                                                              REQUEST_CURRENT, PAIR_LIST_REQUEST,
642                                                              REQUEST_CURRENT, PAIR_LIST_REQUEST);
643                                 if (!c->data.map) {
644                                         return_0("Unknown attribute");
645                                 }
646                                 rad_const_free(c->data.map->dst->name);
647                                 c->data.map->dst->name = talloc_strdup(c->data.map->dst, lhs);
648                                 c->pass2_fixup = PASS2_FIXUP_ATTR;
649                         }
650
651                         if (c->data.map->src->type == VPT_TYPE_REGEX) {
652                                 c->data.map->src->vpt_iflag = i_flag;
653                         }
654
655                         /*
656                          *      Could have been a reference to an attribute which is registered later.
657                          *      Mark it as being checked in pass2.
658                          */
659                         if ((lhs_type == T_BARE_WORD) &&
660                             (c->data.map->dst->type == VPT_TYPE_LITERAL)) {
661                                 c->pass2_fixup = PASS2_FIXUP_ATTR;
662                         }
663
664                         /*
665                          *      Save the CONF_ITEM for later.
666                          */
667                         c->data.map->ci = ci;
668
669                         /*
670                          *      @todo: check LHS and RHS separately, to
671                          *      get better errors
672                          */
673                         if ((c->data.map->src->type == VPT_TYPE_LIST) ||
674                             (c->data.map->dst->type == VPT_TYPE_LIST)) {
675                                 return_0("Cannot use list references in condition");
676                         }
677
678                         /*
679                          *      Check cast type.  We can have the RHS
680                          *      a string if the LHS has a cast.  But
681                          *      if the RHS is an attr, it MUST be the
682                          *      same type as the LHS.
683                          */
684                         if (c->cast) {
685                                 if ((c->data.map->src->type == VPT_TYPE_ATTR) &&
686                                     (c->cast->type != c->data.map->src->vpt_da->type)) {
687                                         goto same_type;
688                                 }
689
690                                 if (c->data.map->src->type == VPT_TYPE_REGEX) {
691                                         return_0("Cannot use cast with regex comparison");
692                                 }
693
694                                 /*
695                                  *      The LHS is a literal which has been cast to a data type.
696                                  *      Cast it to the appropriate data type.
697                                  */
698                                 if ((c->data.map->dst->type == VPT_TYPE_LITERAL) &&
699                                     !radius_cast_tmpl(c->data.map->dst, c->cast)) {
700                                         *error = "Failed to parse field";
701                                         if (lhs) talloc_free(lhs);
702                                         if (rhs) talloc_free(rhs);
703                                         talloc_free(c);
704                                         return -(lhs_p - start);
705                                 }
706
707                                 /*
708                                  *      The RHS is a literal, and the LHS has been cast to a data
709                                  *      type.
710                                  */
711                                 if ((c->data.map->dst->type == VPT_TYPE_DATA) &&
712                                     (c->data.map->src->type == VPT_TYPE_LITERAL) &&
713                                     !radius_cast_tmpl(c->data.map->src, c->data.map->dst->vpt_da)) {
714                                         return_rhs("Failed to parse field");
715                                 }
716
717                                 /*
718                                  *      We may be casting incompatible
719                                  *      types.  We check this based on
720                                  *      their size.
721                                  */
722                                 if (c->data.map->dst->type == VPT_TYPE_ATTR) {
723                                         /*
724                                          *      dst.min == src.min
725                                          *      dst.max == src.max
726                                          */
727                                         if ((dict_attr_sizes[c->cast->type][0] == dict_attr_sizes[c->data.map->dst->vpt_da->type][0]) &&
728                                             (dict_attr_sizes[c->cast->type][1] == dict_attr_sizes[c->data.map->dst->vpt_da->type][1])) {
729                                                 goto cast_ok;
730                                         }
731
732                                         /*
733                                          *      Run-time parsing of strings.
734                                          *      Run-time copying of octets.
735                                          */
736                                         if ((c->data.map->dst->vpt_da->type == PW_TYPE_STRING) ||
737                                             (c->data.map->dst->vpt_da->type == PW_TYPE_OCTETS)) {
738                                                 goto cast_ok;
739                                         }
740
741                                         /*
742                                          *      ipaddr to ipv4prefix is OK
743                                          */
744                                         if ((c->data.map->dst->vpt_da->type == PW_TYPE_IPV4_ADDR) &&
745                                             (c->cast->type == PW_TYPE_IPV4_PREFIX)) {
746                                                 goto cast_ok;
747                                         }
748
749                                         /*
750                                          *      ipv6addr to ipv6prefix is OK
751                                          */
752                                         if ((c->data.map->dst->vpt_da->type == PW_TYPE_IPV6_ADDR) &&
753                                             (c->cast->type == PW_TYPE_IPV6_PREFIX)) {
754                                                 goto cast_ok;
755                                         }
756
757                                         /*
758                                          *      integer64 to ethernet is OK.
759                                          */
760                                         if ((c->data.map->dst->vpt_da->type == PW_TYPE_INTEGER64) &&
761                                             (c->cast->type == PW_TYPE_ETHERNET)) {
762                                                 goto cast_ok;
763                                         }
764
765                                         /*
766                                          *      dst.max < src.min
767                                          *      dst.min > src.max
768                                          */
769                                         if ((dict_attr_sizes[c->cast->type][1] < dict_attr_sizes[c->data.map->dst->vpt_da->type][0]) ||
770                                             (dict_attr_sizes[c->cast->type][0] > dict_attr_sizes[c->data.map->dst->vpt_da->type][1])) {
771                                                 return_0("Cannot cast to attribute of incompatible size");
772                                         }
773                                 }
774
775                         cast_ok:
776                                 /*
777                                  *      Casting to a redundant type means we don't need the cast.
778                                  *
779                                  *      Do this LAST, as the rest of the code above assumes c->cast
780                                  *      is not NULL.
781                                  */
782                                 if ((c->data.map->dst->type == VPT_TYPE_ATTR) &&
783                                     (c->cast->type == c->data.map->dst->vpt_da->type)) {
784                                         c->cast = NULL;
785                                 }
786
787                         } else {
788                                 /*
789                                  *      Two attributes?  They must be of the same type
790                                  */
791                                 if ((c->data.map->src->type == VPT_TYPE_ATTR) &&
792                                     (c->data.map->dst->type == VPT_TYPE_ATTR) &&
793                                     (c->data.map->dst->vpt_da->type != c->data.map->src->vpt_da->type)) {
794                                 same_type:
795                                         return_0("Attribute comparisons must be of the same data type");
796                                 }
797
798                                 /*
799                                  *      Without a cast, we can't compare "foo" to User-Name,
800                                  *      it has to be done the other way around.
801                                  */
802                                 if ((c->data.map->src->type == VPT_TYPE_ATTR) &&
803                                     (c->data.map->dst->type != VPT_TYPE_ATTR)) {
804                                         *error = "Cannot use attribute reference on right side of condition";
805                                 return_0:
806                                         if (lhs) talloc_free(lhs);
807                                         if (rhs) talloc_free(rhs);
808                                         talloc_free(c);
809                                         return 0;
810                                 }
811
812                                 /*
813                                  *      Invalid: User-Name == bob
814                                  *      Valid:   User-Name == "bob"
815                                  *
816                                  *      There's no real reason for
817                                  *      this, other than consistency.
818                                  */
819                                 if ((c->data.map->dst->type == VPT_TYPE_ATTR) &&
820                                     (c->data.map->src->type != VPT_TYPE_ATTR) &&
821                                     (c->data.map->dst->vpt_da->type == PW_TYPE_STRING) &&
822                                     (c->data.map->op != T_OP_CMP_TRUE) &&
823                                     (c->data.map->op != T_OP_CMP_FALSE) &&
824                                     (rhs_type == T_BARE_WORD)) {
825                                         return_rhs("Must have string as value for attribute");
826                                 }
827
828                                 /*
829                                  *      Quotes around non-string
830                                  *      attributes mean that it's
831                                  *      either xlat, or an exec.
832                                  */
833                                 if ((c->data.map->dst->type == VPT_TYPE_ATTR) &&
834                                     (c->data.map->src->type != VPT_TYPE_ATTR) &&
835                                     (c->data.map->dst->vpt_da->type != PW_TYPE_STRING) &&
836                                     (c->data.map->dst->vpt_da->type != PW_TYPE_OCTETS) &&
837                                     (c->data.map->dst->vpt_da->type != PW_TYPE_DATE) &&
838                                     (rhs_type == T_SINGLE_QUOTED_STRING)) {
839                                         *error = "Value must be an unquoted string";
840                                 return_rhs:
841                                         if (lhs) talloc_free(lhs);
842                                         if (rhs) talloc_free(rhs);
843                                         talloc_free(c);
844                                         return -(rhs_p - start);
845                                 }
846
847                                 /*
848                                  *      The LHS has been cast to a data type, and the RHS is a
849                                  *      literal.  Cast the RHS to the type of the cast.
850                                  */
851                                 if (c->cast && (c->data.map->src->type == VPT_TYPE_LITERAL) &&
852                                     !radius_cast_tmpl(c->data.map->src, c->cast)) {
853                                         return_rhs("Failed to parse field");
854                                 }
855
856                                 /*
857                                  *      The LHS is an attribute, and the RHS is a literal.  Cast the
858                                  *      RHS to the data type of the LHS.
859                                  */
860                                 if ((c->data.map->dst->type == VPT_TYPE_ATTR) &&
861                                     (c->data.map->src->type == VPT_TYPE_LITERAL) &&
862                                     !radius_cast_tmpl(c->data.map->src, c->data.map->dst->vpt_da)) {
863                                         DICT_ATTR const *da = c->data.map->dst->vpt_da;
864
865                                         if ((da->vendor == 0) &&
866                                             ((da->attr == PW_AUTH_TYPE) ||
867                                              (da->attr == PW_AUTZ_TYPE) ||
868                                              (da->attr == PW_ACCT_TYPE) ||
869                                              (da->attr == PW_SESSION_TYPE) ||
870                                              (da->attr == PW_POST_AUTH_TYPE) ||
871                                              (da->attr == PW_PRE_PROXY_TYPE) ||
872                                              (da->attr == PW_POST_PROXY_TYPE) ||
873                                              (da->attr == PW_PRE_ACCT_TYPE) ||
874                                              (da->attr == PW_RECV_COA_TYPE) ||
875                                              (da->attr == PW_SEND_COA_TYPE))) {
876                                                 /*
877                                                  *      The types for these attributes are dynamically allocated
878                                                  *      by modules.c, so we can't enforce strictness here.
879                                                  */
880                                                 c->pass2_fixup = PASS2_FIXUP_TYPE;
881
882                                         } else {
883                                                 return_rhs("Failed to parse value for attribute");
884                                         }
885                                 }
886                         }
887
888                         p += slen;
889
890                         while (isspace((int) *p)) p++; /* skip spaces after RHS */
891                 } /* parse OP RHS */
892         } /* parse a condition (COND) or FOO OP BAR*/
893
894         /*
895          *      ...COND)
896          */
897         if (*p == ')') {
898                 if (!brace) {
899                         return_P("Unexpected closing brace");
900                 }
901
902                 p++;
903                 while (isspace((int) *p)) p++; /* skip spaces after closing brace */
904                 goto done;
905         }
906
907         /*
908          *      End of string is now allowed.
909          */
910         if (!*p) {
911                 if (brace) {
912                         return_P("No closing brace at end of string");
913                 }
914
915                 goto done;
916         }
917
918         if (!(((p[0] == '&') && (p[1] == '&')) ||
919               ((p[0] == '|') && (p[1] == '|')))) {
920                 *error = "Unexpected text after condition";
921         return_p:
922                 if (lhs) talloc_free(lhs);
923                 if (rhs) talloc_free(rhs);
924                 talloc_free(c);
925                 return -(p - start);
926         }
927
928         /*
929          *      Recurse to parse the next condition.
930          */
931         c->next_op = p[0];
932         p += 2;
933
934         /*
935          *      May still be looking for a closing brace.
936          */
937         slen = condition_tokenize(c, ci, p, brace, &c->next, error, flags);
938         if (slen <= 0) {
939         return_slen:
940                 if (lhs) talloc_free(lhs);
941                 if (rhs) talloc_free(rhs);
942                 talloc_free(c);
943                 return slen - (p - start);
944         }
945         p += slen;
946
947 done:
948         /*
949          *      Normalize the condition before returning.
950          *
951          *      We collapse multiple levels of braces to one.  Then
952          *      convert maps to literals.  Then literals to true/false
953          *      statements.  Then true/false ||/&& followed by other
954          *      conditions to just conditions.
955          *
956          *      Order is important.  The more complex cases are
957          *      converted to simpler ones, from the most complex cases
958          *      to the simplest ones.
959          */
960
961         /*
962          *      (FOO)     --> FOO
963          *      (FOO) ... --> FOO ...
964          */
965         if ((c->type == COND_TYPE_CHILD) && !c->data.child->next) {
966                 fr_cond_t *child;
967
968                 child = talloc_steal(ctx, c->data.child);
969                 c->data.child = NULL;
970
971                 child->next = talloc_steal(child, c->next);
972                 c->next = NULL;
973
974                 child->next_op = c->next_op;
975
976                 /*
977                  *      Set the negation properly
978                  */
979                 if ((c->negate && !child->negate) ||
980                     (!c->negate && child->negate)) {
981                         child->negate = true;
982                 } else {
983                         child->negate = false;
984                 }
985
986                 lhs = rhs = NULL;
987                 talloc_free(c);
988                 c = child;
989         }
990
991         /*
992          *      (FOO ...) --> FOO ...
993          *
994          *      But don't do !(FOO || BAR) --> !FOO || BAR
995          *      Because that's different.
996          */
997         if ((c->type == COND_TYPE_CHILD) &&
998             !c->next && !c->negate) {
999                 fr_cond_t *child;
1000
1001                 child = talloc_steal(ctx, c->data.child);
1002                 c->data.child = NULL;
1003
1004                 lhs = rhs = NULL;
1005                 talloc_free(c);
1006                 c = child;
1007         }
1008
1009         /*
1010          *      Convert maps to literals.  Convert one form of map to
1011          *      a standardized form.  This doesn't make any
1012          *      theoretical difference, but it does mean that the
1013          *      run-time evaluation has fewer cases to check.
1014          */
1015         if (c->type == COND_TYPE_MAP) do {
1016                 /*
1017                  *      !FOO !~ BAR --> FOO =~ BAR
1018                  */
1019                 if (c->negate && (c->data.map->op == T_OP_REG_NE)) {
1020                         c->negate = false;
1021                         c->data.map->op = T_OP_REG_EQ;
1022                 }
1023
1024                 /*
1025                  *      FOO !~ BAR --> !FOO =~ BAR
1026                  */
1027                 if (!c->negate && (c->data.map->op == T_OP_REG_NE)) {
1028                         c->negate = true;
1029                         c->data.map->op = T_OP_REG_EQ;
1030                 }
1031
1032                 /*
1033                  *      !FOO != BAR --> FOO == BAR
1034                  */
1035                 if (c->negate && (c->data.map->op == T_OP_NE)) {
1036                         c->negate = false;
1037                         c->data.map->op = T_OP_CMP_EQ;
1038                 }
1039
1040                 /*
1041                  *      This next one catches "LDAP-Group != foo",
1042                  *      which doesn't work as-is, but this hack fixes
1043                  *      it.
1044                  *
1045                  *      FOO != BAR --> !FOO == BAR
1046                  */
1047                 if (!c->negate && (c->data.map->op == T_OP_NE)) {
1048                         c->negate = true;
1049                         c->data.map->op = T_OP_CMP_EQ;
1050                 }
1051
1052                 /*
1053                  *      FOO =* BAR --> FOO
1054                  *      FOO !* BAR --> !FOO
1055                  */
1056                 if ((c->data.map->op == T_OP_CMP_TRUE) ||
1057                     (c->data.map->op == T_OP_CMP_FALSE)) {
1058                         value_pair_tmpl_t *vpt;
1059
1060                         vpt = talloc_steal(c, c->data.map->dst);
1061                         c->data.map->dst = NULL;
1062
1063                         /*
1064                          *      Invert the negation bit.
1065                          */
1066                         if (c->data.map->op == T_OP_CMP_FALSE) {
1067                                 c->negate = !c->negate;
1068                         }
1069
1070                         TALLOC_FREE(c->data.map);
1071
1072                         c->type = COND_TYPE_EXISTS;
1073                         c->data.vpt = vpt;
1074                         break;  /* it's no longer a map */
1075                 }
1076
1077                 /*
1078                  *      Both are data (IP address, integer, etc.)
1079                  *
1080                  *      We can do the evaluation here, so that it
1081                  *      doesn't need to be done at run time
1082                  */
1083                 if ((c->data.map->dst->type == VPT_TYPE_DATA) &&
1084                     (c->data.map->src->type == VPT_TYPE_DATA)) {
1085                         int rcode;
1086
1087                         rad_assert(c->cast != NULL);
1088
1089                         rcode = radius_evaluate_map(NULL, 0, 0, c);
1090                         TALLOC_FREE(c->data.map);
1091                         c->cast = NULL;
1092                         if (rcode) {
1093                                 c->type = COND_TYPE_TRUE;
1094                         } else {
1095                                 c->type = COND_TYPE_FALSE;
1096                         }
1097
1098                         break;  /* it's no longer a map */
1099                 }
1100
1101                 /*
1102                  *      Both are literal strings.  They're not parsed
1103                  *      as VPT_TYPE_DATA because there's no cast to an
1104                  *      attribute.
1105                  *
1106                  *      We can do the evaluation here, so that it
1107                  *      doesn't need to be done at run time
1108                  */
1109                 if ((c->data.map->src->type == VPT_TYPE_LITERAL) &&
1110                     (c->data.map->dst->type == VPT_TYPE_LITERAL) &&
1111                     !c->pass2_fixup) {
1112                         int rcode;
1113
1114                         rad_assert(c->cast == NULL);
1115
1116                         rcode = radius_evaluate_map(NULL, 0, 0, c);
1117                         if (rcode) {
1118                                 c->type = COND_TYPE_TRUE;
1119                         } else {
1120                                 DEBUG("OPTIMIZING %s %s --> FALSE",
1121                                       c->data.map->dst->name,
1122                                       c->data.map->src->name);
1123                                 c->type = COND_TYPE_FALSE;
1124                         }
1125
1126                         /*
1127                          *      Free map after using it above.
1128                          */
1129                         TALLOC_FREE(c->data.map);
1130                         break;
1131                 }
1132
1133                 /*
1134                  *      <ipaddr>"foo" CMP &Attribute-Name The cast is
1135                  *      unnecessary, and we can re-write it so that
1136                  *      the attribute reference is on the LHS.
1137                  */
1138                 if (c->cast &&
1139                     (c->data.map->src->type == VPT_TYPE_ATTR) &&
1140                     (c->data.map->dst->type != VPT_TYPE_ATTR)) {
1141                         value_pair_tmpl_t *tmp;
1142
1143                         tmp = c->data.map->src;
1144                         c->data.map->src = c->data.map->dst;
1145                         c->data.map->dst = tmp;
1146
1147                         c->cast = NULL;
1148
1149                         switch (c->data.map->op) {
1150                         case T_OP_CMP_EQ:
1151                                 /* do nothing */
1152                                 break;
1153
1154                         case T_OP_LE:
1155                                 c->data.map->op = T_OP_GE;
1156                                 break;
1157
1158                         case T_OP_LT:
1159                                 c->data.map->op = T_OP_GT;
1160                                 break;
1161
1162                         case T_OP_GE:
1163                                 c->data.map->op = T_OP_LE;
1164                                 break;
1165
1166                         case T_OP_GT:
1167                                 c->data.map->op = T_OP_LT;
1168                                 break;
1169
1170                         default:
1171                                 return_0("Internal sanity check failed");
1172                         }
1173
1174                         /*
1175                          *      This must have been parsed into VPT_TYPE_DATA.
1176                          */
1177                         rad_assert(c->data.map->src->type != VPT_TYPE_LITERAL);
1178                 }
1179
1180         } while (0);
1181
1182         /*
1183          *      Existence checks.  We short-circuit static strings,
1184          *      too.
1185          */
1186         if (c->type == COND_TYPE_EXISTS) {
1187                 switch (c->data.vpt->type) {
1188                 case VPT_TYPE_XLAT:
1189                 case VPT_TYPE_ATTR:
1190                 case VPT_TYPE_LIST:
1191                 case VPT_TYPE_EXEC:
1192                         break;
1193
1194                         /*
1195                          *      'true' and 'false' are special strings
1196                          *      which mean themselves.
1197                          *
1198                          *      For integers, 0 is false, all other
1199                          *      integers are true.
1200                          *
1201                          *      For strings, '' and "" are false.
1202                          *      'foo' and "foo" are true.
1203                          *
1204                          *      The str2tmpl function takes care of
1205                          *      marking "%{foo}" as VPT_TYPE_XLAT, so
1206                          *      the strings here are fixed at compile
1207                          *      time.
1208                          *
1209                          *      `exec` and "%{...}" are left alone.
1210                          *
1211                          *      Bare words must be module return
1212                          *      codes.
1213                          */
1214                 case VPT_TYPE_LITERAL:
1215                         if ((strcmp(c->data.vpt->name, "true") == 0) ||
1216                             (strcmp(c->data.vpt->name, "1") == 0)) {
1217                                 c->type = COND_TYPE_TRUE;
1218                                 TALLOC_FREE(c->data.vpt);
1219
1220                         } else if ((strcmp(c->data.vpt->name, "false") == 0) ||
1221                                    (strcmp(c->data.vpt->name, "0") == 0)) {
1222                                 c->type = COND_TYPE_FALSE;
1223                                 TALLOC_FREE(c->data.vpt);
1224
1225                         } else if (!*c->data.vpt->name) {
1226                                 c->type = COND_TYPE_FALSE;
1227                                 TALLOC_FREE(c->data.vpt);
1228
1229                         } else if ((lhs_type == T_SINGLE_QUOTED_STRING) ||
1230                                    (lhs_type == T_DOUBLE_QUOTED_STRING)) {
1231                                 c->type = COND_TYPE_TRUE;
1232                                 TALLOC_FREE(c->data.vpt);
1233
1234                         } else if (lhs_type == T_BARE_WORD) {
1235                                 int rcode;
1236                                 char const *q;
1237
1238                                 for (q = c->data.vpt->name;
1239                                      *q != '\0';
1240                                      q++) {
1241                                         if (!isdigit((int) *q)) {
1242                                                 break;
1243                                         }
1244                                 }
1245
1246                                 /*
1247                                  *      It's all digits, and therefore
1248                                  *      'true'.
1249                                  */
1250                                 if (!*q) {
1251                                         c->type = COND_TYPE_TRUE;
1252                                         TALLOC_FREE(c->data.vpt);
1253                                         break;
1254                                 }
1255
1256                                 rcode = fr_str2int(allowed_return_codes,
1257                                                    c->data.vpt->name, 0);
1258                                 if (!rcode) {
1259                                         return_0("Expected a module return code");
1260                                 }
1261                         }
1262
1263                         /*
1264                          *      Else lhs_type==T_OP_INVALID, and this
1265                          *      node was made by promoting a child
1266                          *      which had already been normalized.
1267                          */
1268                         break;
1269
1270                 case VPT_TYPE_DATA:
1271                         return_0("Cannot use data here");
1272
1273                 default:
1274                         return_0("Internal sanity check failed");
1275                 }
1276         }
1277
1278         /*
1279          *      !TRUE -> FALSE
1280          */
1281         if (c->type == COND_TYPE_TRUE) {
1282                 if (c->negate) {
1283                         c->negate = false;
1284                         c->type = COND_TYPE_FALSE;
1285                 }
1286         }
1287
1288         /*
1289          *      !FALSE -> TRUE
1290          */
1291         if (c->type == COND_TYPE_FALSE) {
1292                 if (c->negate) {
1293                         c->negate = false;
1294                         c->type = COND_TYPE_TRUE;
1295                 }
1296         }
1297
1298         /*
1299          *      true && FOO --> FOO
1300          */
1301         if ((c->type == COND_TYPE_TRUE) &&
1302             (c->next_op == COND_AND)) {
1303                 fr_cond_t *next;
1304
1305                 next = talloc_steal(ctx, c->next);
1306                 c->next = NULL;
1307
1308                 lhs = rhs = NULL;
1309                 talloc_free(c);
1310                 c = next;
1311         }
1312
1313         /*
1314          *      false && FOO --> false
1315          */
1316         if ((c->type == COND_TYPE_FALSE) &&
1317             (c->next_op == COND_AND)) {
1318                 talloc_free(c->next);
1319                 c->next = NULL;
1320                 c->next_op = COND_NONE;
1321         }
1322
1323         /*
1324          *      false || FOO --> FOO
1325          */
1326         if ((c->type == COND_TYPE_FALSE) &&
1327             (c->next_op == COND_OR)) {
1328                 fr_cond_t *next;
1329
1330                 next = talloc_steal(ctx, c->next);
1331                 c->next = NULL;
1332
1333                 lhs = rhs = NULL;
1334                 talloc_free(c);
1335                 c = next;
1336         }
1337
1338         /*
1339          *      true || FOO --> true
1340          */
1341         if ((c->type == COND_TYPE_TRUE) &&
1342             (c->next_op == COND_OR)) {
1343                 talloc_free(c->next);
1344                 c->next = NULL;
1345                 c->next_op = COND_NONE;
1346         }
1347
1348         if (lhs) talloc_free(lhs);
1349         if (rhs) talloc_free(rhs);
1350
1351         *pcond = c;
1352         return p - start;
1353 }
1354
1355 /** Tokenize a conditional check
1356  *
1357  *  @param[in] ctx for talloc
1358  *  @param[in] ci for CONF_ITEM
1359  *  @param[in] start the start of the string to process.  Should be "(..."
1360  *  @param[out] head the parsed condition structure
1361  *  @param[out] error the parse error (if any)
1362  *  @param[in] flags do one/two pass
1363  *  @return length of the string skipped, or when negative, the offset to the offending error
1364  */
1365 ssize_t fr_condition_tokenize(TALLOC_CTX *ctx, CONF_ITEM *ci, char const *start, fr_cond_t **head, char const **error, int flags)
1366 {
1367         return condition_tokenize(ctx, ci, start, false, head, error, flags);
1368 }
1369
1370 /*
1371  *      Walk in order.
1372  */
1373 bool fr_condition_walk(fr_cond_t *c, bool (*callback)(void *, fr_cond_t *), void *ctx)
1374 {
1375         while (c) {
1376                 /*
1377                  *      Process this one, exit on error.
1378                  */
1379                 if (!callback(ctx, c)) return false;
1380
1381                 switch (c->type) {
1382                 case COND_TYPE_INVALID:
1383                         return false;
1384
1385                 case COND_TYPE_EXISTS:
1386                 case COND_TYPE_MAP:
1387                 case COND_TYPE_TRUE:
1388                 case COND_TYPE_FALSE:
1389                         break;
1390
1391                 case COND_TYPE_CHILD:
1392                         /*
1393                          *      Walk over the child.
1394                          */
1395                         if (!fr_condition_walk(c->data.child, callback, ctx)) {
1396                                 return false;
1397                         }
1398                 }
1399
1400                 /*
1401                  *      No sibling, stop.
1402                  */
1403                 if (c->next_op == COND_NONE) break;
1404
1405                 /*
1406                  *      process the next sibling
1407                  */
1408                 c = c->next;
1409         }
1410
1411         return true;
1412 }