Add support for 'm' (multiline) regex flag
[freeradius.git] / src / main / modcall.c
1 /*
2  * @name modcall.c
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 2000,2006  The FreeRADIUS server project
21  */
22
23 RCSID("$Id$")
24
25 #include <freeradius-devel/radiusd.h>
26 #include <freeradius-devel/modpriv.h>
27 #include <freeradius-devel/modcall.h>
28 #include <freeradius-devel/parser.h>
29 #include <freeradius-devel/rad_assert.h>
30
31
32 /* mutually-recursive static functions need a prototype up front */
33 static modcallable *do_compile_modgroup(modcallable *,
34                                         rlm_components_t, CONF_SECTION *,
35                                         int, int, int);
36
37 /* Actions may be a positive integer (the highest one returned in the group
38  * will be returned), or the keyword "return", represented here by
39  * MOD_ACTION_RETURN, to cause an immediate return.
40  * There's also the keyword "reject", represented here by MOD_ACTION_REJECT
41  * to cause an immediate reject. */
42 #define MOD_ACTION_RETURN  (-1)
43 #define MOD_ACTION_REJECT  (-2)
44
45 /* Here are our basic types: modcallable, modgroup, and modsingle. For an
46  * explanation of what they are all about, see doc/configurable_failover.rst */
47 struct modcallable {
48         modcallable *parent;
49         struct modcallable *next;
50         char const *name;
51         char const *debug_name;
52         enum { MOD_SINGLE = 1, MOD_GROUP, MOD_LOAD_BALANCE, MOD_REDUNDANT_LOAD_BALANCE,
53 #ifdef WITH_UNLANG
54                MOD_IF, MOD_ELSE, MOD_ELSIF, MOD_UPDATE, MOD_SWITCH, MOD_CASE,
55                MOD_FOREACH, MOD_BREAK, MOD_RETURN,
56 #endif
57                MOD_POLICY, MOD_REFERENCE, MOD_XLAT } type;
58         rlm_components_t method;
59         int actions[RLM_MODULE_NUMCODES];
60 };
61
62 #define MOD_LOG_OPEN_BRACE RDEBUG2("%s {", c->debug_name)
63
64 #define MOD_LOG_CLOSE_BRACE RDEBUG2("} # %s = %s", c->debug_name, fr_int2str(mod_rcode_table, result, "<invalid>"))
65
66 typedef struct {
67         modcallable             mc;             /* self */
68         enum {
69                 GROUPTYPE_SIMPLE = 0,
70                 GROUPTYPE_REDUNDANT,
71                 GROUPTYPE_APPEND,
72                 GROUPTYPE_COUNT
73         } grouptype;                            /* after mc */
74         modcallable             *children;
75         modcallable             *tail;          /* of the children list */
76         CONF_SECTION            *cs;
77         value_pair_map_t        *map;           /* update */
78         value_pair_tmpl_t       *vpt;           /* switch */
79         fr_cond_t               *cond;          /* if/elsif */
80         bool                    done_pass2;
81 } modgroup;
82
83 typedef struct {
84         modcallable mc;
85         module_instance_t *modinst;
86 } modsingle;
87
88 typedef struct {
89         modcallable mc;
90         char const *ref_name;
91         CONF_SECTION *ref_cs;
92 } modref;
93
94 typedef struct {
95         modcallable mc;
96         int exec;
97         char *xlat_name;
98 } modxlat;
99
100 /* Simple conversions: modsingle and modgroup are subclasses of modcallable,
101  * so we often want to go back and forth between them. */
102 static modsingle *mod_callabletosingle(modcallable *p)
103 {
104         rad_assert(p->type==MOD_SINGLE);
105         return (modsingle *)p;
106 }
107 static modgroup *mod_callabletogroup(modcallable *p)
108 {
109         rad_assert((p->type > MOD_SINGLE) && (p->type <= MOD_POLICY));
110
111         return (modgroup *)p;
112 }
113 static modcallable *mod_singletocallable(modsingle *p)
114 {
115         return (modcallable *)p;
116 }
117 static modcallable *mod_grouptocallable(modgroup *p)
118 {
119         return (modcallable *)p;
120 }
121
122 static modref *mod_callabletoref(modcallable *p)
123 {
124         rad_assert(p->type==MOD_REFERENCE);
125         return (modref *)p;
126 }
127 static modcallable *mod_reftocallable(modref *p)
128 {
129         return (modcallable *)p;
130 }
131
132 static modxlat *mod_callabletoxlat(modcallable *p)
133 {
134         rad_assert(p->type==MOD_XLAT);
135         return (modxlat *)p;
136 }
137 static modcallable *mod_xlattocallable(modxlat *p)
138 {
139         return (modcallable *)p;
140 }
141
142 /* modgroups are grown by adding a modcallable to the end */
143 static void add_child(modgroup *g, modcallable *c)
144 {
145         if (!c) return;
146
147         (void) talloc_steal(g, c);
148
149         if (!g->children) {
150                 g->children = g->tail = c;
151         } else {
152                 rad_assert(g->tail->next == NULL);
153                 g->tail->next = c;
154                 g->tail = c;
155         }
156
157         c->parent = mod_grouptocallable(g);
158 }
159
160 /* Here's where we recognize all of our keywords: first the rcodes, then the
161  * actions */
162 const FR_NAME_NUMBER mod_rcode_table[] = {
163         { "reject",     RLM_MODULE_REJECT       },
164         { "fail",       RLM_MODULE_FAIL  },
165         { "ok",         RLM_MODULE_OK      },
166         { "handled",    RLM_MODULE_HANDLED      },
167         { "invalid",    RLM_MODULE_INVALID      },
168         { "userlock",   RLM_MODULE_USERLOCK     },
169         { "notfound",   RLM_MODULE_NOTFOUND     },
170         { "noop",       RLM_MODULE_NOOP  },
171         { "updated",    RLM_MODULE_UPDATED      },
172         { NULL, 0 }
173 };
174
175
176 static char const *group_name[];
177
178 /*
179  *      Compile action && rcode for later use.
180  */
181 static int compile_action(modcallable *c, CONF_PAIR *cp)
182 {
183         int action;
184         char const *attr, *value;
185
186         attr = cf_pair_attr(cp);
187         value = cf_pair_value(cp);
188         if (!value) return 0;
189
190         if (c->type != MOD_SINGLE) {
191                 ERROR("%s[%d] Invalid return code assigment inside of a %s section",
192                       cf_pair_filename(cp), cf_pair_lineno(cp), group_name[c->type]);
193                 return 0;
194         }
195
196         if (!strcasecmp(value, "return"))
197                 action = MOD_ACTION_RETURN;
198
199         else if (!strcasecmp(value, "break"))
200                 action = MOD_ACTION_RETURN;
201
202         else if (!strcasecmp(value, "reject"))
203                 action = MOD_ACTION_REJECT;
204
205         else if (strspn(value, "0123456789")==strlen(value)) {
206                 action = atoi(value);
207
208                 /*
209                  *      Don't allow priority zero, for future use.
210                  */
211                 if (action == 0) return 0;
212         } else {
213                 cf_log_err_cp(cp, "Unknown action '%s'.\n",
214                            value);
215                 return 0;
216         }
217
218         if (strcasecmp(attr, "default") != 0) {
219                 int rcode;
220
221                 rcode = fr_str2int(mod_rcode_table, attr, -1);
222                 if (rcode < 0) {
223                         cf_log_err_cp(cp,
224                                    "Unknown module rcode '%s'.\n",
225                                    attr);
226                         return 0;
227                 }
228                 c->actions[rcode] = action;
229
230         } else {                /* set all unset values to the default */
231                 int i;
232
233                 for (i = 0; i < RLM_MODULE_NUMCODES; i++) {
234                         if (!c->actions[i]) c->actions[i] = action;
235                 }
236         }
237
238         return 1;
239 }
240
241 /* Some short names for debugging output */
242 static char const * const comp2str[] = {
243         "authenticate",
244         "authorize",
245         "preacct",
246         "accounting",
247         "session",
248         "pre-proxy",
249         "post-proxy",
250         "post-auth"
251 #ifdef WITH_COA
252         ,
253         "recv-coa",
254         "send-coa"
255 #endif
256 };
257
258 #ifdef HAVE_PTHREAD_H
259 /*
260  *      Lock the mutex for the module
261  */
262 static void safe_lock(module_instance_t *instance)
263 {
264         if (instance->mutex)
265                 pthread_mutex_lock(instance->mutex);
266 }
267
268 /*
269  *      Unlock the mutex for the module
270  */
271 static void safe_unlock(module_instance_t *instance)
272 {
273         if (instance->mutex)
274                 pthread_mutex_unlock(instance->mutex);
275 }
276 #else
277 /*
278  *      No threads: these functions become NULL's.
279  */
280 #define safe_lock(foo)
281 #define safe_unlock(foo)
282 #endif
283
284 static rlm_rcode_t CC_HINT(nonnull) call_modsingle(rlm_components_t component, modsingle *sp, REQUEST *request)
285 {
286         int blocked;
287         int indent = request->log.indent;
288
289         /*
290          *      If the request should stop, refuse to do anything.
291          */
292         blocked = (request->master_state == REQUEST_STOP_PROCESSING);
293         if (blocked) return RLM_MODULE_NOOP;
294
295         RDEBUG3("modsingle[%s]: calling %s (%s) for request %d",
296                 comp2str[component], sp->modinst->name,
297                 sp->modinst->entry->name, request->number);
298         request->log.indent = 0;
299
300         if (sp->modinst->force) {
301                 request->rcode = sp->modinst->code;
302                 goto fail;
303         }
304
305         /*
306          *      For logging unresponsive children.
307          */
308         request->module = sp->modinst->name;
309
310         safe_lock(sp->modinst);
311         request->rcode = sp->modinst->entry->module->methods[component](sp->modinst->insthandle, request);
312         safe_unlock(sp->modinst);
313
314         request->module = "";
315
316         /*
317          *      Wasn't blocked, and now is.  Complain!
318          */
319         blocked = (request->master_state == REQUEST_STOP_PROCESSING);
320         if (blocked) {
321                 RWARN("Module %s became unblocked for request %u", sp->modinst->entry->name, request->number);
322         }
323
324  fail:
325         request->log.indent = indent;
326         RDEBUG3("modsingle[%s]: returned from %s (%s) for request %d",
327                comp2str[component], sp->modinst->name,
328                sp->modinst->entry->name, request->number);
329
330         return request->rcode;
331 }
332
333 static int default_component_results[RLM_COMPONENT_COUNT] = {
334         RLM_MODULE_REJECT,      /* AUTH */
335         RLM_MODULE_NOTFOUND,    /* AUTZ */
336         RLM_MODULE_NOOP,        /* PREACCT */
337         RLM_MODULE_NOOP,        /* ACCT */
338         RLM_MODULE_FAIL,        /* SESS */
339         RLM_MODULE_NOOP,        /* PRE_PROXY */
340         RLM_MODULE_NOOP,        /* POST_PROXY */
341         RLM_MODULE_NOOP         /* POST_AUTH */
342 #ifdef WITH_COA
343         ,
344         RLM_MODULE_NOOP,        /* RECV_COA_TYPE */
345         RLM_MODULE_NOOP         /* SEND_COA_TYPE */
346 #endif
347 };
348
349
350 static char const *group_name[] = {
351         "",
352         "single",
353         "group",
354         "load-balance group",
355         "redundant-load-balance group",
356 #ifdef WITH_UNLANG
357         "if",
358         "else",
359         "elsif",
360         "update",
361         "switch",
362         "case",
363         "foreach",
364         "break",
365         "return",
366 #endif
367         "policy",
368         "reference",
369         "xlat"
370 };
371
372 static char const modcall_spaces[] = "                                                                ";
373
374 #define MODCALL_STACK_MAX (32)
375
376 /*
377  *      Don't call the modules recursively.  Instead, do them
378  *      iteratively, and manage the call stack ourselves.
379  */
380 typedef struct modcall_stack_entry_t {
381         rlm_rcode_t result;
382         int priority;
383         int unwind;             /* unwind to this one if it exists */
384         modcallable *c;
385 } modcall_stack_entry_t;
386
387
388 static bool modcall_recurse(REQUEST *request, rlm_components_t component, int depth,
389                             modcall_stack_entry_t *entry);
390
391 /*
392  *      Call a child of a block.
393  */
394 static void modcall_child(REQUEST *request, rlm_components_t component, int depth,
395                           modcall_stack_entry_t *entry, modcallable *c,
396                           rlm_rcode_t *result)
397 {
398         modcall_stack_entry_t *next;
399
400         if (depth >= MODCALL_STACK_MAX) {
401                 ERROR("Internal sanity check failed: module stack is too deep");
402                 fr_exit(1);
403         }
404
405         /*
406          *      Initialize the childs stack frame.
407          */
408         next = entry + 1;
409         next->c = c;
410         next->result = entry->result;
411         next->priority = 0;
412         next->unwind = 0;
413
414         if (!modcall_recurse(request, component,
415                              depth, next)) {
416                 *result = RLM_MODULE_FAIL;
417                  return;
418         }
419
420         /*
421          *      Unwind back up the stack
422          */
423         if (next->unwind != 0) {
424                 entry->unwind = next->unwind;
425         }
426
427         *result = next->result;
428
429         return;
430 }
431
432
433 /*
434  *      Interpret the various types of blocks.
435  */
436 static bool modcall_recurse(REQUEST *request, rlm_components_t component, int depth,
437                             modcall_stack_entry_t *entry)
438 {
439         bool if_taken, was_if;
440         modcallable *c;
441         int priority;
442         rlm_rcode_t result;
443
444         was_if = if_taken = false;
445         result = RLM_MODULE_UNKNOWN;
446         RINDENT();
447
448 redo:
449         priority = -1;
450         c = entry->c;
451
452         /*
453          *      Nothing more to do.  Return the code and priority
454          *      which was set by the caller.
455          */
456         if (!c) goto finish;
457
458         /*
459          *      We've been asked to stop.  Do so.
460          */
461         if ((request->master_state == REQUEST_STOP_PROCESSING) ||
462             (request->parent &&
463              (request->parent->master_state == REQUEST_STOP_PROCESSING))) {
464                 entry->result = RLM_MODULE_FAIL;
465                 entry->priority = 9999;
466                 goto finish;
467         }
468
469 #ifdef WITH_UNLANG
470         /*
471          *      Handle "if" conditions.
472          */
473         if (c->type == MOD_IF) {
474                 int condition;
475                 modgroup *g;
476
477         mod_if:
478                 g = mod_callabletogroup(c);
479                 rad_assert(g->cond != NULL);
480
481                 RDEBUG2("%s %s{", group_name[c->type], c->name);
482
483                 condition = radius_evaluate_cond(request, result, 0, g->cond);
484                 if (condition < 0) {
485                         condition = false;
486                         REDEBUG("Failed retrieving values required to evaluate condition");
487                 } else {
488                         RDEBUG2("%s %s -> %s",
489                                 group_name[c->type],
490                                 c->name, condition ? "TRUE" : "FALSE");
491                 }
492
493                 /*
494                  *      Didn't pass.  Remember that.
495                  */
496                 if (!condition) {
497                         was_if = true;
498                         if_taken = false;
499                         goto next_sibling;
500                 }
501
502                 /*
503                  *      We took the "if".  Go recurse into its' children.
504                  */
505                 was_if = true;
506                 if_taken = true;
507                 goto do_children;
508         } /* MOD_IF */
509
510         /*
511          *      "else" if the previous "if" was taken.
512          *      "if" if the previous if wasn't taken.
513          */
514         if (c->type == MOD_ELSIF) {
515                 if (!was_if) goto elsif_error;
516
517                 /*
518                  *      Like MOD_ELSE, but allow for a later "else"
519                  */
520                 if (if_taken) {
521                         RDEBUG2("... skipping %s for request %d: Preceding \"if\" was taken",
522                                 group_name[c->type], request->number);
523                         was_if = true;
524                         if_taken = true;
525                         goto next_sibling;
526                 }
527
528                 /*
529                  *      Check the "if" condition.
530                  */
531                 goto mod_if;
532         } /* MOD_ELSIF */
533
534         /*
535          *      "else" for a preceding "if".
536          */
537         if (c->type == MOD_ELSE) {
538                 if (!was_if) { /* error */
539                 elsif_error:
540                         RDEBUG2("... skipping %s for request %d: No preceding \"if\"",
541                                 group_name[c->type], request->number);
542                         goto next_sibling;
543                 }
544
545                 if (if_taken) {
546                         RDEBUG2("... skipping %s for request %d: Preceding \"if\" was taken",
547                                 group_name[c->type], request->number);
548                         was_if = false;
549                         if_taken = false;
550                         goto next_sibling;
551                 }
552
553                 /*
554                  *      We need to process it.  Go do that.
555                  */
556                 was_if = false;
557                 if_taken = false;
558                 goto do_children;
559         } /* MOD_ELSE */
560
561         /*
562          *      We're no longer processing if/else/elsif.  Reset the
563          *      trackers for those conditions.
564          */
565         was_if = false;
566         if_taken = false;
567 #endif  /* WITH_UNLANG */
568
569         if (c->type == MOD_SINGLE) {
570                 modsingle *sp;
571
572                 /*
573                  *      Process a stand-alone child, and fall through
574                  *      to dealing with it's parent.
575                  */
576                 sp = mod_callabletosingle(c);
577
578                 result = call_modsingle(c->method, sp, request);
579                 RDEBUG2("[%s] = %s", c->name ? c->name : "",
580                         fr_int2str(mod_rcode_table, result, "<invalid>"));
581                 goto calculate_result;
582         } /* MOD_SINGLE */
583
584 #ifdef WITH_UNLANG
585         /*
586          *      Update attribute(s)
587          */
588         if (c->type == MOD_UPDATE) {
589                 int rcode;
590                 modgroup *g = mod_callabletogroup(c);
591                 value_pair_map_t *map;
592
593                 MOD_LOG_OPEN_BRACE;
594                 RINDENT();
595                 for (map = g->map; map != NULL; map = map->next) {
596                         rcode = map_to_request(request, map, map_to_vp, NULL);
597                         if (rcode < 0) {
598                                 result = (rcode == -2) ? RLM_MODULE_INVALID : RLM_MODULE_FAIL;
599                                 REXDENT();
600                                 MOD_LOG_CLOSE_BRACE;
601                                 goto calculate_result;
602                         }
603                 }
604                 REXDENT();
605                 result = RLM_MODULE_NOOP;
606                 MOD_LOG_CLOSE_BRACE;
607                 goto calculate_result;
608         } /* MOD_IF */
609
610         /*
611          *      Loop over a set of attributes.
612          */
613         if (c->type == MOD_FOREACH) {
614                 int i, foreach_depth = -1;
615                 VALUE_PAIR *vps, *vp;
616                 modcall_stack_entry_t *next = NULL;
617                 vp_cursor_t copy;
618                 modgroup *g = mod_callabletogroup(c);
619
620                 if (depth >= MODCALL_STACK_MAX) {
621                         ERROR("Internal sanity check failed: module stack is too deep");
622                         fr_exit(1);
623                 }
624
625                 /*
626                  *      Figure out how deep we are in nesting by looking at request_data
627                  *      stored previously.
628                  */
629                 for (i = 0; i < 8; i++) {
630                         if (!request_data_reference(request,
631                                                     radius_get_vp, i)) {
632                                 foreach_depth = i;
633                                 break;
634                         }
635                 }
636
637                 if (foreach_depth < 0) {
638                         REDEBUG("foreach Nesting too deep!");
639                         result = RLM_MODULE_FAIL;
640                         goto calculate_result;
641                 }
642
643                 /*
644                  *      Copy the VPs from the original request, this ensures deterministic
645                  *      behaviour if someone decides to add or remove VPs in the set were
646                  *      iterating over.
647                  */
648                 if (tmpl_copy_vps(request, &vps, request, g->vpt) < 0) {        /* nothing to loop over */
649                         MOD_LOG_OPEN_BRACE;
650                         result = RLM_MODULE_NOOP;
651                         MOD_LOG_CLOSE_BRACE;
652                         goto calculate_result;
653                 }
654
655                 rad_assert(vps != NULL);
656                 fr_cursor_init(&copy, &vps);
657
658                 RDEBUG2("foreach %s ", c->name);
659
660                 /*
661                  *      This is the actual body of the foreach loop
662                  */
663                 for (vp = fr_cursor_first(&copy);
664                      vp != NULL;
665                      vp = fr_cursor_next(&copy)) {
666 #ifndef NDEBUG
667                         if (fr_debug_flag >= 2) {
668                                 char buffer[1024];
669
670                                 vp_prints_value(buffer, sizeof(buffer), vp, '"');
671                                 RDEBUG2("# Foreach-Variable-%d = %s", foreach_depth, buffer);
672                         }
673 #endif
674
675                         /*
676                          *      Add the vp to the request, so that
677                          *      xlat.c, xlat_foreach() can find it.
678                          */
679                         request_data_add(request, radius_get_vp, foreach_depth, &vp, false);
680
681                         /*
682                          *      Initialize the childs stack frame.
683                          */
684                         next = entry + 1;
685                         next->c = g->children;
686                         next->result = entry->result;
687                         next->priority = 0;
688                         next->unwind = 0;
689
690                         if (!modcall_recurse(request, component, depth + 1, next)) {
691                                 break;
692                         }
693
694                         /*
695                          *      We've unwound to the enclosing
696                          *      "foreach".  Stop the unwinding.
697                          */
698                         if (next->unwind == MOD_FOREACH) {
699                                 break;
700                         }
701
702                         /*
703                          *      Unwind all the way.
704                          */
705                         if (next->unwind == MOD_RETURN) {
706                                 entry->unwind = MOD_RETURN;
707                                 break;
708                         }
709                 } /* loop over VPs */
710
711                 /*
712                  *      Free the copied vps and the request data
713                  *      If we don't remove the request data, something could call
714                  *      the xlat outside of a foreach loop and trigger a segv.
715                  */
716                 pairfree(&vps);
717                 request_data_get(request, radius_get_vp, foreach_depth);
718
719                 rad_assert(next != NULL);
720                 result = next->result;
721                 priority = next->priority;
722                 MOD_LOG_CLOSE_BRACE;
723                 goto calculate_result;
724         } /* MOD_FOREACH */
725
726         /*
727          *      Break out of a "foreach" loop, or return from a nested
728          *      group.
729          */
730         if ((c->type == MOD_BREAK) || (c->type == MOD_RETURN)) {
731                 int i;
732                 VALUE_PAIR **copy_p;
733
734                 RDEBUG2("%s", group_name[c->type]);
735
736                 for (i = 8; i >= 0; i--) {
737                         copy_p = request_data_get(request, radius_get_vp, i);
738                         if (copy_p) {
739                                 if (c->type == MOD_BREAK) {
740                                         RDEBUG2("# break Foreach-Variable-%d", i);
741                                         break;
742                                 }
743                         }
744                 }
745
746                 /*
747                  *      Leave result / priority on the stack, and stop processing the section.
748                  */
749                 entry->unwind = c->type;
750                 goto finish;
751         } /* MOD_BREAK */
752
753 #endif    /* WITH_UNLANG */
754
755         /*
756          *      Child is a group that has children of it's own.
757          */
758         if ((c->type == MOD_GROUP) || (c->type == MOD_POLICY)
759 #ifdef WITH_UNLANG
760             || (c->type == MOD_CASE)
761 #endif
762                 ) {
763                 modgroup *g;
764
765 #ifdef WITH_UNLANG
766         do_children:
767 #endif
768                 g = mod_callabletogroup(c);
769
770                 /*
771                  *      This should really have been caught in the
772                  *      compiler, and the node never generated.  But
773                  *      doing that requires changing it's API so that
774                  *      it returns a flag instead of the compiled
775                  *      MOD_GROUP.
776                  */
777                 if (!g->children) {
778                         RDEBUG2("%s { ... } # empty sub-section is ignored", c->name);
779                         goto next_sibling;
780                 }
781
782                 MOD_LOG_OPEN_BRACE;
783                 modcall_child(request, component,
784                               depth + 1, entry, g->children,
785                               &result);
786                 MOD_LOG_CLOSE_BRACE;
787                 goto calculate_result;
788         } /* MOD_GROUP */
789
790 #ifdef WITH_UNLANG
791         if (c->type == MOD_SWITCH) {
792                 modcallable *this, *found, *null_case;
793                 modgroup *g, *h;
794                 fr_cond_t cond;
795                 value_data_t data;
796                 value_pair_map_t map;
797                 value_pair_tmpl_t vpt;
798
799                 MOD_LOG_OPEN_BRACE;
800
801                 g = mod_callabletogroup(c);
802
803                 memset(&cond, 0, sizeof(cond));
804                 memset(&map, 0, sizeof(map));
805
806                 cond.type = COND_TYPE_MAP;
807                 cond.data.map = &map;
808
809                 map.op = T_OP_CMP_EQ;
810                 map.ci = cf_sectiontoitem(g->cs);
811
812                 rad_assert(g->vpt != NULL);
813
814                 null_case = found = NULL;
815                 data.ptr = NULL;
816
817                 /*
818                  *      The attribute doesn't exist.  We can skip
819                  *      directly to the default 'case' statement.
820                  */
821                 if ((g->vpt->type == TMPL_TYPE_ATTR) && (tmpl_find_vp(NULL, request, g->vpt) < 0)) {
822                 find_null_case:
823                         for (this = g->children; this; this = this->next) {
824                                 rad_assert(this->type == MOD_CASE);
825
826                                 h = mod_callabletogroup(this);
827                                 if (h->vpt) continue;
828
829                                 found = this;
830                                 break;
831                         }
832
833                         goto do_null_case;
834                 }
835
836                 /*
837                  *      Expand the template if necessary, so that it
838                  *      is evaluated once instead of for each 'case'
839                  *      statement.
840                  */
841                 if ((g->vpt->type == TMPL_TYPE_XLAT_STRUCT) ||
842                     (g->vpt->type == TMPL_TYPE_XLAT) ||
843                     (g->vpt->type == TMPL_TYPE_EXEC)) {
844                         if (radius_expand_tmpl(&data, request, g->vpt) < 0) goto find_null_case;
845                         tmpl_init(&vpt, TMPL_TYPE_LITERAL, data.strvalue, talloc_array_length(data.strvalue) - 1);
846                 }
847
848                 /*
849                  *      Find either the exact matching name, or the
850                  *      "case {...}" statement.
851                  */
852                 for (this = g->children; this; this = this->next) {
853                         rad_assert(this->type == MOD_CASE);
854
855                         h = mod_callabletogroup(this);
856
857                         /*
858                          *      Remember the default case
859                          */
860                         if (!h->vpt) {
861                                 if (!null_case) null_case = this;
862                                 continue;
863                         }
864
865                         /*
866                          *      If we're switching over an attribute
867                          *      AND we haven't pre-parsed the data for
868                          *      the case statement, then cast the data
869                          *      to the type of the attribute.
870                          */
871                         if ((g->vpt->type == TMPL_TYPE_ATTR) &&
872                             (h->vpt->type != TMPL_TYPE_DATA)) {
873                                 map.rhs = g->vpt;
874                                 map.lhs = h->vpt;
875                                 cond.cast = g->vpt->tmpl_da;
876
877                                 /*
878                                  *      Remove unnecessary casting.
879                                  */
880                                 if ((h->vpt->type == TMPL_TYPE_ATTR) &&
881                                     (g->vpt->tmpl_da->type == h->vpt->tmpl_da->type)) {
882                                         cond.cast = NULL;
883                                 }
884
885                                 /*
886                                  *      Use the pre-expanded string.
887                                  */
888                         } else if ((g->vpt->type == TMPL_TYPE_XLAT_STRUCT) ||
889                                    (g->vpt->type == TMPL_TYPE_XLAT) ||
890                                    (g->vpt->type == TMPL_TYPE_EXEC)) {
891                                 map.rhs = h->vpt;
892                                 map.lhs = &vpt;
893                                 cond.cast = NULL;
894
895                                 /*
896                                  *      Else evaluate the 'switch' statement.
897                                  */
898                         } else {
899                                 map.rhs = h->vpt;
900                                 map.lhs = g->vpt;
901                                 cond.cast = NULL;
902                         }
903
904                         if (radius_evaluate_map(request, RLM_MODULE_UNKNOWN, 0,
905                                                 &cond) == 1) {
906                                 found = this;
907                                 break;
908                         }
909                 }
910
911                 if (!found) found = null_case;
912
913         do_null_case:
914                 talloc_free(data.ptr);
915                 modcall_child(request, component, depth + 1, entry, found, &result);
916                 MOD_LOG_CLOSE_BRACE;
917                 goto calculate_result;
918         } /* MOD_SWITCH */
919 #endif
920
921         if ((c->type == MOD_LOAD_BALANCE) ||
922             (c->type == MOD_REDUNDANT_LOAD_BALANCE)) {
923                 uint32_t count = 0;
924                 modcallable *this, *found;
925                 modgroup *g;
926
927                 MOD_LOG_OPEN_BRACE;
928
929                 g = mod_callabletogroup(c);
930                 found = g->children;
931                 rad_assert(g->children != NULL);
932
933                 /*
934                  *      Choose a child at random.
935                  */
936                 for (this = g->children; this; this = this->next) {
937                         count++;
938
939                         if ((count * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
940                                 found = this;
941                         }
942                 }
943
944                 MOD_LOG_OPEN_BRACE;
945
946                 if (c->type == MOD_LOAD_BALANCE) {
947                         modcall_child(request, component,
948                                       depth + 1, entry, found,
949                                       &result);
950
951                 } else {
952                         this = found;
953
954                         do {
955                                 modcall_child(request, component,
956                                               depth + 1, entry, this,
957                                               &result);
958                                 if (this->actions[result] == MOD_ACTION_RETURN) {
959                                         priority = -1;
960                                         break;
961                                 }
962
963                                 this = this->next;
964                                 if (!this) this = g->children;
965                         } while (this != found);
966                 }
967                 MOD_LOG_CLOSE_BRACE;
968                 goto calculate_result;
969         } /* MOD_LOAD_BALANCE */
970
971         /*
972          *      Reference another virtual server.
973          *
974          *      This should really be deleted, and replaced with a
975          *      more abstracted / functional version.
976          */
977         if (c->type == MOD_REFERENCE) {
978                 modref *mr = mod_callabletoref(c);
979                 char const *server = request->server;
980
981                 if (server == mr->ref_name) {
982                         RWDEBUG("Suppressing recursive call to server %s", server);
983                         goto next_sibling;
984                 }
985
986                 request->server = mr->ref_name;
987                 RDEBUG("server %s { # nested call", mr->ref_name);
988                 result = indexed_modcall(component, 0, request);
989                 RDEBUG("} # server %s with nested call", mr->ref_name);
990                 request->server = server;
991                 goto calculate_result;
992         } /* MOD_REFERENCE */
993
994         /*
995          *      xlat a string without doing anything else
996          *
997          *      This should really be deleted, and replaced with a
998          *      more abstracted / functional version.
999          */
1000         if (c->type == MOD_XLAT) {
1001                 modxlat *mx = mod_callabletoxlat(c);
1002                 char buffer[128];
1003
1004                 if (!mx->exec) {
1005                         radius_xlat(buffer, sizeof(buffer), request, mx->xlat_name, NULL, NULL);
1006                 } else {
1007                         RDEBUG("`%s`", mx->xlat_name);
1008                         radius_exec_program(NULL, 0, NULL, request, mx->xlat_name, request->packet->vps,
1009                                             false, true, EXEC_TIMEOUT);
1010                 }
1011
1012                 goto next_sibling;
1013         } /* MOD_XLAT */
1014
1015         /*
1016          *      Add new module types here.
1017          */
1018
1019 calculate_result:
1020 #if 0
1021         RDEBUG("(%s, %d) ? (%s, %d)",
1022                fr_int2str(mod_rcode_table, result, "<invalid>"),
1023                priority,
1024                fr_int2str(mod_rcode_table, entry->result, "<invalid>"),
1025                entry->priority);
1026 #endif
1027
1028
1029         rad_assert(result != RLM_MODULE_UNKNOWN);
1030
1031         /*
1032          *      The child's action says return.  Do so.
1033          */
1034         if ((c->actions[result] == MOD_ACTION_RETURN) &&
1035             (priority <= 0)) {
1036                 entry->result = result;
1037                 goto finish;
1038         }
1039
1040         /*
1041          *      If "reject", break out of the loop and return
1042          *      reject.
1043          */
1044         if (c->actions[result] == MOD_ACTION_REJECT) {
1045                 entry->result = RLM_MODULE_REJECT;
1046                 goto finish;
1047         }
1048
1049         /*
1050          *      The array holds a default priority for this return
1051          *      code.  Grab it in preference to any unset priority.
1052          */
1053         if (priority < 0) {
1054                 priority = c->actions[result];
1055         }
1056
1057         /*
1058          *      We're higher than any previous priority, remember this
1059          *      return code and priority.
1060          */
1061         if (priority > entry->priority) {
1062                 entry->result = result;
1063                 entry->priority = priority;
1064         }
1065
1066 #ifdef WITH_UNLANG
1067         /*
1068          *      If we're processing a "case" statement, we return once
1069          *      it's done, rather than going to the next "case" statement.
1070          */
1071         if (c->type == MOD_CASE) goto finish;
1072 #endif
1073
1074         /*
1075          *      If we've been told to stop processing
1076          *      it, do so.
1077          */
1078         if (entry->unwind == MOD_BREAK) {
1079                 RDEBUG2("# unwind to enclosing foreach");
1080                 entry->unwind = 0;
1081                 goto finish;
1082         }
1083
1084         if (entry->unwind == MOD_RETURN) {
1085                 goto finish;
1086         }
1087
1088 next_sibling:
1089         entry->c = entry->c->next;
1090
1091         if (entry->c) goto redo;
1092
1093 finish:
1094         /*
1095          *      And we're done!
1096          */
1097         REXDENT();
1098         return true;
1099 }
1100
1101
1102 /** Call a module, iteratively, with a local stack, rather than recursively
1103  *
1104  * What did Paul Graham say about Lisp...?
1105  */
1106 int modcall(rlm_components_t component, modcallable *c, REQUEST *request)
1107 {
1108         modcall_stack_entry_t stack[MODCALL_STACK_MAX];
1109
1110 #ifndef NDEBUG
1111         memset(stack, 0, sizeof(stack));
1112 #endif
1113         /*
1114          *      Set up the initial stack frame.
1115          */
1116         stack[0].c = c;
1117         stack[0].result = default_component_results[component];
1118         stack[0].priority = 0;
1119         stack[0].unwind = 0;
1120
1121         /*
1122          *      Call the main handler.
1123          */
1124         if (!modcall_recurse(request, component, 0, &stack[0])) {
1125                 return RLM_MODULE_FAIL;
1126         }
1127
1128         /*
1129          *      Return the result.
1130          */
1131         return stack[0].result;
1132 }
1133
1134
1135 #if 0
1136 static char const *action2str(int action)
1137 {
1138         static char buf[32];
1139         if(action==MOD_ACTION_RETURN)
1140                 return "return";
1141         if(action==MOD_ACTION_REJECT)
1142                 return "reject";
1143         snprintf(buf, sizeof buf, "%d", action);
1144         return buf;
1145 }
1146
1147 /* If you suspect a bug in the parser, you'll want to use these dump
1148  * functions. dump_tree should reproduce a whole tree exactly as it was found
1149  * in radiusd.conf, but in long form (all actions explicitly defined) */
1150 static void dump_mc(modcallable *c, int indent)
1151 {
1152         int i;
1153
1154         if(c->type==MOD_SINGLE) {
1155                 modsingle *single = mod_callabletosingle(c);
1156                 DEBUG("%.*s%s {", indent, "\t\t\t\t\t\t\t\t\t\t\t",
1157                         single->modinst->name);
1158         } else if ((c->type > MOD_SINGLE) && (c->type <= MOD_POLICY)) {
1159                 modgroup *g = mod_callabletogroup(c);
1160                 modcallable *p;
1161                 DEBUG("%.*s%s {", indent, "\t\t\t\t\t\t\t\t\t\t\t",
1162                       group_name[c->type]);
1163                 for(p = g->children;p;p = p->next)
1164                         dump_mc(p, indent+1);
1165         } /* else ignore it for now */
1166
1167         for(i = 0; i<RLM_MODULE_NUMCODES; ++i) {
1168                 DEBUG("%.*s%s = %s", indent+1, "\t\t\t\t\t\t\t\t\t\t\t",
1169                       fr_int2str(mod_rcode_table, i, "<invalid>"),
1170                       action2str(c->actions[i]));
1171         }
1172
1173         DEBUG("%.*s}", indent, "\t\t\t\t\t\t\t\t\t\t\t");
1174 }
1175
1176 static void dump_tree(rlm_components_t comp, modcallable *c)
1177 {
1178         DEBUG("[%s]", comp2str[comp]);
1179         dump_mc(c, 0);
1180 }
1181 #else
1182 #define dump_tree(a, b)
1183 #endif
1184
1185 /* These are the default actions. For each component, the group{} block
1186  * behaves like the code from the old module_*() function. redundant{} and
1187  * append{} are based on my guesses of what they will be used for. --Pac. */
1188 static const int
1189 defaultactions[RLM_COMPONENT_COUNT][GROUPTYPE_COUNT][RLM_MODULE_NUMCODES] =
1190 {
1191         /* authenticate */
1192         {
1193                 /* group */
1194                 {
1195                         MOD_ACTION_RETURN,      /* reject   */
1196                         1,                      /* fail     */
1197                         MOD_ACTION_RETURN,      /* ok       */
1198                         MOD_ACTION_RETURN,      /* handled  */
1199                         1,                      /* invalid  */
1200                         MOD_ACTION_RETURN,      /* userlock */
1201                         MOD_ACTION_RETURN,      /* notfound */
1202                         1,                      /* noop     */
1203                         1                       /* updated  */
1204                 },
1205                 /* redundant */
1206                 {
1207                         MOD_ACTION_RETURN,      /* reject   */
1208                         1,                      /* fail     */
1209                         MOD_ACTION_RETURN,      /* ok       */
1210                         MOD_ACTION_RETURN,      /* handled  */
1211                         MOD_ACTION_RETURN,      /* invalid  */
1212                         MOD_ACTION_RETURN,      /* userlock */
1213                         MOD_ACTION_RETURN,      /* notfound */
1214                         MOD_ACTION_RETURN,      /* noop     */
1215                         MOD_ACTION_RETURN       /* updated  */
1216                 },
1217                 /* append */
1218                 {
1219                         MOD_ACTION_RETURN,      /* reject   */
1220                         1,                      /* fail     */
1221                         MOD_ACTION_RETURN,      /* ok       */
1222                         MOD_ACTION_RETURN,      /* handled  */
1223                         MOD_ACTION_RETURN,      /* invalid  */
1224                         MOD_ACTION_RETURN,      /* userlock */
1225                         2,                      /* notfound */
1226                         MOD_ACTION_RETURN,      /* noop     */
1227                         MOD_ACTION_RETURN       /* updated  */
1228                 }
1229         },
1230         /* authorize */
1231         {
1232                 /* group */
1233                 {
1234                         MOD_ACTION_RETURN,      /* reject   */
1235                         MOD_ACTION_RETURN,      /* fail     */
1236                         3,                      /* ok       */
1237                         MOD_ACTION_RETURN,      /* handled  */
1238                         MOD_ACTION_RETURN,      /* invalid  */
1239                         MOD_ACTION_RETURN,      /* userlock */
1240                         1,                      /* notfound */
1241                         2,                      /* noop     */
1242                         4                       /* updated  */
1243                 },
1244                 /* redundant */
1245                 {
1246                         MOD_ACTION_RETURN,      /* reject   */
1247                         1,                      /* fail     */
1248                         MOD_ACTION_RETURN,      /* ok       */
1249                         MOD_ACTION_RETURN,      /* handled  */
1250                         MOD_ACTION_RETURN,      /* invalid  */
1251                         MOD_ACTION_RETURN,      /* userlock */
1252                         MOD_ACTION_RETURN,      /* notfound */
1253                         MOD_ACTION_RETURN,      /* noop     */
1254                         MOD_ACTION_RETURN       /* updated  */
1255                 },
1256                 /* append */
1257                 {
1258                         MOD_ACTION_RETURN,      /* reject   */
1259                         1,                      /* fail     */
1260                         MOD_ACTION_RETURN,      /* ok       */
1261                         MOD_ACTION_RETURN,      /* handled  */
1262                         MOD_ACTION_RETURN,      /* invalid  */
1263                         MOD_ACTION_RETURN,      /* userlock */
1264                         2,                      /* notfound */
1265                         MOD_ACTION_RETURN,      /* noop     */
1266                         MOD_ACTION_RETURN       /* updated  */
1267                 }
1268         },
1269         /* preacct */
1270         {
1271                 /* group */
1272                 {
1273                         MOD_ACTION_RETURN,      /* reject   */
1274                         MOD_ACTION_RETURN,      /* fail     */
1275                         2,                      /* ok       */
1276                         MOD_ACTION_RETURN,      /* handled  */
1277                         MOD_ACTION_RETURN,      /* invalid  */
1278                         MOD_ACTION_RETURN,      /* userlock */
1279                         MOD_ACTION_RETURN,      /* notfound */
1280                         1,                      /* noop     */
1281                         3                       /* updated  */
1282                 },
1283                 /* redundant */
1284                 {
1285                         MOD_ACTION_RETURN,      /* reject   */
1286                         1,                      /* fail     */
1287                         MOD_ACTION_RETURN,      /* ok       */
1288                         MOD_ACTION_RETURN,      /* handled  */
1289                         MOD_ACTION_RETURN,      /* invalid  */
1290                         MOD_ACTION_RETURN,      /* userlock */
1291                         MOD_ACTION_RETURN,      /* notfound */
1292                         MOD_ACTION_RETURN,      /* noop     */
1293                         MOD_ACTION_RETURN       /* updated  */
1294                 },
1295                 /* append */
1296                 {
1297                         MOD_ACTION_RETURN,      /* reject   */
1298                         1,                      /* fail     */
1299                         MOD_ACTION_RETURN,      /* ok       */
1300                         MOD_ACTION_RETURN,      /* handled  */
1301                         MOD_ACTION_RETURN,      /* invalid  */
1302                         MOD_ACTION_RETURN,      /* userlock */
1303                         2,                      /* notfound */
1304                         MOD_ACTION_RETURN,      /* noop     */
1305                         MOD_ACTION_RETURN       /* updated  */
1306                 }
1307         },
1308         /* accounting */
1309         {
1310                 /* group */
1311                 {
1312                         MOD_ACTION_RETURN,      /* reject   */
1313                         MOD_ACTION_RETURN,      /* fail     */
1314                         2,                      /* ok       */
1315                         MOD_ACTION_RETURN,      /* handled  */
1316                         MOD_ACTION_RETURN,      /* invalid  */
1317                         MOD_ACTION_RETURN,      /* userlock */
1318                         MOD_ACTION_RETURN,      /* notfound */
1319                         1,                      /* noop     */
1320                         3                       /* updated  */
1321                 },
1322                 /* redundant */
1323                 {
1324                         1,                      /* reject   */
1325                         1,                      /* fail     */
1326                         MOD_ACTION_RETURN,      /* ok       */
1327                         MOD_ACTION_RETURN,      /* handled  */
1328                         1,                      /* invalid  */
1329                         1,                      /* userlock */
1330                         1,                      /* notfound */
1331                         2,                      /* noop     */
1332                         4                       /* updated  */
1333                 },
1334                 /* append */
1335                 {
1336                         MOD_ACTION_RETURN,      /* reject   */
1337                         1,                      /* fail     */
1338                         MOD_ACTION_RETURN,      /* ok       */
1339                         MOD_ACTION_RETURN,      /* handled  */
1340                         MOD_ACTION_RETURN,      /* invalid  */
1341                         MOD_ACTION_RETURN,      /* userlock */
1342                         2,                      /* notfound */
1343                         MOD_ACTION_RETURN,      /* noop     */
1344                         MOD_ACTION_RETURN       /* updated  */
1345                 }
1346         },
1347         /* checksimul */
1348         {
1349                 /* group */
1350                 {
1351                         MOD_ACTION_RETURN,      /* reject   */
1352                         1,                      /* fail     */
1353                         MOD_ACTION_RETURN,      /* ok       */
1354                         MOD_ACTION_RETURN,      /* handled  */
1355                         MOD_ACTION_RETURN,      /* invalid  */
1356                         MOD_ACTION_RETURN,      /* userlock */
1357                         MOD_ACTION_RETURN,      /* notfound */
1358                         MOD_ACTION_RETURN,      /* noop     */
1359                         MOD_ACTION_RETURN       /* updated  */
1360                 },
1361                 /* redundant */
1362                 {
1363                         MOD_ACTION_RETURN,      /* reject   */
1364                         1,                      /* fail     */
1365                         MOD_ACTION_RETURN,      /* ok       */
1366                         MOD_ACTION_RETURN,      /* handled  */
1367                         MOD_ACTION_RETURN,      /* invalid  */
1368                         MOD_ACTION_RETURN,      /* userlock */
1369                         MOD_ACTION_RETURN,      /* notfound */
1370                         MOD_ACTION_RETURN,      /* noop     */
1371                         MOD_ACTION_RETURN       /* updated  */
1372                 },
1373                 /* append */
1374                 {
1375                         MOD_ACTION_RETURN,      /* reject   */
1376                         1,                      /* fail     */
1377                         MOD_ACTION_RETURN,      /* ok       */
1378                         MOD_ACTION_RETURN,      /* handled  */
1379                         MOD_ACTION_RETURN,      /* invalid  */
1380                         MOD_ACTION_RETURN,      /* userlock */
1381                         MOD_ACTION_RETURN,      /* notfound */
1382                         MOD_ACTION_RETURN,      /* noop     */
1383                         MOD_ACTION_RETURN       /* updated  */
1384                 }
1385         },
1386         /* pre-proxy */
1387         {
1388                 /* group */
1389                 {
1390                         MOD_ACTION_RETURN,      /* reject   */
1391                         MOD_ACTION_RETURN,      /* fail     */
1392                         3,                      /* ok       */
1393                         MOD_ACTION_RETURN,      /* handled  */
1394                         MOD_ACTION_RETURN,      /* invalid  */
1395                         MOD_ACTION_RETURN,      /* userlock */
1396                         1,                      /* notfound */
1397                         2,                      /* noop     */
1398                         4                       /* updated  */
1399                 },
1400                 /* redundant */
1401                 {
1402                         MOD_ACTION_RETURN,      /* reject   */
1403                         1,                      /* fail     */
1404                         MOD_ACTION_RETURN,      /* ok       */
1405                         MOD_ACTION_RETURN,      /* handled  */
1406                         MOD_ACTION_RETURN,      /* invalid  */
1407                         MOD_ACTION_RETURN,      /* userlock */
1408                         MOD_ACTION_RETURN,      /* notfound */
1409                         MOD_ACTION_RETURN,      /* noop     */
1410                         MOD_ACTION_RETURN       /* updated  */
1411                 },
1412                 /* append */
1413                 {
1414                         MOD_ACTION_RETURN,      /* reject   */
1415                         1,                      /* fail     */
1416                         MOD_ACTION_RETURN,      /* ok       */
1417                         MOD_ACTION_RETURN,      /* handled  */
1418                         MOD_ACTION_RETURN,      /* invalid  */
1419                         MOD_ACTION_RETURN,      /* userlock */
1420                         2,                      /* notfound */
1421                         MOD_ACTION_RETURN,      /* noop     */
1422                         MOD_ACTION_RETURN       /* updated  */
1423                 }
1424         },
1425         /* post-proxy */
1426         {
1427                 /* group */
1428                 {
1429                         MOD_ACTION_RETURN,      /* reject   */
1430                         MOD_ACTION_RETURN,      /* fail     */
1431                         3,                      /* ok       */
1432                         MOD_ACTION_RETURN,      /* handled  */
1433                         MOD_ACTION_RETURN,      /* invalid  */
1434                         MOD_ACTION_RETURN,      /* userlock */
1435                         1,                      /* notfound */
1436                         2,                      /* noop     */
1437                         4                       /* updated  */
1438                 },
1439                 /* redundant */
1440                 {
1441                         MOD_ACTION_RETURN,      /* reject   */
1442                         1,                      /* fail     */
1443                         MOD_ACTION_RETURN,      /* ok       */
1444                         MOD_ACTION_RETURN,      /* handled  */
1445                         MOD_ACTION_RETURN,      /* invalid  */
1446                         MOD_ACTION_RETURN,      /* userlock */
1447                         MOD_ACTION_RETURN,      /* notfound */
1448                         MOD_ACTION_RETURN,      /* noop     */
1449                         MOD_ACTION_RETURN       /* updated  */
1450                 },
1451                 /* append */
1452                 {
1453                         MOD_ACTION_RETURN,      /* reject   */
1454                         1,                      /* fail     */
1455                         MOD_ACTION_RETURN,      /* ok       */
1456                         MOD_ACTION_RETURN,      /* handled  */
1457                         MOD_ACTION_RETURN,      /* invalid  */
1458                         MOD_ACTION_RETURN,      /* userlock */
1459                         2,                      /* notfound */
1460                         MOD_ACTION_RETURN,      /* noop     */
1461                         MOD_ACTION_RETURN       /* updated  */
1462                 }
1463         },
1464         /* post-auth */
1465         {
1466                 /* group */
1467                 {
1468                         MOD_ACTION_RETURN,      /* reject   */
1469                         MOD_ACTION_RETURN,      /* fail     */
1470                         3,                      /* ok       */
1471                         MOD_ACTION_RETURN,      /* handled  */
1472                         MOD_ACTION_RETURN,      /* invalid  */
1473                         MOD_ACTION_RETURN,      /* userlock */
1474                         1,                      /* notfound */
1475                         2,                      /* noop     */
1476                         4                       /* updated  */
1477                 },
1478                 /* redundant */
1479                 {
1480                         MOD_ACTION_RETURN,      /* reject   */
1481                         1,                      /* fail     */
1482                         MOD_ACTION_RETURN,      /* ok       */
1483                         MOD_ACTION_RETURN,      /* handled  */
1484                         MOD_ACTION_RETURN,      /* invalid  */
1485                         MOD_ACTION_RETURN,      /* userlock */
1486                         MOD_ACTION_RETURN,      /* notfound */
1487                         MOD_ACTION_RETURN,      /* noop     */
1488                         MOD_ACTION_RETURN       /* updated  */
1489                 },
1490                 /* append */
1491                 {
1492                         MOD_ACTION_RETURN,      /* reject   */
1493                         1,                      /* fail     */
1494                         MOD_ACTION_RETURN,      /* ok       */
1495                         MOD_ACTION_RETURN,      /* handled  */
1496                         MOD_ACTION_RETURN,      /* invalid  */
1497                         MOD_ACTION_RETURN,      /* userlock */
1498                         2,                      /* notfound */
1499                         MOD_ACTION_RETURN,      /* noop     */
1500                         MOD_ACTION_RETURN       /* updated  */
1501                 }
1502         }
1503 #ifdef WITH_COA
1504         ,
1505         /* recv-coa */
1506         {
1507                 /* group */
1508                 {
1509                         MOD_ACTION_RETURN,      /* reject   */
1510                         MOD_ACTION_RETURN,      /* fail     */
1511                         3,                      /* ok       */
1512                         MOD_ACTION_RETURN,      /* handled  */
1513                         MOD_ACTION_RETURN,      /* invalid  */
1514                         MOD_ACTION_RETURN,      /* userlock */
1515                         1,                      /* notfound */
1516                         2,                      /* noop     */
1517                         4                       /* updated  */
1518                 },
1519                 /* redundant */
1520                 {
1521                         MOD_ACTION_RETURN,      /* reject   */
1522                         1,                      /* fail     */
1523                         MOD_ACTION_RETURN,      /* ok       */
1524                         MOD_ACTION_RETURN,      /* handled  */
1525                         MOD_ACTION_RETURN,      /* invalid  */
1526                         MOD_ACTION_RETURN,      /* userlock */
1527                         MOD_ACTION_RETURN,      /* notfound */
1528                         MOD_ACTION_RETURN,      /* noop     */
1529                         MOD_ACTION_RETURN       /* updated  */
1530                 },
1531                 /* append */
1532                 {
1533                         MOD_ACTION_RETURN,      /* reject   */
1534                         1,                      /* fail     */
1535                         MOD_ACTION_RETURN,      /* ok       */
1536                         MOD_ACTION_RETURN,      /* handled  */
1537                         MOD_ACTION_RETURN,      /* invalid  */
1538                         MOD_ACTION_RETURN,      /* userlock */
1539                         2,                      /* notfound */
1540                         MOD_ACTION_RETURN,      /* noop     */
1541                         MOD_ACTION_RETURN       /* updated  */
1542                 }
1543         },
1544         /* send-coa */
1545         {
1546                 /* group */
1547                 {
1548                         MOD_ACTION_RETURN,      /* reject   */
1549                         MOD_ACTION_RETURN,      /* fail     */
1550                         3,                      /* ok       */
1551                         MOD_ACTION_RETURN,      /* handled  */
1552                         MOD_ACTION_RETURN,      /* invalid  */
1553                         MOD_ACTION_RETURN,      /* userlock */
1554                         1,                      /* notfound */
1555                         2,                      /* noop     */
1556                         4                       /* updated  */
1557                 },
1558                 /* redundant */
1559                 {
1560                         MOD_ACTION_RETURN,      /* reject   */
1561                         1,                      /* fail     */
1562                         MOD_ACTION_RETURN,      /* ok       */
1563                         MOD_ACTION_RETURN,      /* handled  */
1564                         MOD_ACTION_RETURN,      /* invalid  */
1565                         MOD_ACTION_RETURN,      /* userlock */
1566                         MOD_ACTION_RETURN,      /* notfound */
1567                         MOD_ACTION_RETURN,      /* noop     */
1568                         MOD_ACTION_RETURN       /* updated  */
1569                 },
1570                 /* append */
1571                 {
1572                         MOD_ACTION_RETURN,      /* reject   */
1573                         1,                      /* fail     */
1574                         MOD_ACTION_RETURN,      /* ok       */
1575                         MOD_ACTION_RETURN,      /* handled  */
1576                         MOD_ACTION_RETURN,      /* invalid  */
1577                         MOD_ACTION_RETURN,      /* userlock */
1578                         2,                      /* notfound */
1579                         MOD_ACTION_RETURN,      /* noop     */
1580                         MOD_ACTION_RETURN       /* updated  */
1581                 }
1582         }
1583 #endif
1584 };
1585
1586 /** Validate and fixup a map that's part of an update section.
1587  *
1588  * @param map to validate.
1589  * @param ctx data to pass to fixup function (currently unused).
1590  * @return 0 if valid else -1.
1591  */
1592 int modcall_fixup_update(value_pair_map_t *map, UNUSED void *ctx)
1593 {
1594         CONF_PAIR *cp = cf_itemtopair(map->ci);
1595
1596         /*
1597          *      Anal-retentive checks.
1598          */
1599         if (DEBUG_ENABLED2) {
1600                 if ((map->lhs->type == TMPL_TYPE_ATTR) && (map->lhs->name[0] != '&')) {
1601                         WARN("%s[%d]: Please change attribute reference to '&%s %s ...'",
1602                              cf_pair_filename(cp), cf_pair_lineno(cp),
1603                              map->lhs->name, fr_int2str(fr_tokens, map->op, "<INVALID>"));
1604                 }
1605
1606                 if ((map->rhs->type == TMPL_TYPE_ATTR) && (map->rhs->name[0] != '&')) {
1607                         WARN("%s[%d]: Please change attribute reference to '... %s &%s'",
1608                              cf_pair_filename(cp), cf_pair_lineno(cp),
1609                              fr_int2str(fr_tokens, map->op, "<INVALID>"), map->rhs->name);
1610                 }
1611         }
1612
1613         /*
1614          *      Values used by unary operators should be literal ANY
1615          *
1616          *      We then free the template and alloc a NULL one instead.
1617          */
1618         if (map->op == T_OP_CMP_FALSE) {
1619                 if ((map->rhs->type != TMPL_TYPE_LITERAL) || (strcmp(map->rhs->name, "ANY") != 0)) {
1620                         WARN("%s[%d] Wildcard deletion MUST use '!* ANY'",
1621                              cf_pair_filename(cp), cf_pair_lineno(cp));
1622                 }
1623
1624                 tmpl_free(&map->rhs);
1625
1626                 map->rhs = tmpl_alloc(map, TMPL_TYPE_NULL, NULL, 0);
1627         }
1628
1629         /*
1630          *      Lots of sanity checks for insane people...
1631          */
1632
1633         /*
1634          *      We don't support implicit type conversion,
1635          *      except for "octets"
1636          */
1637         if (((map->lhs->type == TMPL_TYPE_ATTR) || (map->lhs->type == TMPL_TYPE_DATA)) &&
1638             ((map->rhs->type == TMPL_TYPE_ATTR) || (map->rhs->type == TMPL_TYPE_DATA))) {
1639                 PW_TYPE rhs_type;
1640                 PW_TYPE lhs_type;
1641
1642                 switch (map->lhs->type) {
1643                 case TMPL_TYPE_ATTR:
1644                         lhs_type = map->lhs->tmpl_da->type;
1645                         break;
1646
1647                 case TMPL_TYPE_DATA:
1648                         lhs_type = map->lhs->tmpl_data_type;
1649                         break;
1650
1651                 default:
1652                         rad_assert(0);
1653                         return -1;
1654                 }
1655
1656                 switch (map->rhs->type) {
1657                 case TMPL_TYPE_ATTR:
1658                         rhs_type = map->rhs->tmpl_da->type;
1659                         break;
1660
1661                 case TMPL_TYPE_DATA:
1662                         rhs_type = map->rhs->tmpl_data_type;
1663                         break;
1664
1665                 default:
1666                         rad_assert(0);
1667                         return -1;
1668                 }
1669
1670
1671                 if ((lhs_type != rhs_type) &&
1672                     (lhs_type != PW_TYPE_OCTETS) &&
1673                     (rhs_type != PW_TYPE_OCTETS)) {
1674                         cf_log_err(map->ci, "Attribute type mismatch");
1675                         return -1;
1676                 }
1677         }
1678
1679         /*
1680          *      What exactly where you expecting to happen here?
1681          */
1682         if ((map->lhs->type == TMPL_TYPE_ATTR) &&
1683             (map->rhs->type == TMPL_TYPE_LIST)) {
1684                 cf_log_err(map->ci, "Can't copy list into an attribute");
1685                 return -1;
1686         }
1687
1688         /*
1689          *      Depending on the attribute type, some operators are disallowed.
1690          */
1691         if (map->lhs->type == TMPL_TYPE_ATTR) {
1692                 switch (map->op) {
1693                 default:
1694                         cf_log_err(map->ci, "Invalid operator for attribute");
1695                         return -1;
1696
1697                 case T_OP_EQ:
1698                 case T_OP_CMP_EQ:
1699                 case T_OP_ADD:
1700                 case T_OP_SUB:
1701                 case T_OP_LE:
1702                 case T_OP_GE:
1703                 case T_OP_CMP_FALSE:
1704                 case T_OP_SET:
1705                         break;
1706                 }
1707         }
1708
1709         if (map->lhs->type == TMPL_TYPE_LIST) {
1710                 /*
1711                  *      Can't copy an xlat expansion or literal into a list,
1712                  *      we don't know what type of attribute we'd need
1713                  *      to create.
1714                  *
1715                  *      The only exception is where were using a unary
1716                  *      operator like !*.
1717                  */
1718                 if (map->op != T_OP_CMP_FALSE) switch (map->rhs->type) {
1719                 case TMPL_TYPE_XLAT:
1720                 case TMPL_TYPE_LITERAL:
1721                         cf_log_err(map->ci, "Can't copy value into list (we don't know which attribute to create)");
1722                         return -1;
1723
1724                 default:
1725                         break;
1726                 }
1727
1728                 /*
1729                  *      Only += and :=, and !* operators are supported
1730                  *      for lists.
1731                  */
1732                 switch (map->op) {
1733                 case T_OP_CMP_FALSE:
1734                         break;
1735
1736                 case T_OP_ADD:
1737                         if ((map->rhs->type != TMPL_TYPE_LIST) &&
1738                             (map->rhs->type != TMPL_TYPE_EXEC)) {
1739                                 cf_log_err(map->ci, "Invalid source for list assignment '%s += ...'", map->lhs->name);
1740                                 return -1;
1741                         }
1742                         break;
1743
1744                 case T_OP_SET:
1745                         if (map->rhs->type == TMPL_TYPE_EXEC) {
1746                                 WARN("%s[%d] Please change ':=' to '=' for list assignment",
1747                                      cf_pair_filename(cp), cf_pair_lineno(cp));
1748                         }
1749
1750                         if (map->rhs->type != TMPL_TYPE_LIST) {
1751                                 cf_log_err(map->ci, "Invalid source for list assignment '%s := ...'", map->lhs->name);
1752                                 return -1;
1753                         }
1754                         break;
1755
1756                 case T_OP_EQ:
1757                         if (map->rhs->type != TMPL_TYPE_EXEC) {
1758                                 cf_log_err(map->ci, "Invalid source for list assignment '%s = ...'", map->lhs->name);
1759                                 return -1;
1760                         }
1761                         break;
1762
1763                 default:
1764                         cf_log_err(map->ci, "Operator \"%s\" not allowed for list assignment",
1765                                    fr_int2str(fr_tokens, map->op, "<INVALID>"));
1766                         return -1;
1767                 }
1768         }
1769
1770         /*
1771          *      If the map has a unary operator there's no further
1772          *      processing we need to, as RHS is unused.
1773          */
1774         if (map->op == T_OP_CMP_FALSE) return 0;
1775
1776         /*
1777          *      If LHS is an attribute, and RHS is a literal, we can
1778          *      preparse the information into a TMPL_TYPE_DATA.
1779          *
1780          *      Unless it's a unary operator in which case we
1781          *      ignore map->rhs.
1782          */
1783         if ((map->lhs->type == TMPL_TYPE_ATTR) && (map->rhs->type == TMPL_TYPE_LITERAL)) {
1784                 /*
1785                  *      It's a literal string, just copy it.
1786                  *      Don't escape anything.
1787                  */
1788                 if (!cf_new_escape &&
1789                     (map->lhs->tmpl_da->type == PW_TYPE_STRING) &&
1790                     (cf_pair_value_type(cp) == T_SINGLE_QUOTED_STRING)) {
1791                         tmpl_cast_in_place_str(map->rhs);
1792                 } else {
1793                         if (!tmpl_cast_in_place(map->rhs, map->lhs->tmpl_da->type, map->lhs->tmpl_da)) {
1794                                 cf_log_err(map->ci, "%s", fr_strerror());
1795                                 return -1;
1796                         }
1797
1798                         /*
1799                          *      Fixup LHS da if it doesn't match the type
1800                          *      of the RHS.
1801                          */
1802                         if (map->lhs->tmpl_da->type != map->rhs->tmpl_data_type) {
1803                                 DICT_ATTR const *da;
1804
1805                                 da = dict_attrbytype(map->lhs->tmpl_da->attr, map->lhs->tmpl_da->vendor,
1806                                                      map->rhs->tmpl_data_type);
1807                                 if (!da) {
1808                                         fr_strerror_printf("Cannot find %s variant of attribute \"%s\"",
1809                                                            fr_int2str(dict_attr_types, map->rhs->tmpl_data_type,
1810                                                            "<INVALID>"), map->lhs->tmpl_da->name);
1811                                         return -1;
1812                                 }
1813                                 map->lhs->tmpl_da = da;
1814                         }
1815                 }
1816         } /* else we can't precompile the data */
1817
1818         return 0;
1819 }
1820
1821
1822 #ifdef WITH_UNLANG
1823 static modcallable *do_compile_modupdate(modcallable *parent, UNUSED rlm_components_t component,
1824                                          CONF_SECTION *cs, char const *name2)
1825 {
1826         int rcode;
1827         modgroup *g;
1828         modcallable *csingle;
1829
1830         value_pair_map_t *head;
1831
1832         /*
1833          *      This looks at cs->name2 to determine which list to update
1834          */
1835         rcode = map_afrom_cs(&head, cs, PAIR_LIST_REQUEST, PAIR_LIST_REQUEST, modcall_fixup_update, NULL, 128);
1836         if (rcode < 0) return NULL; /* message already printed */
1837         if (!head) {
1838                 cf_log_err_cs(cs, "'update' sections cannot be empty");
1839                 return NULL;
1840         }
1841
1842         g = talloc_zero(parent, modgroup);
1843         csingle = mod_grouptocallable(g);
1844
1845         csingle->parent = parent;
1846         csingle->next = NULL;
1847
1848         if (name2) {
1849                 csingle->name = name2;
1850         } else {
1851                 csingle->name = "";
1852         }
1853         csingle->type = MOD_UPDATE;
1854         csingle->method = component;
1855
1856         memcpy(csingle->actions, defaultactions[component][GROUPTYPE_SIMPLE],
1857                sizeof(csingle->actions));
1858
1859         g->grouptype = GROUPTYPE_SIMPLE;
1860         g->children = NULL;
1861         g->cs = cs;
1862         g->map = talloc_steal(g, head);
1863
1864         return csingle;
1865 }
1866
1867
1868 static modcallable *do_compile_modswitch (modcallable *parent, rlm_components_t component, CONF_SECTION *cs)
1869 {
1870         CONF_ITEM *ci;
1871         FR_TOKEN type;
1872         char const *name2;
1873         bool had_seen_default = false;
1874         modcallable *csingle;
1875         modgroup *g;
1876         ssize_t slen;
1877         value_pair_tmpl_t *vpt;
1878
1879         name2 = cf_section_name2(cs);
1880         if (!name2) {
1881                 cf_log_err_cs(cs, "You must specify a variable to switch over for 'switch'");
1882                 return NULL;
1883         }
1884
1885         if (!cf_item_find_next(cs, NULL)) {
1886                 cf_log_err_cs(cs, "'switch' statements cannot be empty");
1887                 return NULL;
1888         }
1889
1890         /*
1891          *      Create the template.  If we fail, AND it's a bare word
1892          *      with &Foo-Bar, it MAY be an attribute defined by a
1893          *      module.  Allow it for now.  The pass2 checks below
1894          *      will fix it up.
1895          */
1896         type = cf_section_name2_type(cs);
1897         slen = tmpl_afrom_str(cs, &vpt, name2, strlen(name2), type, REQUEST_CURRENT, PAIR_LIST_REQUEST);
1898         if ((slen < 0) && ((type != T_BARE_WORD) || (name2[0] != '&'))) {
1899                 char *spaces, *text;
1900
1901                 fr_canonicalize_error(cs, &spaces, &text, slen, fr_strerror());
1902
1903                 cf_log_err_cs(cs, "Syntax error");
1904                 cf_log_err_cs(cs, "%s", name2);
1905                 cf_log_err_cs(cs, "%s^ %s", spaces, text);
1906
1907                 talloc_free(spaces);
1908                 talloc_free(text);
1909
1910                 return NULL;
1911         }
1912
1913         /*
1914          *      Otherwise a NULL vpt may refer to an attribute defined
1915          *      by a module.  That is checked in pass 2.
1916          */
1917
1918         /*
1919          *      Walk through the children of the switch section,
1920          *      ensuring that they're all 'case' statements
1921          */
1922         for (ci = cf_item_find_next(cs, NULL);
1923              ci != NULL;
1924              ci = cf_item_find_next(cs, ci)) {
1925                 CONF_SECTION *subcs;
1926                 char const *name1;
1927
1928                 if (!cf_item_is_section(ci)) {
1929                         if (!cf_item_is_pair(ci)) continue;
1930
1931                         cf_log_err(ci, "\"switch\" sections can only have \"case\" subsections");
1932                         talloc_free(vpt);
1933                         return NULL;
1934                 }
1935
1936                 subcs = cf_itemtosection(ci);   /* can't return NULL */
1937                 name1 = cf_section_name1(subcs);
1938
1939                 if (strcmp(name1, "case") != 0) {
1940                         cf_log_err(ci, "\"switch\" sections can only have \"case\" subsections");
1941                         talloc_free(vpt);
1942                         return NULL;
1943                 }
1944
1945                 name2 = cf_section_name2(subcs);
1946                 if (!name2) {
1947                         if (!had_seen_default) {
1948                                 had_seen_default = true;
1949                                 continue;
1950                         }
1951
1952                         cf_log_err(ci, "Cannot have two 'default' case statements");
1953                         talloc_free(vpt);
1954                         return NULL;
1955                 }
1956         }
1957
1958         csingle = do_compile_modgroup(parent, component, cs,
1959                                       GROUPTYPE_SIMPLE,
1960                                       GROUPTYPE_SIMPLE,
1961                                       MOD_SWITCH);
1962         if (!csingle) {
1963                 talloc_free(vpt);
1964                 return NULL;
1965         }
1966
1967         g = mod_callabletogroup(csingle);
1968         g->vpt = talloc_steal(g, vpt);
1969
1970         return csingle;
1971 }
1972
1973 static modcallable *do_compile_modcase(modcallable *parent, rlm_components_t component, CONF_SECTION *cs)
1974 {
1975         int i;
1976         char const *name2;
1977         modcallable *csingle;
1978         modgroup *g;
1979         value_pair_tmpl_t *vpt;
1980
1981         if (!parent || (parent->type != MOD_SWITCH)) {
1982                 cf_log_err_cs(cs, "\"case\" statements may only appear within a \"switch\" section");
1983                 return NULL;
1984         }
1985
1986         /*
1987          *      case THING means "match THING"
1988          *      case       means "match anything"
1989          */
1990         name2 = cf_section_name2(cs);
1991         if (name2) {
1992                 ssize_t slen;
1993                 FR_TOKEN type;
1994
1995                 type = cf_section_name2_type(cs);
1996
1997                 slen = tmpl_afrom_str(cs, &vpt, name2, strlen(name2), type, REQUEST_CURRENT, PAIR_LIST_REQUEST);
1998                 if ((slen < 0) && ((type != T_BARE_WORD) || (name2[0] != '&'))) {
1999                         char *spaces, *text;
2000
2001                         fr_canonicalize_error(cs, &spaces, &text, slen, fr_strerror());
2002
2003                         cf_log_err_cs(cs, "Syntax error");
2004                         cf_log_err_cs(cs, "%s", name2);
2005                         cf_log_err_cs(cs, "%s^ %s", spaces, text);
2006
2007                         talloc_free(spaces);
2008                         talloc_free(text);
2009
2010                         return NULL;
2011                 }
2012
2013                 /*
2014                  *      Otherwise a NULL vpt may refer to an attribute defined
2015                  *      by a module.  That is checked in pass 2.
2016                  */
2017
2018         } else {
2019                 vpt = NULL;
2020         }
2021
2022         csingle = do_compile_modgroup(parent, component, cs,
2023                                       GROUPTYPE_SIMPLE,
2024                                       GROUPTYPE_SIMPLE,
2025                                       MOD_CASE);
2026         if (!csingle) {
2027                 talloc_free(vpt);
2028                 return NULL;
2029         }
2030
2031         /*
2032          *      The interpretor expects this to be NULL for the
2033          *      default case.  do_compile_modgroup sets it to name2,
2034          *      unless name2 is NULL, in which case it sets it to name1.
2035          */
2036         csingle->name = name2;
2037
2038         g = mod_callabletogroup(csingle);
2039         g->vpt = talloc_steal(g, vpt);
2040
2041         /*
2042          *      Set all of it's codes to return, so that
2043          *      when we pick a 'case' statement, we don't
2044          *      fall through to processing the next one.
2045          */
2046         for (i = 0; i < RLM_MODULE_NUMCODES; i++) {
2047                 csingle->actions[i] = MOD_ACTION_RETURN;
2048         }
2049
2050         return csingle;
2051 }
2052
2053 static modcallable *do_compile_modforeach(modcallable *parent,
2054                                           UNUSED rlm_components_t component, CONF_SECTION *cs)
2055 {
2056         FR_TOKEN type;
2057         char const *name2;
2058         modcallable *csingle;
2059         modgroup *g;
2060         ssize_t slen;
2061         value_pair_tmpl_t *vpt;
2062
2063         name2 = cf_section_name2(cs);
2064         if (!name2) {
2065                 cf_log_err_cs(cs,
2066                            "You must specify an attribute to loop over in 'foreach'");
2067                 return NULL;
2068         }
2069
2070         if (!cf_item_find_next(cs, NULL)) {
2071                 cf_log_err_cs(cs, "'foreach' blocks cannot be empty");
2072                 return NULL;
2073         }
2074
2075         /*
2076          *      Create the template.  If we fail, AND it's a bare word
2077          *      with &Foo-Bar, it MAY be an attribute defined by a
2078          *      module.  Allow it for now.  The pass2 checks below
2079          *      will fix it up.
2080          */
2081         type = cf_section_name2_type(cs);
2082         slen = tmpl_afrom_str(cs, &vpt, name2, strlen(name2), type, REQUEST_CURRENT, PAIR_LIST_REQUEST);
2083         if ((slen < 0) && ((type != T_BARE_WORD) || (name2[0] != '&'))) {
2084                 char *spaces, *text;
2085
2086                 fr_canonicalize_error(cs, &spaces, &text, slen, fr_strerror());
2087
2088                 cf_log_err_cs(cs, "Syntax error");
2089                 cf_log_err_cs(cs, "%s", name2);
2090                 cf_log_err_cs(cs, "%s^ %s", spaces, text);
2091
2092                 talloc_free(spaces);
2093                 talloc_free(text);
2094
2095                 return NULL;
2096         }
2097
2098         if (vpt && (vpt->type != TMPL_TYPE_ATTR)) {
2099                 cf_log_err_cs(cs, "MUST use attribute reference in 'foreach'");
2100                 return NULL;
2101         }
2102
2103         /*
2104          *      Fix up the template to iterate over all instances of
2105          *      the attribute. In a perfect consistent world, users would do
2106          *      foreach &attr[*], but that's taking the consistency thing a bit far.
2107          */
2108         if (vpt && (vpt->type == TMPL_TYPE_ATTR)) {
2109                 vpt->tmpl_num = NUM_ALL;
2110         }
2111
2112         csingle = do_compile_modgroup(parent, component, cs,
2113                                       GROUPTYPE_SIMPLE, GROUPTYPE_SIMPLE,
2114                                       MOD_FOREACH);
2115
2116         if (!csingle) {
2117                 talloc_free(vpt);
2118                 return NULL;
2119         }
2120
2121         g = mod_callabletogroup(csingle);
2122         g->vpt = vpt;
2123
2124         return csingle;
2125 }
2126
2127 static modcallable *do_compile_modbreak(modcallable *parent,
2128                                         rlm_components_t component, CONF_ITEM const *ci)
2129 {
2130         CONF_SECTION const *cs = NULL;
2131
2132         for (cs = cf_item_parent(ci);
2133              cs != NULL;
2134              cs = cf_item_parent(cf_sectiontoitem(cs))) {
2135                 if (strcmp(cf_section_name1(cs), "foreach") == 0) {
2136                         break;
2137                 }
2138         }
2139
2140         if (!cs) {
2141                 cf_log_err(ci, "'break' can only be used in a 'foreach' section");
2142                 return NULL;
2143         }
2144
2145         return do_compile_modgroup(parent, component, NULL,
2146                                    GROUPTYPE_SIMPLE, GROUPTYPE_SIMPLE,
2147                                    MOD_BREAK);
2148 }
2149 #endif
2150
2151 static modcallable *do_compile_modserver(modcallable *parent,
2152                                          rlm_components_t component, CONF_ITEM *ci,
2153                                          char const *name,
2154                                          CONF_SECTION *cs,
2155                                          char const *server)
2156 {
2157         modcallable *csingle;
2158         CONF_SECTION *subcs;
2159         modref *mr;
2160
2161         subcs = cf_section_sub_find_name2(cs, comp2str[component], NULL);
2162         if (!subcs) {
2163                 cf_log_err(ci, "Server %s has no %s section",
2164                            server, comp2str[component]);
2165                 return NULL;
2166         }
2167
2168         mr = talloc_zero(parent, modref);
2169
2170         csingle = mod_reftocallable(mr);
2171         csingle->parent = parent;
2172         csingle->next = NULL;
2173         csingle->name = name;
2174         csingle->type = MOD_REFERENCE;
2175         csingle->method = component;
2176
2177         memcpy(csingle->actions, defaultactions[component][GROUPTYPE_SIMPLE],
2178                sizeof(csingle->actions));
2179
2180         mr->ref_name = strdup(server);
2181         mr->ref_cs = cs;
2182
2183         return csingle;
2184 }
2185
2186 static modcallable *do_compile_modxlat(modcallable *parent,
2187                                        rlm_components_t component, char const *fmt)
2188 {
2189         modcallable *csingle;
2190         modxlat *mx;
2191
2192         mx = talloc_zero(parent, modxlat);
2193
2194         csingle = mod_xlattocallable(mx);
2195         csingle->parent = parent;
2196         csingle->next = NULL;
2197         csingle->name = "expand";
2198         csingle->type = MOD_XLAT;
2199         csingle->method = component;
2200
2201         memcpy(csingle->actions, defaultactions[component][GROUPTYPE_SIMPLE],
2202                sizeof(csingle->actions));
2203
2204         mx->xlat_name = strdup(fmt);
2205         if (fmt[0] != '%') {
2206                 char *p;
2207                 mx->exec = true;
2208
2209                 strcpy(mx->xlat_name, fmt + 1);
2210                 p = strrchr(mx->xlat_name, '`');
2211                 if (p) *p = '\0';
2212         }
2213
2214         return csingle;
2215 }
2216
2217 /*
2218  *      redundant, etc. can refer to modules or groups, but not much else.
2219  */
2220 static int all_children_are_modules(CONF_SECTION *cs, char const *name)
2221 {
2222         CONF_ITEM *ci;
2223
2224         for (ci=cf_item_find_next(cs, NULL);
2225              ci != NULL;
2226              ci=cf_item_find_next(cs, ci)) {
2227                 /*
2228                  *      If we're a redundant, etc. group, then the
2229                  *      intention is to call modules, rather than
2230                  *      processing logic.  These checks aren't
2231                  *      *strictly* necessary, but they keep the users
2232                  *      from doing crazy things.
2233                  */
2234                 if (cf_item_is_section(ci)) {
2235                         CONF_SECTION *subcs = cf_itemtosection(ci);
2236                         char const *name1 = cf_section_name1(subcs);
2237
2238                         if ((strcmp(name1, "if") == 0) ||
2239                             (strcmp(name1, "else") == 0) ||
2240                             (strcmp(name1, "elsif") == 0) ||
2241                             (strcmp(name1, "update") == 0) ||
2242                             (strcmp(name1, "switch") == 0) ||
2243                             (strcmp(name1, "case") == 0)) {
2244                                 cf_log_err(ci, "%s sections cannot contain a \"%s\" statement",
2245                                        name, name1);
2246                                 return 0;
2247                         }
2248                         continue;
2249                 }
2250
2251                 if (cf_item_is_pair(ci)) {
2252                         CONF_PAIR *cp = cf_itemtopair(ci);
2253                         if (cf_pair_value(cp) != NULL) {
2254                                 cf_log_err(ci,
2255                                            "Entry with no value is invalid");
2256                                 return 0;
2257                         }
2258                 }
2259         }
2260
2261         return 1;
2262 }
2263
2264
2265 /*
2266  *      Compile one entry of a module call.
2267  */
2268 static modcallable *do_compile_modsingle(modcallable *parent,
2269                                          rlm_components_t component, CONF_ITEM *ci,
2270                                          int grouptype,
2271                                          char const **modname)
2272 {
2273         char const *modrefname;
2274         modsingle *single;
2275         modcallable *csingle;
2276         module_instance_t *this;
2277         CONF_SECTION *cs, *subcs, *modules;
2278         char const *realname;
2279
2280         if (cf_item_is_section(ci)) {
2281                 char const *name2;
2282
2283                 cs = cf_itemtosection(ci);
2284                 modrefname = cf_section_name1(cs);
2285                 name2 = cf_section_name2(cs);
2286                 if (!name2) name2 = "";
2287
2288                 /*
2289                  *      group{}, redundant{}, or append{} may appear
2290                  *      where a single module instance was expected.
2291                  *      In that case, we hand it off to
2292                  *      compile_modgroup
2293                  */
2294                 if (strcmp(modrefname, "group") == 0) {
2295                         *modname = name2;
2296                         return do_compile_modgroup(parent, component, cs,
2297                                                    GROUPTYPE_SIMPLE,
2298                                                    grouptype, MOD_GROUP);
2299
2300                 } else if (strcmp(modrefname, "redundant") == 0) {
2301                         *modname = name2;
2302
2303                         if (!all_children_are_modules(cs, modrefname)) {
2304                                 return NULL;
2305                         }
2306
2307                         return do_compile_modgroup(parent, component, cs,
2308                                                    GROUPTYPE_REDUNDANT,
2309                                                    grouptype, MOD_GROUP);
2310
2311                 } else if (strcmp(modrefname, "append") == 0) {
2312                         *modname = name2;
2313                         return do_compile_modgroup(parent, component, cs,
2314                                                    GROUPTYPE_APPEND,
2315                                                    grouptype, MOD_GROUP);
2316
2317                 } else if (strcmp(modrefname, "load-balance") == 0) {
2318                         *modname = name2;
2319
2320                         if (!all_children_are_modules(cs, modrefname)) {
2321                                 return NULL;
2322                         }
2323
2324                         return do_compile_modgroup(parent, component, cs,
2325                                                    GROUPTYPE_SIMPLE,
2326                                                    grouptype, MOD_LOAD_BALANCE);
2327
2328                 } else if (strcmp(modrefname, "redundant-load-balance") == 0) {
2329                         *modname = name2;
2330
2331                         if (!all_children_are_modules(cs, modrefname)) {
2332                                 return NULL;
2333                         }
2334
2335                         return do_compile_modgroup(parent, component, cs,
2336                                                    GROUPTYPE_REDUNDANT,
2337                                                    grouptype, MOD_REDUNDANT_LOAD_BALANCE);
2338
2339 #ifdef WITH_UNLANG
2340                 } else  if (strcmp(modrefname, "if") == 0) {
2341                         if (!cf_section_name2(cs)) {
2342                                 cf_log_err(ci, "'if' without condition");
2343                                 return NULL;
2344                         }
2345
2346                         *modname = name2;
2347                         csingle= do_compile_modgroup(parent, component, cs,
2348                                                      GROUPTYPE_SIMPLE,
2349                                                      grouptype, MOD_IF);
2350                         if (!csingle) return NULL;
2351                         *modname = name2;
2352
2353                         return csingle;
2354
2355                 } else  if (strcmp(modrefname, "elsif") == 0) {
2356                         if (parent &&
2357                             ((parent->type == MOD_LOAD_BALANCE) ||
2358                              (parent->type == MOD_REDUNDANT_LOAD_BALANCE))) {
2359                                 cf_log_err(ci, "'elsif' cannot be used in this section");
2360                                 return NULL;
2361                         }
2362
2363                         if (!cf_section_name2(cs)) {
2364                                 cf_log_err(ci, "'elsif' without condition");
2365                                 return NULL;
2366                         }
2367
2368                         *modname = name2;
2369                         return do_compile_modgroup(parent, component, cs,
2370                                                    GROUPTYPE_SIMPLE,
2371                                                    grouptype, MOD_ELSIF);
2372
2373                 } else  if (strcmp(modrefname, "else") == 0) {
2374                         if (parent &&
2375                             ((parent->type == MOD_LOAD_BALANCE) ||
2376                              (parent->type == MOD_REDUNDANT_LOAD_BALANCE))) {
2377                                 cf_log_err(ci, "'else' cannot be used in this section section");
2378                                 return NULL;
2379                         }
2380
2381                         if (cf_section_name2(cs)) {
2382                                 cf_log_err(ci, "Cannot have conditions on 'else'");
2383                                 return NULL;
2384                         }
2385
2386                         *modname = name2;
2387                         return  do_compile_modgroup(parent, component, cs,
2388                                                     GROUPTYPE_SIMPLE,
2389                                                     grouptype, MOD_ELSE);
2390
2391                 } else  if (strcmp(modrefname, "update") == 0) {
2392                         *modname = name2;
2393
2394                         return do_compile_modupdate(parent, component, cs,
2395                                                     name2);
2396
2397                 } else  if (strcmp(modrefname, "switch") == 0) {
2398                         *modname = name2;
2399
2400                         return do_compile_modswitch (parent, component, cs);
2401
2402                 } else  if (strcmp(modrefname, "case") == 0) {
2403                         *modname = name2;
2404
2405                         return do_compile_modcase(parent, component, cs);
2406
2407                 } else  if (strcmp(modrefname, "foreach") == 0) {
2408                         *modname = name2;
2409
2410                         return do_compile_modforeach(parent, component, cs);
2411
2412 #endif
2413                 } /* else it's something like sql { fail = 1 ...} */
2414
2415         } else if (!cf_item_is_pair(ci)) { /* CONF_DATA or some such */
2416                 return NULL;
2417
2418                 /*
2419                  *      Else it's a module reference, with updated return
2420                  *      codes.
2421                  */
2422         } else {
2423                 CONF_SECTION *loop;
2424                 CONF_PAIR *cp = cf_itemtopair(ci);
2425                 modrefname = cf_pair_attr(cp);
2426
2427                 /*
2428                  *      Actions (ok = 1), etc. are orthogonal to just
2429                  *      about everything else.
2430                  */
2431                 if (cf_pair_value(cp) != NULL) {
2432                         cf_log_err(ci, "Entry is not a reference to a module");
2433                         return NULL;
2434                 }
2435
2436                 if (((modrefname[0] == '%') && (modrefname[1] == '{')) ||
2437                     (modrefname[0] == '`')) {
2438                         return do_compile_modxlat(parent, component,
2439                                                   modrefname);
2440                 }
2441
2442                 /*
2443                  *      See if the module is a virtual one.  If so,
2444                  *      return that, rather than doing anything here.
2445                  */
2446                 subcs = NULL;
2447                 cs = cf_section_find("instantiate");
2448                 if (cs) subcs = cf_section_sub_find_name2(cs, NULL,
2449                                                           modrefname);
2450                 if (!subcs &&
2451                     (cs = cf_section_find("policy")) != NULL) {
2452                         char buffer[256];
2453
2454                         snprintf(buffer, sizeof(buffer), "%s.%s",
2455                                  modrefname, comp2str[component]);
2456
2457                         /*
2458                          *      Prefer name.section, then name.
2459                          */
2460                         subcs = cf_section_sub_find_name2(cs, NULL,
2461                                                           buffer);
2462                         if (!subcs) {
2463                                 subcs = cf_section_sub_find_name2(cs, NULL,
2464                                                                   modrefname);
2465                         }
2466                 }
2467
2468                 /*
2469                  *      Allow policies to over-ride module names.
2470                  *      i.e. the "sql" policy can do some extra things,
2471                  *      and then call the "sql" module.
2472                  */
2473                 for (loop = cf_item_parent(ci);
2474                      loop && subcs;
2475                      loop = cf_item_parent(cf_sectiontoitem(loop))) {
2476                         if (loop == subcs) {
2477                                 subcs = NULL;
2478                         }
2479                 }
2480
2481                 if (subcs) {
2482                         /*
2483                          *      redundant foo {} is a single.
2484                          */
2485                         if (cf_section_name2(subcs)) {
2486                                 return do_compile_modsingle(parent,
2487                                                             component,
2488                                                             cf_sectiontoitem(subcs),
2489                                                             grouptype,
2490                                                             modname);
2491                         } else {
2492                                 /*
2493                                  *      foo {} is a group.
2494                                  */
2495                                 return do_compile_modgroup(parent,
2496                                                            component,
2497                                                            subcs,
2498                                                            GROUPTYPE_SIMPLE,
2499                                                            grouptype, MOD_GROUP);
2500                         }
2501                 }
2502         }
2503
2504 #ifdef WITH_UNLANG
2505         if (strcmp(modrefname, "break") == 0) {
2506                 return do_compile_modbreak(parent, component, ci);
2507         }
2508
2509         if (strcmp(modrefname, "return") == 0) {
2510                 return do_compile_modgroup(parent, component, NULL,
2511                                            GROUPTYPE_SIMPLE, GROUPTYPE_SIMPLE,
2512                                            MOD_RETURN);
2513         }
2514 #endif
2515
2516         /*
2517          *      Not a virtual module.  It must be a real module.
2518          */
2519         modules = cf_section_find("modules");
2520         this = NULL;
2521         realname = modrefname;
2522
2523         if (modules) {
2524                 /*
2525                  *      Try to load the optional module.
2526                  */
2527                 if (realname[0] == '-') realname++;
2528
2529                 /*
2530                  *      As of v3, only known modules are in the
2531                  *      "modules" section.
2532                  */
2533                 if (cf_section_sub_find_name2(modules, NULL, realname)) {
2534                         this = find_module_instance(modules, realname, true);
2535                         if (!this && (realname != modrefname)) {
2536                                 return NULL;
2537                         }
2538
2539                 } else {
2540                         /*
2541                          *      We were asked to MAYBE load it and it
2542                          *      doesn't exist.  Return a soft error.
2543                          */
2544                         if (realname != modrefname) {
2545                                 *modname = modrefname;
2546                                 return NULL;
2547                         }
2548                 }
2549         }
2550
2551         if (!this) do {
2552                 int i;
2553                 char *p;
2554
2555                 /*
2556                  *      Maybe it's module.method
2557                  */
2558                 p = strrchr(modrefname, '.');
2559                 if (p) for (i = RLM_COMPONENT_AUTH;
2560                             i < RLM_COMPONENT_COUNT;
2561                             i++) {
2562                         if (strcmp(p + 1, comp2str[i]) == 0) {
2563                                 char buffer[256];
2564
2565                                 strlcpy(buffer, modrefname, sizeof(buffer));
2566                                 buffer[p - modrefname] = '\0';
2567                                 component = i;
2568
2569                                 this = find_module_instance(modules, buffer, true);
2570                                 if (this && !this->entry->module->methods[i]) {
2571                                         *modname = NULL;
2572                                         cf_log_err(ci, "Module %s has no such method %s", buffer, comp2str[i]);
2573                                         return NULL;
2574                                 }
2575                                 break;
2576                         }
2577                 }
2578                 if (this) break;
2579
2580                 /*
2581                  *      Call a server.  This should really be deleted...
2582                  */
2583                 if (strncmp(modrefname, "server[", 7) == 0) {
2584                         char buffer[256];
2585
2586                         strlcpy(buffer, modrefname + 7, sizeof(buffer));
2587                         p = strrchr(buffer, ']');
2588                         if (!p || p[1] != '\0' || (p == buffer)) {
2589                                 cf_log_err(ci, "Invalid server reference in \"%s\".", modrefname);
2590                                 return NULL;
2591                         }
2592                         *p = '\0';
2593
2594                         cs = cf_section_sub_find_name2(NULL, "server", buffer);
2595                         if (!cs) {
2596                                 cf_log_err(ci, "No such server \"%s\".", buffer);
2597                                 return NULL;
2598                         }
2599
2600                         return do_compile_modserver(parent, component, ci,
2601                                                     modrefname, cs, buffer);
2602                 }
2603
2604                 *modname = NULL;
2605                 cf_log_err(ci, "Failed to find \"%s\" in the \"modules\" section.", modrefname);
2606                 cf_log_err(ci, "Please verify that the configuration exists in the file %s/mods-enabled/%s.", get_radius_dir(), modrefname);
2607                 return NULL;
2608         } while (0);
2609
2610         /*
2611          *      We know it's all OK, allocate the structures, and fill
2612          *      them in.
2613          */
2614         single = talloc_zero(parent, modsingle);
2615         csingle = mod_singletocallable(single);
2616         csingle->parent = parent;
2617         csingle->next = NULL;
2618         if (!parent || (component != RLM_COMPONENT_AUTH)) {
2619                 memcpy(csingle->actions, defaultactions[component][grouptype],
2620                        sizeof csingle->actions);
2621         } else { /* inside Auth-Type has different rules */
2622                 memcpy(csingle->actions, defaultactions[RLM_COMPONENT_AUTZ][grouptype],
2623                        sizeof csingle->actions);
2624         }
2625         rad_assert(modrefname != NULL);
2626         csingle->name = realname;
2627         csingle->type = MOD_SINGLE;
2628         csingle->method = component;
2629
2630         /*
2631          *      Singles can override the actions, virtual modules cannot.
2632          *
2633          *      FIXME: We may want to re-visit how to do this...
2634          *      maybe a csingle as a ref?
2635          */
2636         if (cf_item_is_section(ci)) {
2637                 CONF_ITEM *csi;
2638
2639                 cs = cf_itemtosection(ci);
2640                 for (csi=cf_item_find_next(cs, NULL);
2641                      csi != NULL;
2642                      csi=cf_item_find_next(cs, csi)) {
2643
2644                         if (cf_item_is_section(csi)) {
2645                                 cf_log_err(csi, "Subsection of module instance call not allowed");
2646                                 talloc_free(csingle);
2647                                 return NULL;
2648                         }
2649
2650                         if (!cf_item_is_pair(csi)) continue;
2651
2652                         if (!compile_action(csingle, cf_itemtopair(csi))) {
2653                                 talloc_free(csingle);
2654                                 return NULL;
2655                         }
2656                 }
2657         }
2658
2659         /*
2660          *      Bail out if the module in question does not supply the
2661          *      wanted component
2662          */
2663         if (!this->entry->module->methods[component]) {
2664                 cf_log_err(ci, "\"%s\" modules aren't allowed in '%s' sections -- they have no such method.", this->entry->module->name,
2665                        comp2str[component]);
2666                 talloc_free(csingle);
2667                 return NULL;
2668         }
2669
2670         single->modinst = this;
2671         *modname = this->entry->module->name;
2672         return csingle;
2673 }
2674
2675 modcallable *compile_modsingle(TALLOC_CTX *ctx,
2676                                modcallable **parent,
2677                                rlm_components_t component, CONF_ITEM *ci,
2678                                char const **modname)
2679 {
2680         modcallable *ret;
2681
2682         if (!*parent) {
2683                 modcallable *c;
2684                 modgroup *g;
2685                 CONF_SECTION *parentcs;
2686
2687                 g = talloc_zero(ctx, modgroup);
2688                 memset(g, 0, sizeof(*g));
2689                 g->grouptype = GROUPTYPE_SIMPLE;
2690                 c = mod_grouptocallable(g);
2691                 c->next = NULL;
2692                 memcpy(c->actions,
2693                        defaultactions[component][GROUPTYPE_SIMPLE],
2694                        sizeof(c->actions));
2695
2696                 parentcs = cf_item_parent(ci);
2697                 c->name = cf_section_name2(parentcs);
2698                 if (!c->name) {
2699                         c->name = cf_section_name1(parentcs);
2700                 }
2701
2702                 c->type = MOD_GROUP;
2703                 c->method = component;
2704                 g->children = NULL;
2705
2706                 *parent = mod_grouptocallable(g);
2707         }
2708
2709         ret = do_compile_modsingle(*parent, component, ci,
2710                                    GROUPTYPE_SIMPLE,
2711                                    modname);
2712         dump_tree(component, ret);
2713         return ret;
2714 }
2715
2716
2717 /*
2718  *      Internal compile group code.
2719  */
2720 static modcallable *do_compile_modgroup(modcallable *parent,
2721                                         rlm_components_t component, CONF_SECTION *cs,
2722                                         int grouptype, int parentgrouptype, int mod_type)
2723 {
2724         int i;
2725         modgroup *g;
2726         modcallable *c;
2727         CONF_ITEM *ci;
2728
2729         g = talloc_zero(parent, modgroup);
2730         g->grouptype = grouptype;
2731         g->children = NULL;
2732         g->cs = cs;
2733
2734         c = mod_grouptocallable(g);
2735         c->parent = parent;
2736         c->type = mod_type;
2737         c->next = NULL;
2738         memset(c->actions, 0, sizeof(c->actions));
2739
2740         if (!cs) {              /* only for "break" and "return" */
2741                 c->name = "";
2742                 goto set_codes;
2743         }
2744
2745         /*
2746          *      Remember the name for printing, etc.
2747          *
2748          *      FIXME: We may also want to put the names into a
2749          *      rbtree, so that groups can reference each other...
2750          */
2751         c->name = cf_section_name2(cs);
2752         if (!c->name) {
2753                 c->name = cf_section_name1(cs);
2754                 if ((strcmp(c->name, "group") == 0) ||
2755                     (strcmp(c->name, "redundant") == 0)) {
2756                         c->name = "";
2757                 } else if (c->type == MOD_GROUP) {
2758                         c->type = MOD_POLICY;
2759                 }
2760         }
2761
2762 #ifdef WITH_UNLANG
2763         /*
2764          *      Do load-time optimizations
2765          */
2766         if ((c->type == MOD_IF) || (c->type == MOD_ELSIF) || (c->type == MOD_ELSE)) {
2767                 modgroup *f, *p;
2768
2769                 rad_assert(parent != NULL);
2770
2771                 if (c->type == MOD_IF) {
2772                         g->cond = cf_data_find(g->cs, "if");
2773                         rad_assert(g->cond != NULL);
2774
2775                 check_if:
2776                         if (g->cond->type == COND_TYPE_FALSE) {
2777                                 INFO(" # Skipping contents of '%s' as it is always 'false' -- %s:%d",
2778                                      group_name[g->mc.type],
2779                                      cf_section_filename(g->cs), cf_section_lineno(g->cs));
2780                                 goto set_codes;
2781                         }
2782
2783                 } else if (c->type == MOD_ELSIF) {
2784
2785                         g->cond = cf_data_find(g->cs, "if");
2786                         rad_assert(g->cond != NULL);
2787
2788                         rad_assert(parent != NULL);
2789                         p = mod_callabletogroup(parent);
2790
2791                         rad_assert(p->tail != NULL);
2792
2793                         f = mod_callabletogroup(p->tail);
2794                         rad_assert((f->mc.type == MOD_IF) ||
2795                                    (f->mc.type == MOD_ELSIF));
2796
2797                         /*
2798                          *      If we took the previous condition, we
2799                          *      don't need to take this one.
2800                          *
2801                          *      We reset our condition to 'true', so
2802                          *      that subsequent sections can check
2803                          *      that they don't need to be executed.
2804                          */
2805                         if (f->cond->type == COND_TYPE_TRUE) {
2806                         skip_true:
2807                                 INFO(" # Skipping contents of '%s' as previous '%s' is always  'true' -- %s:%d",
2808                                      group_name[g->mc.type],
2809                                      group_name[f->mc.type],
2810                                      cf_section_filename(g->cs), cf_section_lineno(g->cs));
2811                                 g->cond = f->cond;
2812                                 goto set_codes;
2813                         }
2814                         goto check_if;
2815
2816                 } else {
2817                         rad_assert(c->type == MOD_ELSE);
2818
2819                         rad_assert(parent != NULL);
2820                         p = mod_callabletogroup(parent);
2821
2822                         rad_assert(p->tail != NULL);
2823
2824                         f = mod_callabletogroup(p->tail);
2825                         rad_assert((f->mc.type == MOD_IF) ||
2826                                    (f->mc.type == MOD_ELSIF));
2827
2828                         /*
2829                          *      If we took the previous condition, we
2830                          *      don't need to take this one.
2831                          */
2832                         if (f->cond->type == COND_TYPE_TRUE) goto skip_true;
2833                 }
2834
2835                 /*
2836                  *      Else we need to compile this section
2837                  */
2838         }
2839 #endif
2840
2841         /*
2842          *      Loop over the children of this group.
2843          */
2844         for (ci=cf_item_find_next(cs, NULL);
2845              ci != NULL;
2846              ci=cf_item_find_next(cs, ci)) {
2847
2848                 /*
2849                  *      Sections are references to other groups, or
2850                  *      to modules with updated return codes.
2851                  */
2852                 if (cf_item_is_section(ci)) {
2853                         char const *junk = NULL;
2854                         modcallable *single;
2855                         CONF_SECTION *subcs = cf_itemtosection(ci);
2856
2857                         single = do_compile_modsingle(c, component, ci,
2858                                                       grouptype, &junk);
2859                         if (!single) {
2860                                 cf_log_err(ci, "Failed to parse \"%s\" subsection.",
2861                                        cf_section_name1(subcs));
2862                                 talloc_free(c);
2863                                 return NULL;
2864                         }
2865                         add_child(g, single);
2866
2867                 } else if (!cf_item_is_pair(ci)) { /* CONF_DATA */
2868                         continue;
2869
2870                 } else {
2871                         char const *attr, *value;
2872                         CONF_PAIR *cp = cf_itemtopair(ci);
2873
2874                         attr = cf_pair_attr(cp);
2875                         value = cf_pair_value(cp);
2876
2877                         /*
2878                          *      A CONF_PAIR is either a module
2879                          *      instance with no actions
2880                          *      specified ...
2881                          */
2882                         if (!value) {
2883                                 modcallable *single;
2884                                 char const *junk = NULL;
2885
2886                                 single = do_compile_modsingle(c,
2887                                                               component,
2888                                                               ci,
2889                                                               grouptype,
2890                                                               &junk);
2891                                 if (!single) {
2892                                         if (cf_item_is_pair(ci) &&
2893                                             cf_pair_attr(cf_itemtopair(ci))[0] == '-') {
2894                                                 continue;
2895                                         }
2896
2897                                         cf_log_err(ci,
2898                                                    "Failed to parse \"%s\" entry.",
2899                                                    attr);
2900                                         talloc_free(c);
2901                                         return NULL;
2902                                 }
2903                                 add_child(g, single);
2904
2905                                 /*
2906                                  *      Or a module instance with action.
2907                                  */
2908                         } else if (!compile_action(c, cp)) {
2909                                 talloc_free(c);
2910                                 return NULL;
2911                         } /* else it worked */
2912                 }
2913         }
2914
2915 set_codes:
2916         /*
2917          *      Set the default actions, if they haven't already been
2918          *      set.
2919          */
2920         for (i = 0; i < RLM_MODULE_NUMCODES; i++) {
2921                 if (!c->actions[i]) {
2922                         if (!parent || (component != RLM_COMPONENT_AUTH)) {
2923                                 c->actions[i] = defaultactions[component][parentgrouptype][i];
2924                         } else { /* inside Auth-Type has different rules */
2925                                 c->actions[i] = defaultactions[RLM_COMPONENT_AUTZ][parentgrouptype][i];
2926                         }
2927                 }
2928         }
2929
2930         switch (c->type) {
2931         default:
2932                 break;
2933
2934         case MOD_GROUP:
2935                 if (grouptype != GROUPTYPE_REDUNDANT) break;
2936                 /* FALL-THROUGH */
2937
2938         case MOD_LOAD_BALANCE:
2939         case MOD_REDUNDANT_LOAD_BALANCE:
2940                 if (!g->children) {
2941                         cf_log_err_cs(g->cs, "%s sections cannot be empty",
2942                                       cf_section_name1(g->cs));
2943                         talloc_free(c);
2944                         return NULL;
2945                 }
2946         }
2947
2948         /*
2949          *      FIXME: If there are no children, return NULL?
2950          */
2951         return mod_grouptocallable(g);
2952 }
2953
2954 modcallable *compile_modgroup(modcallable *parent,
2955                               rlm_components_t component, CONF_SECTION *cs)
2956 {
2957         modcallable *ret = do_compile_modgroup(parent, component, cs,
2958                                                GROUPTYPE_SIMPLE,
2959                                                GROUPTYPE_SIMPLE, MOD_GROUP);
2960
2961         if (debug_flag > 3) {
2962                 modcall_debug(ret, 2);
2963         }
2964
2965         return ret;
2966 }
2967
2968 void add_to_modcallable(modcallable *parent, modcallable *this)
2969 {
2970         modgroup *g;
2971
2972         rad_assert(this != NULL);
2973         rad_assert(parent != NULL);
2974
2975         g = mod_callabletogroup(parent);
2976
2977         add_child(g, this);
2978 }
2979
2980
2981 #ifdef WITH_UNLANG
2982 static bool pass2_xlat_compile(CONF_ITEM const *ci, value_pair_tmpl_t **pvpt, bool convert,
2983                                DICT_ATTR const *da)
2984 {
2985         ssize_t slen;
2986         char *fmt;
2987         char const *error;
2988         xlat_exp_t *head;
2989         value_pair_tmpl_t *vpt;
2990
2991         vpt = *pvpt;
2992
2993         rad_assert(vpt->type == TMPL_TYPE_XLAT);
2994
2995         fmt = talloc_typed_strdup(vpt, vpt->name);
2996         slen = xlat_tokenize(vpt, fmt, &head, &error);
2997
2998         if (slen < 0) {
2999                 char *spaces, *text;
3000
3001                 fr_canonicalize_error(vpt, &spaces, &text, slen, vpt->name);
3002
3003                 cf_log_err(ci, "Failed parsing expanded string:");
3004                 cf_log_err(ci, "%s", text);
3005                 cf_log_err(ci, "%s^ %s", spaces, error);
3006
3007                 talloc_free(spaces);
3008                 talloc_free(text);
3009                 return false;
3010         }
3011
3012         /*
3013          *      Convert %{Attribute-Name} to &Attribute-Name
3014          */
3015         if (convert) {
3016                 value_pair_tmpl_t *attr;
3017
3018                 attr = xlat_to_tmpl_attr(talloc_parent(vpt), head);
3019                 if (attr) {
3020                         /*
3021                          *      If it's a virtual attribute, leave it
3022                          *      alone.
3023                          */
3024                         if (attr->tmpl_da->flags.virtual) {
3025                                 talloc_free(attr);
3026                                 return true;
3027                         }
3028
3029                         /*
3030                          *      If the attribute is of incompatible
3031                          *      type, leave it alone.
3032                          */
3033                         if (da && (da->type != attr->tmpl_da->type)) {
3034                                 talloc_free(attr);
3035                                 return true;
3036                         }
3037
3038                         if (cf_item_is_pair(ci)) {
3039                                 CONF_PAIR *cp = cf_itemtopair(ci);
3040
3041                                 WARN("%s[%d] Please change %%{%s} to &%s",
3042                                        cf_pair_filename(cp), cf_pair_lineno(cp),
3043                                        attr->name, attr->name);
3044                         } else {
3045                                 CONF_SECTION *cs = cf_itemtosection(ci);
3046
3047                                 WARN("%s[%d] Please change %%{%s} to &%s",
3048                                        cf_section_filename(cs), cf_section_lineno(cs),
3049                                        attr->name, attr->name);
3050                         }
3051                         TALLOC_FREE(*pvpt);
3052                         *pvpt = attr;
3053                         return true;
3054                 }
3055         }
3056
3057         /*
3058          *      Re-write it to be a pre-parsed XLAT structure.
3059          */
3060         vpt->type = TMPL_TYPE_XLAT_STRUCT;
3061         vpt->tmpl_xlat = head;
3062
3063         return true;
3064 }
3065
3066
3067 #ifdef HAVE_REGEX
3068 static bool pass2_regex_compile(CONF_ITEM const *ci, value_pair_tmpl_t *vpt)
3069 {
3070         ssize_t slen;
3071         regex_t *preg;
3072
3073         rad_assert(vpt->type == TMPL_TYPE_REGEX);
3074
3075         /*
3076          *      It's a dynamic expansion.  We can't expand the string,
3077          *      but we can pre-parse it as an xlat struct.  In that
3078          *      case, we convert it to a pre-compiled XLAT.
3079          *
3080          *      This is a little more complicated than it needs to be
3081          *      because radius_evaluate_map() keys off of the src
3082          *      template type, instead of the operators.  And, the
3083          *      pass2_xlat_compile() function expects to get passed an
3084          *      XLAT instead of a REGEX.
3085          */
3086         if (strchr(vpt->name, '%')) {
3087                 vpt->type = TMPL_TYPE_XLAT;
3088                 return pass2_xlat_compile(ci, &vpt, false, NULL);
3089         }
3090
3091         slen = regex_compile(vpt, &preg, vpt->name, vpt->len,
3092                              vpt->tmpl_iflag, vpt->tmpl_mflag, false);
3093         if (slen <= 0) {
3094                 char *spaces, *text;
3095
3096                 fr_canonicalize_error(vpt, &spaces, &text, slen, vpt->name);
3097
3098                 cf_log_err(ci, "Invalid regular expression:");
3099                 cf_log_err(ci, "%s", text);
3100                 cf_log_err(ci, "%s^ %s", spaces, fr_strerror());
3101
3102                 talloc_free(spaces);
3103                 talloc_free(text);
3104
3105                 return false;
3106         }
3107
3108         vpt->type = TMPL_TYPE_REGEX_STRUCT;
3109         vpt->tmpl_preg = preg;
3110
3111         return true;
3112 }
3113 #endif
3114
3115 static bool pass2_fixup_undefined(CONF_ITEM const *ci, value_pair_tmpl_t *vpt)
3116 {
3117         DICT_ATTR const *da;
3118
3119         rad_assert(vpt->type == TMPL_TYPE_ATTR_UNDEFINED);
3120
3121         da = dict_attrbyname(vpt->tmpl_unknown_name);
3122         if (!da) {
3123                 cf_log_err(ci, "Unknown attribute '%s'", vpt->tmpl_unknown_name);
3124                 return false;
3125         }
3126
3127         vpt->tmpl_da = da;
3128         vpt->type = TMPL_TYPE_ATTR;
3129         return true;
3130 }
3131
3132 /** Convert an &attr[*] reference to an XLAT
3133  *
3134  * @param vpt to convert
3135  * @return true if conversion was successful, else false.
3136  */
3137 static bool pass2_fixup_attr_count(value_pair_tmpl_t *vpt)
3138 {
3139         xlat_exp_t *node;
3140
3141         rad_assert(vpt->type == TMPL_TYPE_ATTR);
3142         rad_assert(vpt->tmpl_num == NUM_COUNT);
3143
3144         node = xlat_from_tmpl_attr(vpt, vpt);
3145         if (!node) return false;
3146
3147         memset(&vpt->data, 0, sizeof(vpt->data));
3148         vpt->type = TMPL_TYPE_XLAT_STRUCT;
3149         vpt->data.xlat = node;
3150
3151         return true;
3152 }
3153
3154 static bool pass2_callback(UNUSED void *ctx, fr_cond_t *c)
3155 {
3156         value_pair_map_t *map;
3157
3158         if (c->type == COND_TYPE_EXISTS) {
3159                 if (c->data.vpt->type == TMPL_TYPE_XLAT) {
3160                         return pass2_xlat_compile(c->ci, &c->data.vpt, true, NULL);
3161                 }
3162
3163                 rad_assert(c->data.vpt->type != TMPL_TYPE_REGEX);
3164
3165                 /*
3166                  *      The existence check might have been &Foo-Bar,
3167                  *      where Foo-Bar is defined by a module.
3168                  */
3169                 if (c->pass2_fixup == PASS2_FIXUP_ATTR) {
3170                         if (!pass2_fixup_undefined(c->ci, c->data.vpt)) return false;
3171                         c->pass2_fixup = PASS2_FIXUP_NONE;
3172                 }
3173
3174                 if ((c->data.vpt->type == TMPL_TYPE_ATTR) && (c->data.vpt->tmpl_num == NUM_COUNT)) {
3175                         return pass2_fixup_attr_count(c->data.vpt);
3176                 }
3177                 return true;
3178         }
3179
3180         /*
3181          *      Maps have a paircompare fixup applied to them.
3182          *      Others get ignored.
3183          */
3184         if (c->pass2_fixup == PASS2_FIXUP_NONE) {
3185                 if (c->type == COND_TYPE_MAP) {
3186                         map = c->data.map;
3187                         goto check_paircmp;
3188                 }
3189
3190                 return true;
3191         }
3192
3193         map = c->data.map;      /* shorter */
3194
3195         /*
3196          *      Auth-Type := foo
3197          *
3198          *      Where "foo" is dynamically defined.
3199          */
3200         if (c->pass2_fixup == PASS2_FIXUP_TYPE) {
3201                 if (!dict_valbyname(map->lhs->tmpl_da->attr,
3202                                     map->lhs->tmpl_da->vendor,
3203                                     map->rhs->name)) {
3204                         cf_log_err(map->ci, "Invalid reference to non-existent %s %s { ... }",
3205                                    map->lhs->tmpl_da->name,
3206                                    map->rhs->name);
3207                         return false;
3208                 }
3209
3210                 /*
3211                  *      These guys can't have a paircompare fixup applied.
3212                  */
3213                 c->pass2_fixup = PASS2_FIXUP_NONE;
3214                 return true;
3215         }
3216
3217         if (c->pass2_fixup == PASS2_FIXUP_ATTR) {
3218                 if (map->lhs->type == TMPL_TYPE_ATTR_UNDEFINED) {
3219                         if (!pass2_fixup_undefined(map->ci, map->lhs)) return false;
3220                 }
3221
3222                 if (map->rhs->type == TMPL_TYPE_ATTR_UNDEFINED) {
3223                         if (!pass2_fixup_undefined(map->ci, map->rhs)) return false;
3224                 }
3225
3226                 c->pass2_fixup = PASS2_FIXUP_NONE;
3227         }
3228
3229 check_paircmp:
3230         /*
3231          *      Just in case someone adds a new fixup later.
3232          */
3233         rad_assert((c->pass2_fixup == PASS2_FIXUP_NONE) ||
3234                    (c->pass2_fixup == PASS2_PAIRCOMPARE));
3235
3236         if ((map->lhs->type == TMPL_TYPE_ATTR) && (map->lhs->tmpl_num == NUM_COUNT)) {
3237                 if (!pass2_fixup_attr_count(map->lhs)) return false;
3238         }
3239         if ((map->rhs->type == TMPL_TYPE_ATTR) && (map->rhs->tmpl_num == NUM_COUNT)) {
3240                 if (!pass2_fixup_attr_count(map->rhs)) return false;
3241         }
3242
3243         /*
3244          *      Precompile xlat's
3245          */
3246         if (map->lhs->type == TMPL_TYPE_XLAT) {
3247                 /*
3248                  *      Don't compile the LHS to an attribute
3249                  *      reference for now.  When we do that, we've got
3250                  *      to check the RHS for type-specific data, and
3251                  *      parse it to a TMPL_TYPE_DATA.
3252                  */
3253                 if (!pass2_xlat_compile(map->ci, &map->lhs, false, NULL)) {
3254                         return false;
3255                 }
3256         }
3257
3258         if (map->rhs->type == TMPL_TYPE_XLAT) {
3259                 /*
3260                  *      Convert the RHS to an attribute reference only
3261                  *      if the LHS is an attribute reference, AND is
3262                  *      of the same type as the RHS.
3263                  *
3264                  *      We can fix this when the code in evaluate.c
3265                  *      can handle strings on the LHS, and attributes
3266                  *      on the RHS.  For now, the code in parser.c
3267                  *      forbids this.
3268                  */
3269                 if (map->lhs->type == TMPL_TYPE_ATTR) {
3270                         DICT_ATTR const *da = c->cast;
3271
3272                         if (!c->cast) da = map->lhs->tmpl_da;
3273
3274                         if (!pass2_xlat_compile(map->ci, &map->rhs, true, da)) {
3275                                 return false;
3276                         }
3277
3278                 } else {
3279                         if (!pass2_xlat_compile(map->ci, &map->rhs, false, NULL)) {
3280                                 return false;
3281                         }
3282                 }
3283         }
3284
3285         /*
3286          *      Convert bare refs to %{Foreach-Variable-N}
3287          */
3288         if ((map->lhs->type == TMPL_TYPE_LITERAL) &&
3289             (strncmp(map->lhs->name, "Foreach-Variable-", 17) == 0)) {
3290                 char *fmt;
3291                 ssize_t slen;
3292                 value_pair_tmpl_t *vpt;
3293
3294                 fmt = talloc_asprintf(map->lhs, "%%{%s}", map->lhs->name);
3295                 slen = tmpl_afrom_str(map, &vpt, fmt, talloc_array_length(fmt) - 1,
3296                                       T_DOUBLE_QUOTED_STRING, REQUEST_CURRENT, PAIR_LIST_REQUEST);
3297                 if (slen < 0) {
3298                         char *spaces, *text;
3299
3300                         fr_canonicalize_error(map->ci, &spaces, &text, slen, fr_strerror());
3301
3302                         cf_log_err(map->ci, "Failed converting %s to xlat", map->lhs->name);
3303                         cf_log_err(map->ci, "%s", fmt);
3304                         cf_log_err(map->ci, "%s^ %s", spaces, text);
3305
3306                         talloc_free(spaces);
3307                         talloc_free(text);
3308                         talloc_free(fmt);
3309
3310                         return false;
3311                 }
3312                 talloc_free(map->lhs);
3313                 map->lhs = vpt;
3314         }
3315
3316 #ifdef HAVE_REGEX
3317         if (map->rhs->type == TMPL_TYPE_REGEX) {
3318                 if (!pass2_regex_compile(map->ci, map->rhs)) {
3319                         return false;
3320                 }
3321         }
3322         rad_assert(map->lhs->type != TMPL_TYPE_REGEX);
3323 #endif
3324
3325         /*
3326          *      Only attributes can have a paircompare registered, and
3327          *      they can only be with the current REQUEST, and only
3328          *      with the request pairs.
3329          */
3330         if ((map->lhs->type != TMPL_TYPE_ATTR) ||
3331             (map->lhs->tmpl_request != REQUEST_CURRENT) ||
3332             (map->lhs->tmpl_list != PAIR_LIST_REQUEST)) {
3333                 return true;
3334         }
3335
3336         if (!radius_find_compare(map->lhs->tmpl_da)) return true;
3337
3338         if (map->rhs->type == TMPL_TYPE_ATTR) {
3339                 cf_log_err(map->ci, "Cannot compare virtual attribute %s to another attribute",
3340                            map->lhs->name);
3341                 return false;
3342         }
3343
3344         if (map->rhs->type == TMPL_TYPE_REGEX) {
3345                 cf_log_err(map->ci, "Cannot compare virtual attribute %s via a regex",
3346                            map->lhs->name);
3347                 return false;
3348         }
3349
3350         if (c->cast) {
3351                 cf_log_err(map->ci, "Cannot cast virtual attribute %s",
3352                            map->lhs->name);
3353                 return false;
3354         }
3355
3356         if (map->op != T_OP_CMP_EQ) {
3357                 cf_log_err(map->ci, "Must use '==' for comparisons with virtual attribute %s",
3358                            map->lhs->name);
3359                 return false;
3360         }
3361
3362         /*
3363          *      Mark it as requiring a paircompare() call, instead of
3364          *      paircmp().
3365          */
3366         c->pass2_fixup = PASS2_PAIRCOMPARE;
3367
3368         return true;
3369 }
3370
3371
3372 /*
3373  *      Compile the RHS of update sections to xlat_exp_t
3374  */
3375 static bool modcall_pass2_update(modgroup *g)
3376 {
3377         value_pair_map_t *map;
3378
3379         for (map = g->map; map != NULL; map = map->next) {
3380                 if (map->rhs->type == TMPL_TYPE_XLAT) {
3381                         rad_assert(map->rhs->tmpl_xlat == NULL);
3382
3383                         /*
3384                          *      FIXME: compile to attribute && handle
3385                          *      the conversion in map_to_vp().
3386                          */
3387                         if (!pass2_xlat_compile(map->ci, &map->rhs, false, NULL)) {
3388                                 return false;
3389                         }
3390                 }
3391
3392                 rad_assert(map->rhs->type != TMPL_TYPE_REGEX);
3393         }
3394
3395         return true;
3396 }
3397 #endif
3398
3399 /*
3400  *      Do a second-stage pass on compiling the modules.
3401  */
3402 bool modcall_pass2(modcallable *mc)
3403 {
3404         ssize_t slen;
3405         char const *name2;
3406         modcallable *c;
3407         modgroup *g;
3408
3409         for (c = mc; c != NULL; c = c->next) {
3410                 switch (c->type) {
3411                 default:
3412                         rad_assert(0 == 1);
3413                         break;
3414
3415 #ifdef WITH_UNLANG
3416                 case MOD_UPDATE:
3417                         g = mod_callabletogroup(c);
3418                         if (g->done_pass2) return true;
3419
3420                         name2 = cf_section_name2(g->cs);
3421                         if (!name2) {
3422                                 c->debug_name = group_name[c->type];
3423                         } else {
3424                                 c->debug_name = talloc_asprintf(c, "update %s", name2);
3425                         }
3426
3427                         if (!modcall_pass2_update(g)) {
3428                                 return false;
3429                         }
3430                         g->done_pass2 = true;
3431                         break;
3432
3433                 case MOD_XLAT:   /* @todo: pre-parse xlat's */
3434                 case MOD_REFERENCE:
3435                 case MOD_BREAK:
3436                 case MOD_RETURN:
3437 #endif
3438
3439                 case MOD_SINGLE:
3440                         c->debug_name = c->name;
3441                         break;  /* do nothing */
3442
3443 #ifdef WITH_UNLANG
3444                 case MOD_IF:
3445                 case MOD_ELSIF:
3446                         g = mod_callabletogroup(c);
3447                         if (g->done_pass2) return true;
3448
3449                         name2 = cf_section_name2(g->cs);
3450                         c->debug_name = talloc_asprintf(c, "%s %s", group_name[c->type], name2);
3451
3452                         /*
3453                          *      Don't walk over these.
3454                          */
3455                         if ((g->cond->type == COND_TYPE_TRUE) ||
3456                             (g->cond->type == COND_TYPE_FALSE)) {
3457                                 break;
3458                         }
3459
3460                         /*
3461                          *      The compilation code takes care of
3462                          *      simplifying 'true' and 'false'
3463                          *      conditions.  For others, we have to do
3464                          *      a second pass to parse && compile xlats.
3465                          */
3466                         if (!fr_condition_walk(g->cond, pass2_callback, NULL)) {
3467                                 return false;
3468                         }
3469
3470                         if (!modcall_pass2(g->children)) return false;
3471                         g->done_pass2 = true;
3472                         break;
3473 #endif
3474
3475 #ifdef WITH_UNLANG
3476                 case MOD_SWITCH:
3477                         g = mod_callabletogroup(c);
3478                         if (g->done_pass2) return true;
3479
3480                         name2 = cf_section_name2(g->cs);
3481                         c->debug_name = talloc_asprintf(c, "%s %s", group_name[c->type], name2);
3482
3483                         /*
3484                          *      We had &Foo-Bar, where Foo-Bar is
3485                          *      defined by a module.
3486                          */
3487                         if (!g->vpt) {
3488                                 rad_assert(c->name != NULL);
3489                                 rad_assert(c->name[0] == '&');
3490                                 rad_assert(cf_section_name2_type(g->cs) == T_BARE_WORD);
3491
3492                                 slen = tmpl_afrom_str(g->cs, &g->vpt, c->name, strlen(c->name),
3493                                                       cf_section_name2_type(g->cs),
3494                                                       REQUEST_CURRENT, PAIR_LIST_REQUEST);
3495                                 if (slen < 0) {
3496                                         char *spaces, *text;
3497
3498                                 parse_error:
3499                                         fr_canonicalize_error(g->cs, &spaces, &text, slen, fr_strerror());
3500
3501                                         cf_log_err_cs(g->cs, "Syntax error");
3502                                         cf_log_err_cs(g->cs, "%s", c->name);
3503                                         cf_log_err_cs(g->cs, "%s^ %s", spaces, text);
3504
3505                                         talloc_free(spaces);
3506                                         talloc_free(text);
3507
3508                                         return false;
3509                                 }
3510
3511                                 goto do_children;
3512                         }
3513
3514                         /*
3515                          *      Statically compile xlats
3516                          */
3517                         if (g->vpt->type == TMPL_TYPE_XLAT) {
3518                                 if (!pass2_xlat_compile(cf_sectiontoitem(g->cs),
3519                                                         &g->vpt, true, NULL)) {
3520                                         return false;
3521                                 }
3522
3523                                 goto do_children;
3524                         }
3525
3526                         /*
3527                          *      We may have: switch Foo-Bar {
3528                          *
3529                          *      where Foo-Bar is an attribute defined
3530                          *      by a module.  Since there's no leading
3531                          *      &, it's parsed as a literal.  But if
3532                          *      we can parse it as an attribute,
3533                          *      switch to using that.
3534                          */
3535                         if (g->vpt->type == TMPL_TYPE_LITERAL) {
3536                                 value_pair_tmpl_t *vpt;
3537
3538                                 slen = tmpl_afrom_str(g->cs, &vpt, c->name, strlen(c->name), cf_section_name2_type(g->cs),
3539                                                       REQUEST_CURRENT, PAIR_LIST_REQUEST);
3540                                 if (slen < 0) goto parse_error;
3541                                 if (vpt->type == TMPL_TYPE_ATTR) {
3542                                         talloc_free(g->vpt);
3543                                         g->vpt = vpt;
3544                                 }
3545
3546                                 goto do_children;
3547                         }
3548
3549                         /*
3550                          *      Warn about old-style configuration.
3551                          *
3552                          *      DEPRECATED: switch User-Name { ...
3553                          *      ALLOWED   : switch &User-Name { ...
3554                          */
3555                         if ((g->vpt->type == TMPL_TYPE_ATTR) &&
3556                             (c->name[0] != '&')) {
3557                                 WARN("%s[%d]: Please change %s to &%s",
3558                                        cf_section_filename(g->cs),
3559                                        cf_section_lineno(g->cs),
3560                                        c->name, c->name);
3561                         }
3562
3563                 do_children:
3564                         if (!modcall_pass2(g->children)) return false;
3565                         g->done_pass2 = true;
3566                         break;
3567
3568                 case MOD_CASE:
3569                         g = mod_callabletogroup(c);
3570                         if (g->done_pass2) return true;
3571
3572                         name2 = cf_section_name2(g->cs);
3573                         if (!name2) {
3574                                 c->debug_name = group_name[c->type];
3575                         } else {
3576                                 c->debug_name = talloc_asprintf(c, "%s %s", group_name[c->type], name2);
3577                         }
3578
3579                         rad_assert(c->parent != NULL);
3580                         rad_assert(c->parent->type == MOD_SWITCH);
3581
3582                         /*
3583                          *      The statement may refer to an
3584                          *      attribute which doesn't exist until
3585                          *      all of the modules have been loaded.
3586                          *      Check for that now.
3587                          */
3588                         if (!g->vpt && c->name &&
3589                             (c->name[0] == '&') &&
3590                             (cf_section_name2_type(g->cs) == T_BARE_WORD)) {
3591                                 slen = tmpl_afrom_str(g->cs, &g->vpt, c->name, strlen(c->name),
3592                                                       cf_section_name2_type(g->cs),
3593                                                       REQUEST_CURRENT, PAIR_LIST_REQUEST);
3594                                 if (slen < 0) goto parse_error;
3595                         }
3596
3597                         /*
3598                          *      We have "case {...}".  There's no
3599                          *      argument, so we don't need to check
3600                          *      it.
3601                          */
3602                         if (!g->vpt) goto do_children;
3603
3604                         /*
3605                          *      Do type-specific checks on the case statement
3606                          */
3607                         if (g->vpt->type == TMPL_TYPE_LITERAL) {
3608                                 modgroup *f;
3609
3610                                 f = mod_callabletogroup(mc->parent);
3611                                 rad_assert(f->vpt != NULL);
3612
3613                                 /*
3614                                  *      We're switching over an
3615                                  *      attribute.  Check that the
3616                                  *      values match.
3617                                  */
3618                                 if (f->vpt->type == TMPL_TYPE_ATTR) {
3619                                         rad_assert(f->vpt->tmpl_da != NULL);
3620
3621                                         if (!tmpl_cast_in_place(g->vpt, f->vpt->tmpl_da->type, f->vpt->tmpl_da)) {
3622                                                 cf_log_err_cs(g->cs, "Invalid argument for case statement: %s",
3623                                                               fr_strerror());
3624                                                 return false;
3625                                         }
3626                                 }
3627
3628                                 goto do_children;
3629                         }
3630
3631                         /*
3632                          *      Compile and sanity check xlat
3633                          *      expansions.
3634                          */
3635                         if (g->vpt->type == TMPL_TYPE_XLAT) {
3636                                 modgroup *f;
3637
3638                                 f = mod_callabletogroup(mc->parent);
3639                                 rad_assert(f->vpt != NULL);
3640
3641                                 /*
3642                                  *      Don't expand xlat's into an
3643                                  *      attribute of a different type.
3644                                  */
3645                                 if (f->vpt->type == TMPL_TYPE_ATTR) {
3646                                         if (!pass2_xlat_compile(cf_sectiontoitem(g->cs),
3647                                                                 &g->vpt, true, f->vpt->tmpl_da)) {
3648                                                 return false;
3649                                         }
3650                                 } else {
3651                                         if (!pass2_xlat_compile(cf_sectiontoitem(g->cs),
3652                                                                 &g->vpt, true, NULL)) {
3653                                                 return false;
3654                                         }
3655                                 }
3656                         }
3657
3658                         if (!modcall_pass2(g->children)) return false;
3659                         g->done_pass2 = true;
3660                         break;
3661
3662                 case MOD_FOREACH:
3663                         g = mod_callabletogroup(c);
3664                         if (g->done_pass2) return true;
3665
3666                         name2 = cf_section_name2(g->cs);
3667                         c->debug_name = talloc_asprintf(c, "%s %s", group_name[c->type], name2);
3668
3669                         /*
3670                          *      Already parsed, handle the children.
3671                          */
3672                         if (g->vpt) goto check_children;
3673
3674                         /*
3675                          *      We had &Foo-Bar, where Foo-Bar is
3676                          *      defined by a module.
3677                          */
3678                         rad_assert(c->name != NULL);
3679                         rad_assert(c->name[0] == '&');
3680                         rad_assert(cf_section_name2_type(g->cs) == T_BARE_WORD);
3681
3682                         /*
3683                          *      The statement may refer to an
3684                          *      attribute which doesn't exist until
3685                          *      all of the modules have been loaded.
3686                          *      Check for that now.
3687                          */
3688                         slen = tmpl_afrom_str(g->cs, &g->vpt, c->name, strlen(c->name), cf_section_name2_type(g->cs),
3689                                               REQUEST_CURRENT, PAIR_LIST_REQUEST);
3690                         if (slen < 0) goto parse_error;
3691
3692                 check_children:
3693                         rad_assert(g->vpt->type == TMPL_TYPE_ATTR);
3694                         if (g->vpt->tmpl_num != NUM_ALL) {
3695                                 cf_log_err_cs(g->cs, "MUST NOT use instance selectors in 'foreach'");
3696                                 return false;
3697                         }
3698                         if (!modcall_pass2(g->children)) return false;
3699                         g->done_pass2 = true;
3700                         break;
3701
3702                 case MOD_ELSE:
3703                         c->debug_name = group_name[c->type];
3704                         goto do_recurse;
3705
3706                 case MOD_POLICY:
3707                         g = mod_callabletogroup(c);
3708                         c->debug_name = talloc_asprintf(c, "%s %s", group_name[c->type], cf_section_name1(g->cs));
3709                         goto do_recurse;
3710 #endif
3711
3712                 case MOD_GROUP:
3713                 case MOD_LOAD_BALANCE:
3714                 case MOD_REDUNDANT_LOAD_BALANCE:
3715                         c->debug_name = group_name[c->type];
3716
3717 #ifdef WITH_UNLANG
3718                 do_recurse:
3719 #endif
3720                         g = mod_callabletogroup(c);
3721                         if (!g->cs) {
3722                                 c->debug_name = mc->name; /* for authorize, etc. */
3723
3724                         } else if (c->type == MOD_GROUP) { /* for Auth-Type, etc. */
3725                                 char const *name1 = cf_section_name1(g->cs);
3726
3727                                 if (strcmp(name1, group_name[c->type]) != 0) {
3728                                         c->debug_name = talloc_asprintf(c, "%s %s", name1, cf_section_name2(g->cs));
3729                                 }
3730                         }
3731
3732                         if (g->done_pass2) return true;
3733                         if (!modcall_pass2(g->children)) return false;
3734                         g->done_pass2 = true;
3735                         break;
3736                 }
3737         }
3738
3739         return true;
3740 }
3741
3742 void modcall_debug(modcallable *mc, int depth)
3743 {
3744         modcallable *this;
3745         modgroup *g;
3746         value_pair_map_t *map;
3747         char buffer[1024];
3748
3749         for (this = mc; this != NULL; this = this->next) {
3750                 switch (this->type) {
3751                 default:
3752                         break;
3753
3754                 case MOD_SINGLE: {
3755                         modsingle *single = mod_callabletosingle(this);
3756
3757                         DEBUG("%.*s%s", depth, modcall_spaces,
3758                                 single->modinst->name);
3759                         }
3760                         break;
3761
3762 #ifdef WITH_UNLANG
3763                 case MOD_UPDATE:
3764                         g = mod_callabletogroup(this);
3765                         DEBUG("%.*s%s {", depth, modcall_spaces,
3766                                 group_name[this->type]);
3767
3768                         for (map = g->map; map != NULL; map = map->next) {
3769                                 map_prints(buffer, sizeof(buffer), map);
3770                                 DEBUG("%.*s%s", depth + 1, modcall_spaces, buffer);
3771                         }
3772
3773                         DEBUG("%.*s}", depth, modcall_spaces);
3774                         break;
3775
3776                 case MOD_ELSE:
3777                         g = mod_callabletogroup(this);
3778                         DEBUG("%.*s%s {", depth, modcall_spaces,
3779                                 group_name[this->type]);
3780                         modcall_debug(g->children, depth + 1);
3781                         DEBUG("%.*s}", depth, modcall_spaces);
3782                         break;
3783
3784                 case MOD_IF:
3785                 case MOD_ELSIF:
3786                         g = mod_callabletogroup(this);
3787                         fr_cond_sprint(buffer, sizeof(buffer), g->cond);
3788                         DEBUG("%.*s%s (%s) {", depth, modcall_spaces,
3789                                 group_name[this->type], buffer);
3790                         modcall_debug(g->children, depth + 1);
3791                         DEBUG("%.*s}", depth, modcall_spaces);
3792                         break;
3793
3794                 case MOD_SWITCH:
3795                 case MOD_CASE:
3796                         g = mod_callabletogroup(this);
3797                         tmpl_prints(buffer, sizeof(buffer), g->vpt, NULL);
3798                         DEBUG("%.*s%s %s {", depth, modcall_spaces,
3799                                 group_name[this->type], buffer);
3800                         modcall_debug(g->children, depth + 1);
3801                         DEBUG("%.*s}", depth, modcall_spaces);
3802                         break;
3803
3804                 case MOD_POLICY:
3805                 case MOD_FOREACH:
3806                         g = mod_callabletogroup(this);
3807                         DEBUG("%.*s%s %s {", depth, modcall_spaces,
3808                                 group_name[this->type], this->name);
3809                         modcall_debug(g->children, depth + 1);
3810                         DEBUG("%.*s}", depth, modcall_spaces);
3811                         break;
3812
3813                 case MOD_BREAK:
3814                         DEBUG("%.*sbreak", depth, modcall_spaces);
3815                         break;
3816
3817 #endif
3818                 case MOD_GROUP:
3819                         g = mod_callabletogroup(this);
3820                         DEBUG("%.*s%s {", depth, modcall_spaces,
3821                               group_name[this->type]);
3822                         modcall_debug(g->children, depth + 1);
3823                         DEBUG("%.*s}", depth, modcall_spaces);
3824                         break;
3825
3826
3827                 case MOD_LOAD_BALANCE:
3828                 case MOD_REDUNDANT_LOAD_BALANCE:
3829                         g = mod_callabletogroup(this);
3830                         DEBUG("%.*s%s {", depth, modcall_spaces,
3831                                 group_name[this->type]);
3832                         modcall_debug(g->children, depth + 1);
3833                         DEBUG("%.*s}", depth, modcall_spaces);
3834                         break;
3835                 }
3836         }
3837 }