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