Syntax errors are errors, not assertions
[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         vp_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[MOD_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_next_sibling);
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_next_sibling)
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_next_sibling)) {
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_next_sibling)
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                 vp_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_lvl >= 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 been asked to unwind to the
691                          *      enclosing "foreach".  We're here, so
692                          *      we can stop unwinding.
693                          */
694                         if (next->unwind == MOD_BREAK) {
695                                 entry->unwind = 0;
696                                 break;
697                         }
698
699                         /*
700                          *      Unwind all the way.
701                          */
702                         if (next->unwind == MOD_RETURN) {
703                                 entry->unwind = MOD_RETURN;
704                                 break;
705                         }
706                 } /* loop over VPs */
707
708                 /*
709                  *      Free the copied vps and the request data
710                  *      If we don't remove the request data, something could call
711                  *      the xlat outside of a foreach loop and trigger a segv.
712                  */
713                 fr_pair_list_free(&vps);
714                 request_data_get(request, (void *)radius_get_vp, foreach_depth);
715
716                 rad_assert(next != NULL);
717                 result = next->result;
718                 priority = next->priority;
719                 MOD_LOG_CLOSE_BRACE;
720                 goto calculate_result;
721         } /* MOD_FOREACH */
722
723         /*
724          *      Break out of a "foreach" loop, or return from a nested
725          *      group.
726          */
727         if ((c->type == MOD_BREAK) || (c->type == MOD_RETURN)) {
728                 int i;
729                 VALUE_PAIR **copy_p;
730
731                 RDEBUG2("%s", unlang_keyword[c->type]);
732
733                 for (i = 8; i >= 0; i--) {
734                         copy_p = request_data_get(request, (void *)radius_get_vp, i);
735                         if (copy_p) {
736                                 if (c->type == MOD_BREAK) {
737                                         RDEBUG2("# break Foreach-Variable-%d", i);
738                                         break;
739                                 }
740                         }
741                 }
742
743                 /*
744                  *      Leave result / priority on the stack, and stop processing the section.
745                  */
746                 entry->unwind = c->type;
747                 goto finish;
748         } /* MOD_BREAK */
749
750 #endif    /* WITH_UNLANG */
751
752         /*
753          *      Child is a group that has children of it's own.
754          */
755         if ((c->type == MOD_GROUP) || (c->type == MOD_POLICY)
756 #ifdef WITH_UNLANG
757             || (c->type == MOD_CASE)
758 #endif
759                 ) {
760                 modgroup *g;
761
762 #ifdef WITH_UNLANG
763         do_children:
764 #endif
765                 g = mod_callabletogroup(c);
766
767                 /*
768                  *      This should really have been caught in the
769                  *      compiler, and the node never generated.  But
770                  *      doing that requires changing it's API so that
771                  *      it returns a flag instead of the compiled
772                  *      MOD_GROUP.
773                  */
774                 if (!g->children) {
775                         RDEBUG2("%s { ... } # empty sub-section is ignored", c->name);
776                         goto next_sibling;
777                 }
778
779                 MOD_LOG_OPEN_BRACE;
780                 modcall_child(request, component,
781                               depth + 1, entry, g->children,
782                               &result, true);
783                 MOD_LOG_CLOSE_BRACE;
784                 goto calculate_result;
785         } /* MOD_GROUP */
786
787 #ifdef WITH_UNLANG
788         if (c->type == MOD_SWITCH) {
789                 modcallable *this, *found, *null_case;
790                 modgroup *g, *h;
791                 fr_cond_t cond;
792                 value_data_t data;
793                 vp_map_t map;
794                 vp_tmpl_t vpt;
795
796                 MOD_LOG_OPEN_BRACE;
797
798                 g = mod_callabletogroup(c);
799
800                 memset(&cond, 0, sizeof(cond));
801                 memset(&map, 0, sizeof(map));
802
803                 cond.type = COND_TYPE_MAP;
804                 cond.data.map = &map;
805
806                 map.op = T_OP_CMP_EQ;
807                 map.ci = cf_section_to_item(g->cs);
808
809                 rad_assert(g->vpt != NULL);
810
811                 null_case = found = NULL;
812                 data.ptr = NULL;
813
814                 /*
815                  *      The attribute doesn't exist.  We can skip
816                  *      directly to the default 'case' statement.
817                  */
818                 if ((g->vpt->type == TMPL_TYPE_ATTR) && (tmpl_find_vp(NULL, request, g->vpt) < 0)) {
819                 find_null_case:
820                         for (this = g->children; this; this = this->next) {
821                                 rad_assert(this->type == MOD_CASE);
822
823                                 h = mod_callabletogroup(this);
824                                 if (h->vpt) continue;
825
826                                 found = this;
827                                 break;
828                         }
829
830                         goto do_null_case;
831                 }
832
833                 /*
834                  *      Expand the template if necessary, so that it
835                  *      is evaluated once instead of for each 'case'
836                  *      statement.
837                  */
838                 if ((g->vpt->type == TMPL_TYPE_XLAT_STRUCT) ||
839                     (g->vpt->type == TMPL_TYPE_XLAT) ||
840                     (g->vpt->type == TMPL_TYPE_EXEC)) {
841                         char *p;
842                         ssize_t len;
843
844                         len = tmpl_aexpand(request, &p, request, g->vpt, NULL, NULL);
845                         if (len < 0) goto find_null_case;
846                         data.strvalue = p;
847                         tmpl_init(&vpt, TMPL_TYPE_LITERAL, data.strvalue, len);
848                 }
849
850                 /*
851                  *      Find either the exact matching name, or the
852                  *      "case {...}" statement.
853                  */
854                 for (this = g->children; this; this = this->next) {
855                         rad_assert(this->type == MOD_CASE);
856
857                         h = mod_callabletogroup(this);
858
859                         /*
860                          *      Remember the default case
861                          */
862                         if (!h->vpt) {
863                                 if (!null_case) null_case = this;
864                                 continue;
865                         }
866
867                         /*
868                          *      If we're switching over an attribute
869                          *      AND we haven't pre-parsed the data for
870                          *      the case statement, then cast the data
871                          *      to the type of the attribute.
872                          */
873                         if ((g->vpt->type == TMPL_TYPE_ATTR) &&
874                             (h->vpt->type != TMPL_TYPE_DATA)) {
875                                 map.rhs = g->vpt;
876                                 map.lhs = h->vpt;
877                                 cond.cast = g->vpt->tmpl_da;
878
879                                 /*
880                                  *      Remove unnecessary casting.
881                                  */
882                                 if ((h->vpt->type == TMPL_TYPE_ATTR) &&
883                                     (g->vpt->tmpl_da->type == h->vpt->tmpl_da->type)) {
884                                         cond.cast = NULL;
885                                 }
886
887                                 /*
888                                  *      Use the pre-expanded string.
889                                  */
890                         } else if ((g->vpt->type == TMPL_TYPE_XLAT_STRUCT) ||
891                                    (g->vpt->type == TMPL_TYPE_XLAT) ||
892                                    (g->vpt->type == TMPL_TYPE_EXEC)) {
893                                 map.rhs = h->vpt;
894                                 map.lhs = &vpt;
895                                 cond.cast = NULL;
896
897                                 /*
898                                  *      Else evaluate the 'switch' statement.
899                                  */
900                         } else {
901                                 map.rhs = h->vpt;
902                                 map.lhs = g->vpt;
903                                 cond.cast = NULL;
904                         }
905
906                         if (radius_evaluate_map(request, RLM_MODULE_UNKNOWN, 0,
907                                                 &cond) == 1) {
908                                 found = this;
909                                 break;
910                         }
911                 }
912
913                 if (!found) found = null_case;
914
915         do_null_case:
916                 talloc_free(data.ptr);
917                 modcall_child(request, component, depth + 1, entry, found, &result, true);
918                 MOD_LOG_CLOSE_BRACE;
919                 goto calculate_result;
920         } /* MOD_SWITCH */
921 #endif
922
923         if ((c->type == MOD_LOAD_BALANCE) ||
924             (c->type == MOD_REDUNDANT_LOAD_BALANCE)) {
925                 uint32_t count = 0;
926                 modcallable *this, *found;
927                 modgroup *g;
928
929                 MOD_LOG_OPEN_BRACE;
930
931                 g = mod_callabletogroup(c);
932                 found = g->children;
933                 rad_assert(g->children != NULL);
934
935                 /*
936                  *      Choose a child at random.
937                  */
938                 for (this = g->children; this; this = this->next) {
939                         count++;
940
941                         if ((count * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
942                                 found = this;
943                         }
944                 }
945
946                 if (c->type == MOD_LOAD_BALANCE) {
947                         modcall_child(request, component,
948                                       depth + 1, entry, found,
949                                       &result, false);
950
951                 } else {
952                         this = found;
953
954                         do {
955                                 modcall_child(request, component,
956                                               depth + 1, entry, this,
957                                               &result, false);
958                                 if (this->actions[result] == MOD_ACTION_RETURN) {
959                                         priority = -1;
960                                         break;
961                                 }
962
963                                 this = this->next;
964                                 if (!this) this = g->children;
965                         } while (this != found);
966                 }
967                 MOD_LOG_CLOSE_BRACE;
968                 goto calculate_result;
969         } /* MOD_LOAD_BALANCE */
970
971         /*
972          *      Reference another virtual server.
973          *
974          *      This should really be deleted, and replaced with a
975          *      more abstracted / functional version.
976          */
977         if (c->type == MOD_REFERENCE) {
978                 modref *mr = mod_callabletoref(c);
979                 char const *server = request->server;
980
981                 if (server == mr->ref_name) {
982                         RWDEBUG("Suppressing recursive call to server %s", server);
983                         goto next_sibling;
984                 }
985
986                 request->server = mr->ref_name;
987                 RDEBUG("server %s { # nested call", mr->ref_name);
988                 result = indexed_modcall(component, 0, request);
989                 RDEBUG("} # server %s with nested call", mr->ref_name);
990                 request->server = server;
991                 goto calculate_result;
992         } /* MOD_REFERENCE */
993
994         /*
995          *      xlat a string without doing anything else
996          *
997          *      This should really be deleted, and replaced with a
998          *      more abstracted / functional version.
999          */
1000         if (c->type == MOD_XLAT) {
1001                 modxlat *mx = mod_callabletoxlat(c);
1002                 char buffer[128];
1003
1004                 if (!mx->exec) {
1005                         radius_xlat(buffer, sizeof(buffer), request, mx->xlat_name, NULL, NULL);
1006                 } else {
1007                         RDEBUG("`%s`", mx->xlat_name);
1008                         radius_exec_program(request, NULL, 0, NULL, request, mx->xlat_name, request->packet->vps,
1009                                             false, true, EXEC_TIMEOUT);
1010                 }
1011
1012                 goto next_sibling;
1013         } /* MOD_XLAT */
1014
1015         /*
1016          *      Add new module types here.
1017          */
1018
1019 calculate_result:
1020 #if 0
1021         RDEBUG("(%s, %d) ? (%s, %d)",
1022                fr_int2str(mod_rcode_table, result, "<invalid>"),
1023                priority,
1024                fr_int2str(mod_rcode_table, entry->result, "<invalid>"),
1025                entry->priority);
1026 #endif
1027
1028
1029         rad_assert(result != RLM_MODULE_UNKNOWN);
1030
1031         /*
1032          *      The child's action says return.  Do so.
1033          */
1034         if ((c->actions[result] == MOD_ACTION_RETURN) &&
1035             (priority <= 0)) {
1036                 entry->result = result;
1037                 goto finish;
1038         }
1039
1040         /*
1041          *      If "reject", break out of the loop and return
1042          *      reject.
1043          */
1044         if (c->actions[result] == MOD_ACTION_REJECT) {
1045                 entry->result = RLM_MODULE_REJECT;
1046                 goto finish;
1047         }
1048
1049         /*
1050          *      The array holds a default priority for this return
1051          *      code.  Grab it in preference to any unset priority.
1052          */
1053         if (priority < 0) {
1054                 priority = c->actions[result];
1055         }
1056
1057         /*
1058          *      We're higher than any previous priority, remember this
1059          *      return code and priority.
1060          */
1061         if (priority > entry->priority) {
1062                 entry->result = result;
1063                 entry->priority = priority;
1064         }
1065
1066 #ifdef WITH_UNLANG
1067         /*
1068          *      If we're processing a "case" statement, we return once
1069          *      it's done, rather than going to the next "case" statement.
1070          */
1071         if (c->type == MOD_CASE) goto finish;
1072 #endif
1073
1074         /*
1075          *      If we've been told to stop processing
1076          *      it, do so.
1077          */
1078         if (entry->unwind == MOD_BREAK) {
1079                 RDEBUG2("# unwind to enclosing foreach");
1080                 goto finish;
1081         }
1082
1083         if (entry->unwind == MOD_RETURN) {
1084                 goto finish;
1085         }
1086
1087 next_sibling:
1088         if (do_next_sibling) {
1089                 entry->c = entry->c->next;
1090
1091                 if (entry->c) goto redo;
1092         }
1093
1094 finish:
1095         /*
1096          *      And we're done!
1097          */
1098         REXDENT();
1099         return true;
1100 }
1101
1102
1103 /** Call a module, iteratively, with a local stack, rather than recursively
1104  *
1105  * What did Paul Graham say about Lisp...?
1106  */
1107 int modcall(rlm_components_t component, modcallable *c, REQUEST *request)
1108 {
1109         modcall_stack_entry_t stack[MODCALL_STACK_MAX];
1110
1111 #ifndef NDEBUG
1112         memset(stack, 0, sizeof(stack));
1113 #endif
1114         /*
1115          *      Set up the initial stack frame.
1116          */
1117         stack[0].c = c;
1118         stack[0].result = default_component_results[component];
1119         stack[0].priority = 0;
1120         stack[0].unwind = 0;
1121
1122         /*
1123          *      Call the main handler.
1124          */
1125         if (!modcall_recurse(request, component, 0, &stack[0], true)) {
1126                 return RLM_MODULE_FAIL;
1127         }
1128
1129         /*
1130          *      Return the result.
1131          */
1132         return stack[0].result;
1133 }
1134
1135
1136 #if 0
1137 static char const *action2str(int action)
1138 {
1139         static char buf[32];
1140         if(action==MOD_ACTION_RETURN)
1141                 return "return";
1142         if(action==MOD_ACTION_REJECT)
1143                 return "reject";
1144         snprintf(buf, sizeof buf, "%d", action);
1145         return buf;
1146 }
1147
1148 /* If you suspect a bug in the parser, you'll want to use these dump
1149  * functions. dump_tree should reproduce a whole tree exactly as it was found
1150  * in radiusd.conf, but in long form (all actions explicitly defined) */
1151 static void dump_mc(modcallable *c, int indent)
1152 {
1153         int i;
1154
1155         if(c->type==MOD_SINGLE) {
1156                 modsingle *single = mod_callabletosingle(c);
1157                 DEBUG("%.*s%s {", indent, "\t\t\t\t\t\t\t\t\t\t\t",
1158                         single->modinst->name);
1159         } else if ((c->type > MOD_SINGLE) && (c->type <= MOD_POLICY)) {
1160                 modgroup *g = mod_callabletogroup(c);
1161                 modcallable *p;
1162                 DEBUG("%.*s%s {", indent, "\t\t\t\t\t\t\t\t\t\t\t",
1163                       unlang_keyword[c->type]);
1164                 for(p = g->children;p;p = p->next)
1165                         dump_mc(p, indent+1);
1166         } /* else ignore it for now */
1167
1168         for(i = 0; i<RLM_MODULE_NUMCODES; ++i) {
1169                 DEBUG("%.*s%s = %s", indent+1, "\t\t\t\t\t\t\t\t\t\t\t",
1170                       fr_int2str(mod_rcode_table, i, "<invalid>"),
1171                       action2str(c->actions[i]));
1172         }
1173
1174         DEBUG("%.*s}", indent, "\t\t\t\t\t\t\t\t\t\t\t");
1175 }
1176
1177 static void dump_tree(rlm_components_t comp, modcallable *c)
1178 {
1179         DEBUG("[%s]", comp2str[comp]);
1180         dump_mc(c, 0);
1181 }
1182 #else
1183 #define dump_tree(a, b)
1184 #endif
1185
1186 /* These are the default actions. For each component, the group{} block
1187  * behaves like the code from the old module_*() function. redundant{}
1188  * are based on my guesses of what they will be used for. --Pac. */
1189 static const int
1190 defaultactions[MOD_COUNT][GROUPTYPE_COUNT][RLM_MODULE_NUMCODES] =
1191 {
1192         /* authenticate */
1193         {
1194                 /* group */
1195                 {
1196                         MOD_ACTION_RETURN,      /* reject   */
1197                         1,                      /* fail     */
1198                         MOD_ACTION_RETURN,      /* ok       */
1199                         MOD_ACTION_RETURN,      /* handled  */
1200                         1,                      /* invalid  */
1201                         MOD_ACTION_RETURN,      /* userlock */
1202                         MOD_ACTION_RETURN,      /* notfound */
1203                         1,                      /* noop     */
1204                         1                       /* updated  */
1205                 },
1206                 /* redundant */
1207                 {
1208                         MOD_ACTION_RETURN,      /* reject   */
1209                         1,                      /* fail     */
1210                         MOD_ACTION_RETURN,      /* ok       */
1211                         MOD_ACTION_RETURN,      /* handled  */
1212                         MOD_ACTION_RETURN,      /* invalid  */
1213                         MOD_ACTION_RETURN,      /* userlock */
1214                         MOD_ACTION_RETURN,      /* notfound */
1215                         MOD_ACTION_RETURN,      /* noop     */
1216                         MOD_ACTION_RETURN       /* updated  */
1217                 }
1218         },
1219         /* authorize */
1220         {
1221                 /* group */
1222                 {
1223                         MOD_ACTION_RETURN,      /* reject   */
1224                         MOD_ACTION_RETURN,      /* fail     */
1225                         3,                      /* ok       */
1226                         MOD_ACTION_RETURN,      /* handled  */
1227                         MOD_ACTION_RETURN,      /* invalid  */
1228                         MOD_ACTION_RETURN,      /* userlock */
1229                         1,                      /* notfound */
1230                         2,                      /* noop     */
1231                         4                       /* updated  */
1232                 },
1233                 /* redundant */
1234                 {
1235                         MOD_ACTION_RETURN,      /* reject   */
1236                         1,                      /* fail     */
1237                         MOD_ACTION_RETURN,      /* ok       */
1238                         MOD_ACTION_RETURN,      /* handled  */
1239                         MOD_ACTION_RETURN,      /* invalid  */
1240                         MOD_ACTION_RETURN,      /* userlock */
1241                         MOD_ACTION_RETURN,      /* notfound */
1242                         MOD_ACTION_RETURN,      /* noop     */
1243                         MOD_ACTION_RETURN       /* updated  */
1244                 }
1245         },
1246         /* preacct */
1247         {
1248                 /* group */
1249                 {
1250                         MOD_ACTION_RETURN,      /* reject   */
1251                         MOD_ACTION_RETURN,      /* fail     */
1252                         2,                      /* ok       */
1253                         MOD_ACTION_RETURN,      /* handled  */
1254                         MOD_ACTION_RETURN,      /* invalid  */
1255                         MOD_ACTION_RETURN,      /* userlock */
1256                         MOD_ACTION_RETURN,      /* notfound */
1257                         1,                      /* noop     */
1258                         3                       /* updated  */
1259                 },
1260                 /* redundant */
1261                 {
1262                         MOD_ACTION_RETURN,      /* reject   */
1263                         1,                      /* fail     */
1264                         MOD_ACTION_RETURN,      /* ok       */
1265                         MOD_ACTION_RETURN,      /* handled  */
1266                         MOD_ACTION_RETURN,      /* invalid  */
1267                         MOD_ACTION_RETURN,      /* userlock */
1268                         MOD_ACTION_RETURN,      /* notfound */
1269                         MOD_ACTION_RETURN,      /* noop     */
1270                         MOD_ACTION_RETURN       /* updated  */
1271                 }
1272         },
1273         /* accounting */
1274         {
1275                 /* group */
1276                 {
1277                         MOD_ACTION_RETURN,      /* reject   */
1278                         MOD_ACTION_RETURN,      /* fail     */
1279                         2,                      /* ok       */
1280                         MOD_ACTION_RETURN,      /* handled  */
1281                         MOD_ACTION_RETURN,      /* invalid  */
1282                         MOD_ACTION_RETURN,      /* userlock */
1283                         MOD_ACTION_RETURN,      /* notfound */
1284                         1,                      /* noop     */
1285                         3                       /* updated  */
1286                 },
1287                 /* redundant */
1288                 {
1289                         1,                      /* reject   */
1290                         1,                      /* fail     */
1291                         MOD_ACTION_RETURN,      /* ok       */
1292                         MOD_ACTION_RETURN,      /* handled  */
1293                         1,                      /* invalid  */
1294                         1,                      /* userlock */
1295                         1,                      /* notfound */
1296                         2,                      /* noop     */
1297                         4                       /* updated  */
1298                 }
1299         },
1300         /* checksimul */
1301         {
1302                 /* group */
1303                 {
1304                         MOD_ACTION_RETURN,      /* reject   */
1305                         1,                      /* fail     */
1306                         MOD_ACTION_RETURN,      /* ok       */
1307                         MOD_ACTION_RETURN,      /* handled  */
1308                         MOD_ACTION_RETURN,      /* invalid  */
1309                         MOD_ACTION_RETURN,      /* userlock */
1310                         MOD_ACTION_RETURN,      /* notfound */
1311                         MOD_ACTION_RETURN,      /* noop     */
1312                         MOD_ACTION_RETURN       /* updated  */
1313                 },
1314                 /* redundant */
1315                 {
1316                         MOD_ACTION_RETURN,      /* reject   */
1317                         1,                      /* fail     */
1318                         MOD_ACTION_RETURN,      /* ok       */
1319                         MOD_ACTION_RETURN,      /* handled  */
1320                         MOD_ACTION_RETURN,      /* invalid  */
1321                         MOD_ACTION_RETURN,      /* userlock */
1322                         MOD_ACTION_RETURN,      /* notfound */
1323                         MOD_ACTION_RETURN,      /* noop     */
1324                         MOD_ACTION_RETURN       /* updated  */
1325                 }
1326         },
1327         /* pre-proxy */
1328         {
1329                 /* group */
1330                 {
1331                         MOD_ACTION_RETURN,      /* reject   */
1332                         MOD_ACTION_RETURN,      /* fail     */
1333                         3,                      /* ok       */
1334                         MOD_ACTION_RETURN,      /* handled  */
1335                         MOD_ACTION_RETURN,      /* invalid  */
1336                         MOD_ACTION_RETURN,      /* userlock */
1337                         1,                      /* notfound */
1338                         2,                      /* noop     */
1339                         4                       /* updated  */
1340                 },
1341                 /* redundant */
1342                 {
1343                         MOD_ACTION_RETURN,      /* reject   */
1344                         1,                      /* fail     */
1345                         MOD_ACTION_RETURN,      /* ok       */
1346                         MOD_ACTION_RETURN,      /* handled  */
1347                         MOD_ACTION_RETURN,      /* invalid  */
1348                         MOD_ACTION_RETURN,      /* userlock */
1349                         MOD_ACTION_RETURN,      /* notfound */
1350                         MOD_ACTION_RETURN,      /* noop     */
1351                         MOD_ACTION_RETURN       /* updated  */
1352                 }
1353         },
1354         /* post-proxy */
1355         {
1356                 /* group */
1357                 {
1358                         MOD_ACTION_RETURN,      /* reject   */
1359                         MOD_ACTION_RETURN,      /* fail     */
1360                         3,                      /* ok       */
1361                         MOD_ACTION_RETURN,      /* handled  */
1362                         MOD_ACTION_RETURN,      /* invalid  */
1363                         MOD_ACTION_RETURN,      /* userlock */
1364                         1,                      /* notfound */
1365                         2,                      /* noop     */
1366                         4                       /* updated  */
1367                 },
1368                 /* redundant */
1369                 {
1370                         MOD_ACTION_RETURN,      /* reject   */
1371                         1,                      /* fail     */
1372                         MOD_ACTION_RETURN,      /* ok       */
1373                         MOD_ACTION_RETURN,      /* handled  */
1374                         MOD_ACTION_RETURN,      /* invalid  */
1375                         MOD_ACTION_RETURN,      /* userlock */
1376                         MOD_ACTION_RETURN,      /* notfound */
1377                         MOD_ACTION_RETURN,      /* noop     */
1378                         MOD_ACTION_RETURN       /* updated  */
1379                 }
1380         },
1381         /* post-auth */
1382         {
1383                 /* group */
1384                 {
1385                         MOD_ACTION_RETURN,      /* reject   */
1386                         MOD_ACTION_RETURN,      /* fail     */
1387                         3,                      /* ok       */
1388                         MOD_ACTION_RETURN,      /* handled  */
1389                         MOD_ACTION_RETURN,      /* invalid  */
1390                         MOD_ACTION_RETURN,      /* userlock */
1391                         1,                      /* notfound */
1392                         2,                      /* noop     */
1393                         4                       /* updated  */
1394                 },
1395                 /* redundant */
1396                 {
1397                         MOD_ACTION_RETURN,      /* reject   */
1398                         1,                      /* fail     */
1399                         MOD_ACTION_RETURN,      /* ok       */
1400                         MOD_ACTION_RETURN,      /* handled  */
1401                         MOD_ACTION_RETURN,      /* invalid  */
1402                         MOD_ACTION_RETURN,      /* userlock */
1403                         MOD_ACTION_RETURN,      /* notfound */
1404                         MOD_ACTION_RETURN,      /* noop     */
1405                         MOD_ACTION_RETURN       /* updated  */
1406                 }
1407         }
1408 #ifdef WITH_COA
1409         ,
1410         /* recv-coa */
1411         {
1412                 /* group */
1413                 {
1414                         MOD_ACTION_RETURN,      /* reject   */
1415                         MOD_ACTION_RETURN,      /* fail     */
1416                         3,                      /* ok       */
1417                         MOD_ACTION_RETURN,      /* handled  */
1418                         MOD_ACTION_RETURN,      /* invalid  */
1419                         MOD_ACTION_RETURN,      /* userlock */
1420                         1,                      /* notfound */
1421                         2,                      /* noop     */
1422                         4                       /* updated  */
1423                 },
1424                 /* redundant */
1425                 {
1426                         MOD_ACTION_RETURN,      /* reject   */
1427                         1,                      /* fail     */
1428                         MOD_ACTION_RETURN,      /* ok       */
1429                         MOD_ACTION_RETURN,      /* handled  */
1430                         MOD_ACTION_RETURN,      /* invalid  */
1431                         MOD_ACTION_RETURN,      /* userlock */
1432                         MOD_ACTION_RETURN,      /* notfound */
1433                         MOD_ACTION_RETURN,      /* noop     */
1434                         MOD_ACTION_RETURN       /* updated  */
1435                 }
1436         },
1437         /* send-coa */
1438         {
1439                 /* group */
1440                 {
1441                         MOD_ACTION_RETURN,      /* reject   */
1442                         MOD_ACTION_RETURN,      /* fail     */
1443                         3,                      /* ok       */
1444                         MOD_ACTION_RETURN,      /* handled  */
1445                         MOD_ACTION_RETURN,      /* invalid  */
1446                         MOD_ACTION_RETURN,      /* userlock */
1447                         1,                      /* notfound */
1448                         2,                      /* noop     */
1449                         4                       /* updated  */
1450                 },
1451                 /* redundant */
1452                 {
1453                         MOD_ACTION_RETURN,      /* reject   */
1454                         1,                      /* fail     */
1455                         MOD_ACTION_RETURN,      /* ok       */
1456                         MOD_ACTION_RETURN,      /* handled  */
1457                         MOD_ACTION_RETURN,      /* invalid  */
1458                         MOD_ACTION_RETURN,      /* userlock */
1459                         MOD_ACTION_RETURN,      /* notfound */
1460                         MOD_ACTION_RETURN,      /* noop     */
1461                         MOD_ACTION_RETURN       /* updated  */
1462                 }
1463         }
1464 #endif
1465 };
1466
1467 static const int authtype_actions[GROUPTYPE_COUNT][RLM_MODULE_NUMCODES] =
1468 {
1469         /* group */
1470         {
1471                 MOD_ACTION_RETURN,      /* reject   */
1472                 MOD_ACTION_RETURN,      /* fail     */
1473                 4,                      /* ok       */
1474                 MOD_ACTION_RETURN,      /* handled  */
1475                 MOD_ACTION_RETURN,      /* invalid  */
1476                 MOD_ACTION_RETURN,      /* userlock */
1477                 1,                      /* notfound */
1478                 2,                      /* noop     */
1479                 3                       /* updated  */
1480         },
1481         /* redundant */
1482         {
1483                 MOD_ACTION_RETURN,      /* reject   */
1484                 1,                      /* fail     */
1485                 MOD_ACTION_RETURN,      /* ok       */
1486                 MOD_ACTION_RETURN,      /* handled  */
1487                 MOD_ACTION_RETURN,      /* invalid  */
1488                 MOD_ACTION_RETURN,      /* userlock */
1489                 MOD_ACTION_RETURN,      /* notfound */
1490                 MOD_ACTION_RETURN,      /* noop     */
1491                 MOD_ACTION_RETURN       /* updated  */
1492         }
1493 };
1494
1495 /** Validate and fixup a map that's part of an update section.
1496  *
1497  * @param map to validate.
1498  * @param ctx data to pass to fixup function (currently unused).
1499  * @return 0 if valid else -1.
1500  */
1501 int modcall_fixup_update(vp_map_t *map, UNUSED void *ctx)
1502 {
1503         CONF_PAIR *cp = cf_item_to_pair(map->ci);
1504
1505         /*
1506          *      Anal-retentive checks.
1507          */
1508         if (DEBUG_ENABLED3) {
1509                 if ((map->lhs->type == TMPL_TYPE_ATTR) && (map->lhs->name[0] != '&')) {
1510                         WARN("%s[%d]: Please change attribute reference to '&%s %s ...'",
1511                              cf_pair_filename(cp), cf_pair_lineno(cp),
1512                              map->lhs->name, fr_int2str(fr_tokens, map->op, "<INVALID>"));
1513                 }
1514
1515                 if ((map->rhs->type == TMPL_TYPE_ATTR) && (map->rhs->name[0] != '&')) {
1516                         WARN("%s[%d]: Please change attribute reference to '... %s &%s'",
1517                              cf_pair_filename(cp), cf_pair_lineno(cp),
1518                              fr_int2str(fr_tokens, map->op, "<INVALID>"), map->rhs->name);
1519                 }
1520         }
1521
1522         /*
1523          *      Values used by unary operators should be literal ANY
1524          *
1525          *      We then free the template and alloc a NULL one instead.
1526          */
1527         if (map->op == T_OP_CMP_FALSE) {
1528                 if ((map->rhs->type != TMPL_TYPE_LITERAL) || (strcmp(map->rhs->name, "ANY") != 0)) {
1529                         WARN("%s[%d] Wildcard deletion MUST use '!* ANY'",
1530                              cf_pair_filename(cp), cf_pair_lineno(cp));
1531                 }
1532
1533                 TALLOC_FREE(map->rhs);
1534
1535                 map->rhs = tmpl_alloc(map, TMPL_TYPE_NULL, NULL, 0);
1536         }
1537
1538         /*
1539          *      Lots of sanity checks for insane people...
1540          */
1541
1542         /*
1543          *      What exactly where you expecting to happen here?
1544          */
1545         if ((map->lhs->type == TMPL_TYPE_ATTR) &&
1546             (map->rhs->type == TMPL_TYPE_LIST)) {
1547                 cf_log_err(map->ci, "Can't copy list into an attribute");
1548                 return -1;
1549         }
1550
1551         /*
1552          *      Depending on the attribute type, some operators are disallowed.
1553          */
1554         if ((map->lhs->type == TMPL_TYPE_ATTR) && (!fr_assignment_op[map->op] && !fr_equality_op[map->op])) {
1555                 cf_log_err(map->ci, "Invalid operator \"%s\" in update section.  "
1556                            "Only assignment or filter operators are allowed",
1557                            fr_int2str(fr_tokens, map->op, "<INVALID>"));
1558                 return -1;
1559         }
1560
1561         if (map->lhs->type == TMPL_TYPE_LIST) {
1562                 /*
1563                  *      Can't copy an xlat expansion or literal into a list,
1564                  *      we don't know what type of attribute we'd need
1565                  *      to create.
1566                  *
1567                  *      The only exception is where were using a unary
1568                  *      operator like !*.
1569                  */
1570                 if (map->op != T_OP_CMP_FALSE) switch (map->rhs->type) {
1571                 case TMPL_TYPE_XLAT:
1572                 case TMPL_TYPE_LITERAL:
1573                         cf_log_err(map->ci, "Can't copy value into list (we don't know which attribute to create)");
1574                         return -1;
1575
1576                 default:
1577                         break;
1578                 }
1579
1580                 /*
1581                  *      Only += and :=, and !* operators are supported
1582                  *      for lists.
1583                  */
1584                 switch (map->op) {
1585                 case T_OP_CMP_FALSE:
1586                         break;
1587
1588                 case T_OP_ADD:
1589                         if ((map->rhs->type != TMPL_TYPE_LIST) &&
1590                             (map->rhs->type != TMPL_TYPE_EXEC)) {
1591                                 cf_log_err(map->ci, "Invalid source for list assignment '%s += ...'", map->lhs->name);
1592                                 return -1;
1593                         }
1594                         break;
1595
1596                 case T_OP_SET:
1597                         if (map->rhs->type == TMPL_TYPE_EXEC) {
1598                                 WARN("%s[%d]: Please change ':=' to '=' for list assignment",
1599                                      cf_pair_filename(cp), cf_pair_lineno(cp));
1600                         }
1601
1602                         if (map->rhs->type != TMPL_TYPE_LIST) {
1603                                 cf_log_err(map->ci, "Invalid source for list assignment '%s := ...'", map->lhs->name);
1604                                 return -1;
1605                         }
1606                         break;
1607
1608                 case T_OP_EQ:
1609                         if (map->rhs->type != TMPL_TYPE_EXEC) {
1610                                 cf_log_err(map->ci, "Invalid source for list assignment '%s = ...'", map->lhs->name);
1611                                 return -1;
1612                         }
1613                         break;
1614
1615                 default:
1616                         cf_log_err(map->ci, "Operator \"%s\" not allowed for list assignment",
1617                                    fr_int2str(fr_tokens, map->op, "<INVALID>"));
1618                         return -1;
1619                 }
1620         }
1621
1622         /*
1623          *      If the map has a unary operator there's no further
1624          *      processing we need to, as RHS is unused.
1625          */
1626         if (map->op == T_OP_CMP_FALSE) return 0;
1627
1628         /*
1629          *      If LHS is an attribute, and RHS is a literal, we can
1630          *      preparse the information into a TMPL_TYPE_DATA.
1631          *
1632          *      Unless it's a unary operator in which case we
1633          *      ignore map->rhs.
1634          */
1635         if ((map->lhs->type == TMPL_TYPE_ATTR) && (map->rhs->type == TMPL_TYPE_LITERAL)) {
1636                 /*
1637                  *      It's a literal string, just copy it.
1638                  *      Don't escape anything.
1639                  */
1640                 if (!cf_new_escape &&
1641                     (map->lhs->tmpl_da->type == PW_TYPE_STRING) &&
1642                     (cf_pair_value_type(cp) == T_SINGLE_QUOTED_STRING)) {
1643                         tmpl_cast_in_place_str(map->rhs);
1644
1645                 } else {
1646                         /*
1647                          *      RHS is hex, try to parse it as
1648                          *      type-specific data.
1649                          */
1650                         if (map->lhs->auto_converted &&
1651                             (map->rhs->name[0] == '0') && (map->rhs->name[1] == 'x') &&
1652                             (map->rhs->len > 2) && ((map->rhs->len & 0x01) == 0)) {
1653                                 vp_tmpl_t *vpt = map->rhs;
1654                                 map->rhs = NULL;
1655
1656                                 if (!map_cast_from_hex(map, T_BARE_WORD, vpt->name)) {
1657                                         map->rhs = vpt;
1658                                         cf_log_err(map->ci, "%s", fr_strerror());
1659                                         return -1;
1660                                 }
1661                                 talloc_free(vpt);
1662
1663                         } else if (tmpl_cast_in_place(map->rhs, map->lhs->tmpl_da->type, map->lhs->tmpl_da) < 0) {
1664                                 cf_log_err(map->ci, "%s", fr_strerror());
1665                                 return -1;
1666                         }
1667
1668                         /*
1669                          *      Fixup LHS da if it doesn't match the type
1670                          *      of the RHS.
1671                          */
1672                         if (map->lhs->tmpl_da->type != map->rhs->tmpl_data_type) {
1673                                 DICT_ATTR const *da;
1674
1675                                 da = dict_attrbytype(map->lhs->tmpl_da->attr, map->lhs->tmpl_da->vendor,
1676                                                      map->rhs->tmpl_data_type);
1677                                 if (!da) {
1678                                         fr_strerror_printf("Cannot find %s variant of attribute \"%s\"",
1679                                                            fr_int2str(dict_attr_types, map->rhs->tmpl_data_type,
1680                                                            "<INVALID>"), map->lhs->tmpl_da->name);
1681                                         return -1;
1682                                 }
1683                                 map->lhs->tmpl_da = da;
1684                         }
1685                 }
1686         } /* else we can't precompile the data */
1687
1688         return 0;
1689 }
1690
1691
1692 #ifdef WITH_UNLANG
1693 static modcallable *do_compile_modupdate(modcallable *parent, rlm_components_t component,
1694                                          CONF_SECTION *cs, char const *name2)
1695 {
1696         int rcode;
1697         modgroup *g;
1698         modcallable *csingle;
1699
1700         vp_map_t *head;
1701
1702         /*
1703          *      This looks at cs->name2 to determine which list to update
1704          */
1705         rcode = map_afrom_cs(&head, cs, PAIR_LIST_REQUEST, PAIR_LIST_REQUEST, modcall_fixup_update, NULL, 128);
1706         if (rcode < 0) return NULL; /* message already printed */
1707         if (!head) {
1708                 cf_log_err_cs(cs, "'update' sections cannot be empty");
1709                 return NULL;
1710         }
1711
1712         g = talloc_zero(parent, modgroup);
1713         csingle = mod_grouptocallable(g);
1714
1715         csingle->parent = parent;
1716         csingle->next = NULL;
1717
1718         if (name2) {
1719                 csingle->name = name2;
1720         } else {
1721                 csingle->name = "";
1722         }
1723         csingle->type = MOD_UPDATE;
1724         csingle->method = component;
1725
1726         memcpy(csingle->actions, defaultactions[component][GROUPTYPE_SIMPLE],
1727                sizeof(csingle->actions));
1728
1729         g->grouptype = GROUPTYPE_SIMPLE;
1730         g->children = NULL;
1731         g->cs = cs;
1732         g->map = talloc_steal(g, head);
1733
1734         return csingle;
1735 }
1736
1737
1738 static modcallable *do_compile_modswitch (modcallable *parent, rlm_components_t component, CONF_SECTION *cs)
1739 {
1740         CONF_ITEM *ci;
1741         FR_TOKEN type;
1742         char const *name2;
1743         bool had_seen_default = false;
1744         modcallable *csingle;
1745         modgroup *g;
1746         ssize_t slen;
1747         vp_tmpl_t *vpt;
1748
1749         name2 = cf_section_name2(cs);
1750         if (!name2) {
1751                 cf_log_err_cs(cs, "You must specify a variable to switch over for 'switch'");
1752                 return NULL;
1753         }
1754
1755         if (!cf_item_find_next(cs, NULL)) {
1756                 cf_log_err_cs(cs, "'switch' statements cannot be empty");
1757                 return NULL;
1758         }
1759
1760         /*
1761          *      Create the template.  If we fail, AND it's a bare word
1762          *      with &Foo-Bar, it MAY be an attribute defined by a
1763          *      module.  Allow it for now.  The pass2 checks below
1764          *      will fix it up.
1765          */
1766         type = cf_section_name2_type(cs);
1767         slen = tmpl_afrom_str(cs, &vpt, name2, strlen(name2), type, REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
1768         if ((slen < 0) && ((type != T_BARE_WORD) || (name2[0] != '&'))) {
1769                 char *spaces, *text;
1770
1771                 fr_canonicalize_error(cs, &spaces, &text, slen, fr_strerror());
1772
1773                 cf_log_err_cs(cs, "Syntax error");
1774                 cf_log_err_cs(cs, "%s", name2);
1775                 cf_log_err_cs(cs, "%s^ %s", spaces, text);
1776
1777                 talloc_free(spaces);
1778                 talloc_free(text);
1779
1780                 return NULL;
1781         }
1782
1783         /*
1784          *      Otherwise a NULL vpt may refer to an attribute defined
1785          *      by a module.  That is checked in pass 2.
1786          */
1787
1788         if (vpt->type == TMPL_TYPE_LIST) {
1789                 cf_log_err_cs(cs, "Syntax error: Cannot switch over list '%s'", name2);
1790                 return NULL;
1791         }
1792
1793
1794         /*
1795          *      Walk through the children of the switch section,
1796          *      ensuring that they're all 'case' statements
1797          */
1798         for (ci = cf_item_find_next(cs, NULL);
1799              ci != NULL;
1800              ci = cf_item_find_next(cs, ci)) {
1801                 CONF_SECTION *subcs;
1802                 char const *name1;
1803
1804                 if (!cf_item_is_section(ci)) {
1805                         if (!cf_item_is_pair(ci)) continue;
1806
1807                         cf_log_err(ci, "\"switch\" sections can only have \"case\" subsections");
1808                         talloc_free(vpt);
1809                         return NULL;
1810                 }
1811
1812                 subcs = cf_item_to_section(ci); /* can't return NULL */
1813                 name1 = cf_section_name1(subcs);
1814
1815                 if (strcmp(name1, "case") != 0) {
1816                         cf_log_err(ci, "\"switch\" sections can only have \"case\" subsections");
1817                         talloc_free(vpt);
1818                         return NULL;
1819                 }
1820
1821                 name2 = cf_section_name2(subcs);
1822                 if (!name2) {
1823                         if (!had_seen_default) {
1824                                 had_seen_default = true;
1825                                 continue;
1826                         }
1827
1828                         cf_log_err(ci, "Cannot have two 'default' case statements");
1829                         talloc_free(vpt);
1830                         return NULL;
1831                 }
1832         }
1833
1834         csingle = do_compile_modgroup(parent, component, cs,
1835                                       GROUPTYPE_SIMPLE,
1836                                       GROUPTYPE_SIMPLE,
1837                                       MOD_SWITCH);
1838         if (!csingle) {
1839                 talloc_free(vpt);
1840                 return NULL;
1841         }
1842
1843         g = mod_callabletogroup(csingle);
1844         g->vpt = talloc_steal(g, vpt);
1845
1846         return csingle;
1847 }
1848
1849 static modcallable *do_compile_modcase(modcallable *parent, rlm_components_t component, CONF_SECTION *cs)
1850 {
1851         int i;
1852         char const *name2;
1853         modcallable *csingle;
1854         modgroup *g;
1855         vp_tmpl_t *vpt;
1856
1857         if (!parent || (parent->type != MOD_SWITCH)) {
1858                 cf_log_err_cs(cs, "\"case\" statements may only appear within a \"switch\" section");
1859                 return NULL;
1860         }
1861
1862         /*
1863          *      case THING means "match THING"
1864          *      case       means "match anything"
1865          */
1866         name2 = cf_section_name2(cs);
1867         if (name2) {
1868                 ssize_t slen;
1869                 FR_TOKEN type;
1870
1871                 type = cf_section_name2_type(cs);
1872
1873                 slen = tmpl_afrom_str(cs, &vpt, name2, strlen(name2), type, REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
1874                 if ((slen < 0) && ((type != T_BARE_WORD) || (name2[0] != '&'))) {
1875                         char *spaces, *text;
1876
1877                         fr_canonicalize_error(cs, &spaces, &text, slen, fr_strerror());
1878
1879                         cf_log_err_cs(cs, "Syntax error");
1880                         cf_log_err_cs(cs, "%s", name2);
1881                         cf_log_err_cs(cs, "%s^ %s", spaces, text);
1882
1883                         talloc_free(spaces);
1884                         talloc_free(text);
1885
1886                         return NULL;
1887                 }
1888
1889                 if (vpt->type == TMPL_TYPE_LIST) {
1890                         cf_log_err_cs(cs, "Syntax error: Cannot match list '%s'", name2);
1891                         return NULL;
1892                 }
1893
1894                 /*
1895                  *      Otherwise a NULL vpt may refer to an attribute defined
1896                  *      by a module.  That is checked in pass 2.
1897                  */
1898
1899         } else {
1900                 vpt = NULL;
1901         }
1902
1903         csingle = do_compile_modgroup(parent, component, cs,
1904                                       GROUPTYPE_SIMPLE,
1905                                       GROUPTYPE_SIMPLE,
1906                                       MOD_CASE);
1907         if (!csingle) {
1908                 talloc_free(vpt);
1909                 return NULL;
1910         }
1911
1912         /*
1913          *      The interpretor expects this to be NULL for the
1914          *      default case.  do_compile_modgroup sets it to name2,
1915          *      unless name2 is NULL, in which case it sets it to name1.
1916          */
1917         csingle->name = name2;
1918
1919         g = mod_callabletogroup(csingle);
1920         g->vpt = talloc_steal(g, vpt);
1921
1922         /*
1923          *      Set all of it's codes to return, so that
1924          *      when we pick a 'case' statement, we don't
1925          *      fall through to processing the next one.
1926          */
1927         for (i = 0; i < RLM_MODULE_NUMCODES; i++) {
1928                 csingle->actions[i] = MOD_ACTION_RETURN;
1929         }
1930
1931         return csingle;
1932 }
1933
1934 static modcallable *do_compile_modforeach(modcallable *parent,
1935                                           rlm_components_t component, CONF_SECTION *cs)
1936 {
1937         FR_TOKEN type;
1938         char const *name2;
1939         modcallable *csingle;
1940         modgroup *g;
1941         ssize_t slen;
1942         vp_tmpl_t *vpt;
1943
1944         name2 = cf_section_name2(cs);
1945         if (!name2) {
1946                 cf_log_err_cs(cs,
1947                            "You must specify an attribute to loop over in 'foreach'");
1948                 return NULL;
1949         }
1950
1951         if (!cf_item_find_next(cs, NULL)) {
1952                 cf_log_err_cs(cs, "'foreach' blocks cannot be empty");
1953                 return NULL;
1954         }
1955
1956         /*
1957          *      Create the template.  If we fail, AND it's a bare word
1958          *      with &Foo-Bar, it MAY be an attribute defined by a
1959          *      module.  Allow it for now.  The pass2 checks below
1960          *      will fix it up.
1961          */
1962         type = cf_section_name2_type(cs);
1963         slen = tmpl_afrom_str(cs, &vpt, name2, strlen(name2), type, REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
1964         if ((slen < 0) && ((type != T_BARE_WORD) || (name2[0] != '&'))) {
1965                 char *spaces, *text;
1966
1967                 fr_canonicalize_error(cs, &spaces, &text, slen, fr_strerror());
1968
1969                 cf_log_err_cs(cs, "Syntax error");
1970                 cf_log_err_cs(cs, "%s", name2);
1971                 cf_log_err_cs(cs, "%s^ %s", spaces, text);
1972
1973                 talloc_free(spaces);
1974                 talloc_free(text);
1975
1976                 return NULL;
1977         }
1978
1979         /*
1980          *      If we don't have a negative return code, we must have a vpt
1981          *      (mostly to quiet coverity).
1982          */
1983         rad_assert(vpt);
1984
1985         if ((vpt->type != TMPL_TYPE_ATTR) && (vpt->type != TMPL_TYPE_LIST)) {
1986                 cf_log_err_cs(cs, "MUST use attribute or list reference in 'foreach'");
1987                 return NULL;
1988         }
1989
1990         /*
1991          *      Fix up the template to iterate over all instances of
1992          *      the attribute. In a perfect consistent world, users would do
1993          *      foreach &attr[*], but that's taking the consistency thing a bit far.
1994          */
1995         vpt->tmpl_num = NUM_ALL;
1996
1997         csingle = do_compile_modgroup(parent, component, cs,
1998                                       GROUPTYPE_SIMPLE, GROUPTYPE_SIMPLE,
1999                                       MOD_FOREACH);
2000
2001         if (!csingle) {
2002                 talloc_free(vpt);
2003                 return NULL;
2004         }
2005
2006         g = mod_callabletogroup(csingle);
2007         g->vpt = vpt;
2008
2009         return csingle;
2010 }
2011
2012 static modcallable *do_compile_modbreak(modcallable *parent,
2013                                         rlm_components_t component, CONF_ITEM const *ci)
2014 {
2015         CONF_SECTION const *cs = NULL;
2016
2017         for (cs = cf_item_parent(ci);
2018              cs != NULL;
2019              cs = cf_item_parent(cf_section_to_item(cs))) {
2020                 if (strcmp(cf_section_name1(cs), "foreach") == 0) {
2021                         break;
2022                 }
2023         }
2024
2025         if (!cs) {
2026                 cf_log_err(ci, "'break' can only be used in a 'foreach' section");
2027                 return NULL;
2028         }
2029
2030         return do_compile_modgroup(parent, component, NULL,
2031                                    GROUPTYPE_SIMPLE, GROUPTYPE_SIMPLE,
2032                                    MOD_BREAK);
2033 }
2034 #endif
2035
2036 static modcallable *do_compile_modserver(modcallable *parent,
2037                                          rlm_components_t component, CONF_ITEM *ci,
2038                                          char const *name,
2039                                          CONF_SECTION *cs,
2040                                          char const *server)
2041 {
2042         modcallable *csingle;
2043         CONF_SECTION *subcs;
2044         modref *mr;
2045
2046         subcs = cf_section_sub_find_name2(cs, comp2str[component], NULL);
2047         if (!subcs) {
2048                 cf_log_err(ci, "Server %s has no %s section",
2049                            server, comp2str[component]);
2050                 return NULL;
2051         }
2052
2053         mr = talloc_zero(parent, modref);
2054
2055         csingle = mod_reftocallable(mr);
2056         csingle->parent = parent;
2057         csingle->next = NULL;
2058         csingle->name = name;
2059         csingle->type = MOD_REFERENCE;
2060         csingle->method = component;
2061
2062         memcpy(csingle->actions, defaultactions[component][GROUPTYPE_SIMPLE],
2063                sizeof(csingle->actions));
2064
2065         mr->ref_name = strdup(server);
2066         mr->ref_cs = cs;
2067
2068         return csingle;
2069 }
2070
2071 static modcallable *do_compile_modxlat(modcallable *parent,
2072                                        rlm_components_t component, char const *fmt)
2073 {
2074         modcallable *csingle;
2075         modxlat *mx;
2076
2077         mx = talloc_zero(parent, modxlat);
2078
2079         csingle = mod_xlattocallable(mx);
2080         csingle->parent = parent;
2081         csingle->next = NULL;
2082         csingle->name = "expand";
2083         csingle->type = MOD_XLAT;
2084         csingle->method = component;
2085
2086         memcpy(csingle->actions, defaultactions[component][GROUPTYPE_SIMPLE],
2087                sizeof(csingle->actions));
2088
2089         mx->xlat_name = strdup(fmt);
2090         if (fmt[0] != '%') {
2091                 char *p;
2092                 mx->exec = true;
2093
2094                 strcpy(mx->xlat_name, fmt + 1);
2095                 p = strrchr(mx->xlat_name, '`');
2096                 if (p) *p = '\0';
2097         }
2098
2099         return csingle;
2100 }
2101
2102 /*
2103  *      redundant, etc. can refer to modules or groups, but not much else.
2104  */
2105 static int all_children_are_modules(CONF_SECTION *cs, char const *name)
2106 {
2107         CONF_ITEM *ci;
2108
2109         for (ci=cf_item_find_next(cs, NULL);
2110              ci != NULL;
2111              ci=cf_item_find_next(cs, ci)) {
2112                 /*
2113                  *      If we're a redundant, etc. group, then the
2114                  *      intention is to call modules, rather than
2115                  *      processing logic.  These checks aren't
2116                  *      *strictly* necessary, but they keep the users
2117                  *      from doing crazy things.
2118                  */
2119                 if (cf_item_is_section(ci)) {
2120                         CONF_SECTION *subcs = cf_item_to_section(ci);
2121                         char const *name1 = cf_section_name1(subcs);
2122
2123                         if ((strcmp(name1, "if") == 0) ||
2124                             (strcmp(name1, "else") == 0) ||
2125                             (strcmp(name1, "elsif") == 0) ||
2126                             (strcmp(name1, "update") == 0) ||
2127                             (strcmp(name1, "switch") == 0) ||
2128                             (strcmp(name1, "case") == 0)) {
2129                                 cf_log_err(ci, "%s sections cannot contain a \"%s\" statement",
2130                                        name, name1);
2131                                 return 0;
2132                         }
2133                         continue;
2134                 }
2135
2136                 if (cf_item_is_pair(ci)) {
2137                         CONF_PAIR *cp = cf_item_to_pair(ci);
2138                         if (cf_pair_value(cp) != NULL) {
2139                                 cf_log_err(ci,
2140                                            "Entry with no value is invalid");
2141                                 return 0;
2142                         }
2143                 }
2144         }
2145
2146         return 1;
2147 }
2148
2149
2150 /*
2151  *      Load a named module from "instantiate" or "policy".
2152  *
2153  *      If it's "foo.method", look for "foo", and return "method" as the method
2154  *      we wish to use, instead of the input component.
2155  */
2156 static CONF_SECTION *virtual_module_find_cs(char const *virtual_name, char const *method_name,
2157                                             rlm_components_t *pcomponent)
2158 {
2159         CONF_SECTION *cs, *subcs;
2160         rlm_components_t method = *pcomponent;
2161         char buffer[256];
2162
2163         /*
2164          *      Turn the method name into a method enum.
2165          */
2166         if (method_name) {
2167                 rlm_components_t i;
2168
2169                 for (i = MOD_AUTHENTICATE; i < MOD_COUNT; i++) {
2170                         if (strcmp(comp2str[i], method_name) == 0) break;
2171                 }
2172
2173                 if (i == MOD_COUNT) return NULL;
2174
2175                 method = i;
2176         }
2177
2178         /*
2179          *      Look for "foo" in the "instantiate" section.  If we
2180          *      find it, AND there's no method name, we've found the
2181          *      right thing.
2182          *
2183          *      Return it to the caller, with the updated method.
2184          */
2185         cs = cf_section_find("instantiate");
2186         if (cs) {
2187                 /*
2188                  *      Found "foo".  Load it as "foo", or "foo.method".
2189                  */
2190                 subcs = cf_section_sub_find_name2(cs, NULL, virtual_name);
2191                 if (subcs) {
2192                         *pcomponent = method;
2193                         return subcs;
2194                 }
2195         }
2196
2197         /*
2198          *      Look for it in "policy".
2199          *
2200          *      If there's no policy section, we can't do anything else.
2201          */
2202         cs = cf_section_find("policy");
2203         if (!cs) return NULL;
2204
2205         /*
2206          *      "foo.authorize" means "load policy "foo" as method "authorize".
2207          *
2208          *      And bail out if there's no policy "foo".
2209          */
2210         if (method_name) {
2211                 subcs = cf_section_sub_find_name2(cs, NULL, virtual_name);
2212                 if (subcs) *pcomponent = method;
2213
2214                 return subcs;
2215         }
2216
2217         /*
2218          *      "foo" means "look for foo.component" first, to allow
2219          *      method overrides.  If that's not found, just look for
2220          *      a policy "foo".
2221          *
2222          */
2223         snprintf(buffer, sizeof(buffer), "%s.%s",
2224                  virtual_name, comp2str[method]);
2225         subcs = cf_section_sub_find_name2(cs, NULL, buffer);
2226         if (subcs) return subcs;
2227
2228         return cf_section_sub_find_name2(cs, NULL, virtual_name);
2229 }
2230
2231
2232 /*
2233  *      Compile one entry of a module call.
2234  */
2235 static modcallable *do_compile_modsingle(modcallable *parent,
2236                                          rlm_components_t component, CONF_ITEM *ci,
2237                                          int grouptype,
2238                                          char const **modname)
2239 {
2240         char const *modrefname, *p;
2241         modsingle *single;
2242         modcallable *csingle;
2243         module_instance_t *this;
2244         CONF_SECTION *cs, *subcs, *modules;
2245         CONF_SECTION *loop;
2246         char const *realname;
2247         rlm_components_t method = component;
2248
2249         if (cf_item_is_section(ci)) {
2250                 char const *name2;
2251
2252                 cs = cf_item_to_section(ci);
2253                 modrefname = cf_section_name1(cs);
2254                 name2 = cf_section_name2(cs);
2255                 if (!name2) name2 = "";
2256
2257                 /*
2258                  *      group{}, redundant{}, or append{} may appear
2259                  *      where a single module instance was expected.
2260                  *      In that case, we hand it off to
2261                  *      compile_modgroup
2262                  */
2263                 if (strcmp(modrefname, "group") == 0) {
2264                         *modname = name2;
2265                         return do_compile_modgroup(parent, component, cs,
2266                                                    GROUPTYPE_SIMPLE,
2267                                                    grouptype, MOD_GROUP);
2268
2269                 } else if (strcmp(modrefname, "redundant") == 0) {
2270                         *modname = name2;
2271
2272                         if (!all_children_are_modules(cs, modrefname)) {
2273                                 return NULL;
2274                         }
2275
2276                         return do_compile_modgroup(parent, component, cs,
2277                                                    GROUPTYPE_REDUNDANT,
2278                                                    grouptype, MOD_GROUP);
2279
2280                 } else if (strcmp(modrefname, "load-balance") == 0) {
2281                         *modname = name2;
2282
2283                         if (!all_children_are_modules(cs, modrefname)) {
2284                                 return NULL;
2285                         }
2286
2287                         return do_compile_modgroup(parent, component, cs,
2288                                                    GROUPTYPE_SIMPLE,
2289                                                    grouptype, MOD_LOAD_BALANCE);
2290
2291                 } else if (strcmp(modrefname, "redundant-load-balance") == 0) {
2292                         *modname = name2;
2293
2294                         if (!all_children_are_modules(cs, modrefname)) {
2295                                 return NULL;
2296                         }
2297
2298                         return do_compile_modgroup(parent, component, cs,
2299                                                    GROUPTYPE_REDUNDANT,
2300                                                    grouptype, MOD_REDUNDANT_LOAD_BALANCE);
2301
2302 #ifdef WITH_UNLANG
2303                 } else  if (strcmp(modrefname, "if") == 0) {
2304                         if (!cf_section_name2(cs)) {
2305                                 cf_log_err(ci, "'if' without condition");
2306                                 return NULL;
2307                         }
2308
2309                         *modname = name2;
2310                         csingle= do_compile_modgroup(parent, component, cs,
2311                                                      GROUPTYPE_SIMPLE,
2312                                                      grouptype, MOD_IF);
2313                         if (!csingle) return NULL;
2314                         *modname = name2;
2315
2316                         return csingle;
2317
2318                 } else  if (strcmp(modrefname, "elsif") == 0) {
2319                         if (parent &&
2320                             ((parent->type == MOD_LOAD_BALANCE) ||
2321                              (parent->type == MOD_REDUNDANT_LOAD_BALANCE))) {
2322                                 cf_log_err(ci, "'elsif' cannot be used in this section");
2323                                 return NULL;
2324                         }
2325
2326                         if (!cf_section_name2(cs)) {
2327                                 cf_log_err(ci, "'elsif' without condition");
2328                                 return NULL;
2329                         }
2330
2331                         *modname = name2;
2332                         return do_compile_modgroup(parent, component, cs,
2333                                                    GROUPTYPE_SIMPLE,
2334                                                    grouptype, MOD_ELSIF);
2335
2336                 } else  if (strcmp(modrefname, "else") == 0) {
2337                         if (parent &&
2338                             ((parent->type == MOD_LOAD_BALANCE) ||
2339                              (parent->type == MOD_REDUNDANT_LOAD_BALANCE))) {
2340                                 cf_log_err(ci, "'else' cannot be used in this section section");
2341                                 return NULL;
2342                         }
2343
2344                         if (cf_section_name2(cs)) {
2345                                 cf_log_err(ci, "Cannot have conditions on 'else'");
2346                                 return NULL;
2347                         }
2348
2349                         *modname = name2;
2350                         return  do_compile_modgroup(parent, component, cs,
2351                                                     GROUPTYPE_SIMPLE,
2352                                                     grouptype, MOD_ELSE);
2353
2354                 } else  if (strcmp(modrefname, "update") == 0) {
2355                         *modname = name2;
2356
2357                         return do_compile_modupdate(parent, component, cs,
2358                                                     name2);
2359
2360                 } else  if (strcmp(modrefname, "switch") == 0) {
2361                         *modname = name2;
2362
2363                         return do_compile_modswitch (parent, component, cs);
2364
2365                 } else  if (strcmp(modrefname, "case") == 0) {
2366                         *modname = name2;
2367
2368                         return do_compile_modcase(parent, component, cs);
2369
2370                 } else  if (strcmp(modrefname, "foreach") == 0) {
2371                         *modname = name2;
2372
2373                         return do_compile_modforeach(parent, component, cs);
2374
2375 #endif
2376                 } /* else it's something like sql { fail = 1 ...} */
2377
2378         } else if (!cf_item_is_pair(ci)) { /* CONF_DATA or some such */
2379                 return NULL;
2380
2381                 /*
2382                  *      Else it's a module reference, with updated return
2383                  *      codes.
2384                  */
2385         } else {
2386                 CONF_PAIR *cp = cf_item_to_pair(ci);
2387                 modrefname = cf_pair_attr(cp);
2388
2389                 /*
2390                  *      Actions (ok = 1), etc. are orthogonal to just
2391                  *      about everything else.
2392                  */
2393                 if (cf_pair_value(cp) != NULL) {
2394                         cf_log_err(ci, "Entry is not a reference to a module");
2395                         return NULL;
2396                 }
2397
2398                 /*
2399                  *      In-place xlat's via %{...}.
2400                  *
2401                  *      This should really be removed from the server.
2402                  */
2403                 if (((modrefname[0] == '%') && (modrefname[1] == '{')) ||
2404                     (modrefname[0] == '`')) {
2405                         return do_compile_modxlat(parent, component,
2406                                                   modrefname);
2407                 }
2408         }
2409
2410 #ifdef WITH_UNLANG
2411         /*
2412          *      These can't be over-ridden.
2413          */
2414         if (strcmp(modrefname, "break") == 0) {
2415                 if (!cf_item_is_pair(ci)) {
2416                         cf_log_err(ci, "Invalid use of 'break' as section name.");
2417                         return NULL;
2418                 }
2419
2420                 return do_compile_modbreak(parent, component, ci);
2421         }
2422
2423         if (strcmp(modrefname, "return") == 0) {
2424                 if (!cf_item_is_pair(ci)) {
2425                         cf_log_err(ci, "Invalid use of 'return' as section name.");
2426                         return NULL;
2427                 }
2428
2429                 return do_compile_modgroup(parent, component, NULL,
2430                                            GROUPTYPE_SIMPLE, GROUPTYPE_SIMPLE,
2431                                            MOD_RETURN);
2432         }
2433 #endif
2434
2435         /*
2436          *      Run a virtual server.  This is really terrible and
2437          *      should be deleted.
2438          */
2439         if (strncmp(modrefname, "server[", 7) == 0) {
2440                 char buffer[256];
2441
2442                 if (!cf_item_is_pair(ci)) {
2443                         cf_log_err(ci, "Invalid syntax");
2444                         return NULL;
2445                 }
2446
2447                 strlcpy(buffer, modrefname + 7, sizeof(buffer));
2448                 p = strrchr(buffer, ']');
2449                 if (!p || p[1] != '\0' || (p == buffer)) {
2450                         cf_log_err(ci, "Invalid server reference in \"%s\".", modrefname);
2451                         return NULL;
2452                 }
2453
2454                 buffer[p - buffer] = '\0';
2455
2456                 cs = cf_section_sub_find_name2(NULL, "server", buffer);
2457                 if (!cs) {
2458                         cf_log_err(ci, "No such server \"%s\".", buffer);
2459                         return NULL;
2460                 }
2461
2462                 /*
2463                  *      Ignore stupid attempts to over-ride the return
2464                  *      code.
2465                  */
2466                 return do_compile_modserver(parent, component, ci,
2467                                             modrefname, cs, buffer);
2468         }
2469
2470         /*
2471          *      We now have a name.  It can be one of two forms.  A
2472          *      bare module name, or a section named for the module,
2473          *      with over-rides for the return codes.
2474          *
2475          *      The name can refer to a real module, in the "modules"
2476          *      section.  In that case, the name will be either the
2477          *      first or second name of the sub-section of "modules".
2478          *
2479          *      Or, the name can refer to a policy, in the "policy"
2480          *      section.  In that case, the name will be first name of
2481          *      the sub-section of "policy".  Unless it's a "redudant"
2482          *      block...
2483          *
2484          *      Or, the name can refer to a "module.method", in which
2485          *      case we're calling a different method than normal for
2486          *      this section.
2487          *
2488          *      Or, the name can refer to a virtual module, in the
2489          *      "instantiate" section.  In that case, the name will be
2490          *      the first of the sub-section of "instantiate".  Unless
2491          *      it's a "redudant" block...
2492          *
2493          *      We try these in sequence, from the bottom up.  This is
2494          *      so that things in "instantiate" and "policy" can
2495          *      over-ride calls to real modules.
2496          */
2497
2498
2499         /*
2500          *      Try:
2501          *
2502          *      instantiate { ... name { ...} ... }
2503          *      instantiate { ... name.method { ...} ... }
2504          *      policy { ... name { .. } .. }
2505          *      policy { ... name.method { .. } .. }
2506          *
2507          *      The only difference between things in "instantiate"
2508          *      and "policy" is that "instantiate" will cause modules
2509          *      to be instantiated in a particular order.
2510          */
2511         subcs = NULL;
2512         p = strrchr(modrefname, '.');
2513         if (!p) {
2514                 subcs = virtual_module_find_cs(modrefname, NULL, &method);
2515         } else {
2516                 char buffer[256];
2517
2518                 strlcpy(buffer, modrefname, sizeof(buffer));
2519                 buffer[p - modrefname] = '\0';
2520
2521                 subcs = virtual_module_find_cs(buffer, buffer + (p - modrefname) + 1, &method);
2522         }
2523
2524         /*
2525          *      Check that we're not creating a loop.  We may
2526          *      be compiling an "sql" module reference inside
2527          *      of an "sql" policy.  If so, we allow the
2528          *      second "sql" to refer to the module.
2529          */
2530         for (loop = cf_item_parent(ci);
2531              loop && subcs;
2532              loop = cf_item_parent(cf_section_to_item(loop))) {
2533                 if (loop == subcs) {
2534                         subcs = NULL;
2535                 }
2536         }
2537
2538         /*
2539          *      We've found the relevant entry.  It MUST be a
2540          *      sub-section.
2541          *
2542          *      However, it can be a "redundant" block, or just a
2543          *      section name.
2544          */
2545         if (subcs) {
2546                 /*
2547                  *      modules.c takes care of ensuring that this is:
2548                  *
2549                  *      group foo { ...
2550                  *      load-balance foo { ...
2551                  *      redundant foo { ...
2552                  *      redundant-load-balance foo { ...
2553                  *
2554                  *      We can just recurs to compile the section as
2555                  *      if it was found here.
2556                  */
2557                 if (cf_section_name2(subcs)) {
2558                         csingle = do_compile_modsingle(parent,
2559                                                        method,
2560                                                        cf_section_to_item(subcs),
2561                                                        grouptype,
2562                                                        modname);
2563                 } else {
2564                         /*
2565                          *      We have:
2566                          *
2567                          *      foo { ...
2568                          *
2569                          *      So we compile it like it was:
2570                          *
2571                          *      group foo { ...
2572                          */
2573                         csingle = do_compile_modgroup(parent,
2574                                                       method,
2575                                                       subcs,
2576                                                       GROUPTYPE_SIMPLE,
2577                                                       grouptype, MOD_GROUP);
2578                 }
2579
2580                 /*
2581                  *      Return the compiled thing if we can.
2582                  */
2583                 if (!csingle) return NULL;
2584                 if (cf_item_is_pair(ci)) return csingle;
2585
2586                 /*
2587                  *      Else we have a reference to a policy, and that reference
2588                  *      over-rides the return codes for the policy!
2589                  */
2590                 goto action_override;
2591         }
2592
2593         /*
2594          *      Not a virtual module.  It must be a real module.
2595          */
2596         modules = cf_section_find("modules");
2597         this = NULL;
2598         realname = modrefname;
2599
2600         if (modules) {
2601                 /*
2602                  *      Try to load the optional module.
2603                  */
2604                 if (realname[0] == '-') realname++;
2605
2606                 /*
2607                  *      As of v3, the "modules" section contains
2608                  *      modules we use.  Configuration for other
2609                  *      modules belongs in raddb/mods-available/,
2610                  *      which isn't loaded into the "modules" section.
2611                  */
2612                 this = module_instantiate_method(modules, realname, &method);
2613                 if (this) goto allocate_csingle;
2614
2615                 /*
2616                  *      We were asked to MAYBE load it and it
2617                  *      doesn't exist.  Return a soft error.
2618                  */
2619                 if (realname != modrefname) {
2620                         *modname = modrefname;
2621                         return NULL;
2622                 }
2623         }
2624
2625         /*
2626          *      Can't de-reference it to anything.  Ugh.
2627          */
2628         *modname = NULL;
2629         cf_log_err(ci, "Failed to find \"%s\" as a module or policy.", modrefname);
2630         cf_log_err(ci, "Please verify that the configuration exists in %s/mods-enabled/%s.", get_radius_dir(), modrefname);
2631         return NULL;
2632
2633         /*
2634          *      We know it's all OK, allocate the structures, and fill
2635          *      them in.
2636          */
2637 allocate_csingle:
2638         /*
2639          *      Check if the module in question has the necessary
2640          *      component.
2641          */
2642         if (!this->entry->module->methods[method]) {
2643                 cf_log_err(ci, "\"%s\" modules aren't allowed in '%s' sections -- they have no such method.", this->entry->module->name,
2644                            comp2str[method]);
2645                 return NULL;
2646         }
2647
2648         single = talloc_zero(parent, modsingle);
2649         single->modinst = this;
2650         *modname = this->entry->module->name;
2651
2652         csingle = mod_singletocallable(single);
2653         csingle->parent = parent;
2654         csingle->next = NULL;
2655         if (!parent || (component != MOD_AUTHENTICATE)) {
2656                 memcpy(csingle->actions, defaultactions[component][grouptype],
2657                        sizeof csingle->actions);
2658         } else { /* inside Auth-Type has different rules */
2659                 memcpy(csingle->actions, authtype_actions[grouptype],
2660                        sizeof csingle->actions);
2661         }
2662         rad_assert(modrefname != NULL);
2663         csingle->name = realname;
2664         csingle->type = MOD_SINGLE;
2665         csingle->method = method;
2666
2667 action_override:
2668         /*
2669          *      Over-ride the default return codes of the module.
2670          */
2671         if (cf_item_is_section(ci)) {
2672                 CONF_ITEM *csi;
2673
2674                 cs = cf_item_to_section(ci);
2675                 for (csi=cf_item_find_next(cs, NULL);
2676                      csi != NULL;
2677                      csi=cf_item_find_next(cs, csi)) {
2678
2679                         if (cf_item_is_section(csi)) {
2680                                 cf_log_err(csi, "Subsection of module instance call not allowed");
2681                                 talloc_free(csingle);
2682                                 return NULL;
2683                         }
2684
2685                         if (!cf_item_is_pair(csi)) continue;
2686
2687                         if (!compile_action(csingle, cf_item_to_pair(csi))) {
2688                                 talloc_free(csingle);
2689                                 return NULL;
2690                         }
2691                 }
2692         }
2693
2694         return csingle;
2695 }
2696
2697 modcallable *compile_modsingle(TALLOC_CTX *ctx,
2698                                modcallable **parent,
2699                                rlm_components_t component, CONF_ITEM *ci,
2700                                char const **modname)
2701 {
2702         modcallable *ret;
2703
2704         if (!*parent) {
2705                 modcallable *c;
2706                 modgroup *g;
2707                 CONF_SECTION *parentcs;
2708
2709                 g = talloc_zero(ctx, modgroup);
2710                 memset(g, 0, sizeof(*g));
2711                 g->grouptype = GROUPTYPE_SIMPLE;
2712                 c = mod_grouptocallable(g);
2713                 c->next = NULL;
2714                 memcpy(c->actions,
2715                        defaultactions[component][GROUPTYPE_SIMPLE],
2716                        sizeof(c->actions));
2717
2718                 parentcs = cf_item_parent(ci);
2719                 c->name = cf_section_name2(parentcs);
2720                 if (!c->name) {
2721                         c->name = cf_section_name1(parentcs);
2722                 }
2723
2724                 c->type = MOD_GROUP;
2725                 c->method = component;
2726                 g->children = NULL;
2727
2728                 *parent = mod_grouptocallable(g);
2729         }
2730
2731         ret = do_compile_modsingle(*parent, component, ci,
2732                                    GROUPTYPE_SIMPLE,
2733                                    modname);
2734         dump_tree(component, ret);
2735         return ret;
2736 }
2737
2738
2739 /*
2740  *      Internal compile group code.
2741  */
2742 static modcallable *do_compile_modgroup(modcallable *parent,
2743                                         rlm_components_t component, CONF_SECTION *cs,
2744                                         int grouptype, int parentgrouptype, int mod_type)
2745 {
2746         int i;
2747         modgroup *g;
2748         modcallable *c;
2749         CONF_ITEM *ci;
2750
2751         g = talloc_zero(parent, modgroup);
2752         g->grouptype = grouptype;
2753         g->children = NULL;
2754         g->cs = cs;
2755
2756         c = mod_grouptocallable(g);
2757         c->parent = parent;
2758         c->type = mod_type;
2759         c->next = NULL;
2760         memset(c->actions, 0, sizeof(c->actions));
2761
2762         if (!cs) {              /* only for "break" and "return" */
2763                 c->name = "";
2764                 goto set_codes;
2765         }
2766
2767         /*
2768          *      Remember the name for printing, etc.
2769          *
2770          *      FIXME: We may also want to put the names into a
2771          *      rbtree, so that groups can reference each other...
2772          */
2773         c->name = cf_section_name2(cs);
2774         if (!c->name) {
2775                 c->name = cf_section_name1(cs);
2776                 if ((strcmp(c->name, "group") == 0) ||
2777                     (strcmp(c->name, "redundant") == 0)) {
2778                         c->name = "";
2779                 } else if (c->type == MOD_GROUP) {
2780                         c->type = MOD_POLICY;
2781                 }
2782         }
2783
2784 #ifdef WITH_UNLANG
2785         /*
2786          *      Do load-time optimizations
2787          */
2788         if ((c->type == MOD_IF) || (c->type == MOD_ELSIF) || (c->type == MOD_ELSE)) {
2789                 modgroup *f, *p;
2790
2791                 rad_assert(parent != NULL);
2792
2793                 if (c->type == MOD_IF) {
2794                         g->cond = cf_data_find(g->cs, "if");
2795                         rad_assert(g->cond != NULL);
2796
2797                 check_if:
2798                         if (g->cond->type == COND_TYPE_FALSE) {
2799                                 INFO(" # Skipping contents of '%s' as it is always 'false' -- %s:%d",
2800                                      unlang_keyword[g->mc.type],
2801                                      cf_section_filename(g->cs), cf_section_lineno(g->cs));
2802                                 goto set_codes;
2803                         }
2804
2805                 } else if (c->type == MOD_ELSIF) {
2806
2807                         g->cond = cf_data_find(g->cs, "if");
2808                         rad_assert(g->cond != NULL);
2809
2810                         rad_assert(parent != NULL);
2811                         p = mod_callabletogroup(parent);
2812
2813                         rad_assert(p->tail != NULL);
2814
2815                         /*
2816                          *      We're in the process of compiling the
2817                          *      section, so the parent's tail is the
2818                          *      previous "if" statement.
2819                          */
2820                         f = mod_callabletogroup(p->tail);
2821                         if ((f->mc.type != MOD_IF) &&
2822                             (f->mc.type != MOD_ELSIF)) {
2823                                 cf_log_err_cs(g->cs, "Invalid location for 'elsif'.  There is no preceding 'if' statement");
2824                                 talloc_free(g);
2825                                 return NULL;
2826                         }
2827
2828                         /*
2829                          *      If we took the previous condition, we
2830                          *      don't need to take this one.
2831                          *
2832                          *      We reset our condition to 'true', so
2833                          *      that subsequent sections can check
2834                          *      that they don't need to be executed.
2835                          */
2836                         if (f->cond->type == COND_TYPE_TRUE) {
2837                         skip_true:
2838                                 INFO(" # Skipping contents of '%s' as previous '%s' is always  'true' -- %s:%d",
2839                                      unlang_keyword[g->mc.type],
2840                                      unlang_keyword[f->mc.type],
2841                                      cf_section_filename(g->cs), cf_section_lineno(g->cs));
2842                                 g->cond = f->cond;
2843                                 goto set_codes;
2844                         }
2845                         goto check_if;
2846
2847                 } else {
2848                         rad_assert(c->type == MOD_ELSE);
2849
2850                         rad_assert(parent != NULL);
2851                         p = mod_callabletogroup(parent);
2852
2853                         rad_assert(p->tail != NULL);
2854
2855                         f = mod_callabletogroup(p->tail);
2856                         if ((f->mc.type != MOD_IF) &&
2857                             (f->mc.type != MOD_ELSIF)) {
2858                                 cf_log_err_cs(g->cs, "Invalid location for 'else'.  There is no preceding 'if' statement");
2859                                 talloc_free(g);
2860                                 return NULL;
2861                         }
2862
2863                         /*
2864                          *      If we took the previous condition, we
2865                          *      don't need to take this one.
2866                          */
2867                         if (f->cond->type == COND_TYPE_TRUE) goto skip_true;
2868                 }
2869
2870                 /*
2871                  *      Else we need to compile this section
2872                  */
2873         }
2874 #endif
2875
2876         /*
2877          *      Loop over the children of this group.
2878          */
2879         for (ci=cf_item_find_next(cs, NULL);
2880              ci != NULL;
2881              ci=cf_item_find_next(cs, ci)) {
2882
2883                 /*
2884                  *      Sections are references to other groups, or
2885                  *      to modules with updated return codes.
2886                  */
2887                 if (cf_item_is_section(ci)) {
2888                         char const *junk = NULL;
2889                         modcallable *single;
2890                         CONF_SECTION *subcs = cf_item_to_section(ci);
2891
2892                         single = do_compile_modsingle(c, component, ci,
2893                                                       grouptype, &junk);
2894                         if (!single) {
2895                                 cf_log_err(ci, "Failed to parse \"%s\" subsection.",
2896                                        cf_section_name1(subcs));
2897                                 talloc_free(c);
2898                                 return NULL;
2899                         }
2900                         add_child(g, single);
2901
2902                 } else if (!cf_item_is_pair(ci)) { /* CONF_DATA */
2903                         continue;
2904
2905                 } else {
2906                         char const *attr, *value;
2907                         CONF_PAIR *cp = cf_item_to_pair(ci);
2908
2909                         attr = cf_pair_attr(cp);
2910                         value = cf_pair_value(cp);
2911
2912                         /*
2913                          *      A CONF_PAIR is either a module
2914                          *      instance with no actions
2915                          *      specified ...
2916                          */
2917                         if (!value) {
2918                                 modcallable *single;
2919                                 char const *junk = NULL;
2920
2921                                 single = do_compile_modsingle(c,
2922                                                               component,
2923                                                               ci,
2924                                                               grouptype,
2925                                                               &junk);
2926                                 if (!single) {
2927                                         if (cf_item_is_pair(ci) &&
2928                                             cf_pair_attr(cf_item_to_pair(ci))[0] == '-') {
2929                                                 continue;
2930                                         }
2931
2932                                         cf_log_err(ci,
2933                                                    "Failed to parse \"%s\" entry.",
2934                                                    attr);
2935                                         talloc_free(c);
2936                                         return NULL;
2937                                 }
2938                                 add_child(g, single);
2939
2940                                 /*
2941                                  *      Or a module instance with action.
2942                                  */
2943                         } else if (!compile_action(c, cp)) {
2944                                 talloc_free(c);
2945                                 return NULL;
2946                         } /* else it worked */
2947                 }
2948         }
2949
2950 set_codes:
2951         /*
2952          *      Set the default actions, if they haven't already been
2953          *      set.
2954          */
2955         for (i = 0; i < RLM_MODULE_NUMCODES; i++) {
2956                 if (!c->actions[i]) {
2957                         if (!parent || (component != MOD_AUTHENTICATE)) {
2958                                 c->actions[i] = defaultactions[component][parentgrouptype][i];
2959                         } else { /* inside Auth-Type has different rules */
2960                                 c->actions[i] = authtype_actions[parentgrouptype][i];
2961                         }
2962                 }
2963         }
2964
2965         switch (c->type) {
2966         default:
2967                 break;
2968
2969         case MOD_GROUP:
2970                 if (grouptype != GROUPTYPE_REDUNDANT) break;
2971                 /* FALL-THROUGH */
2972
2973         case MOD_LOAD_BALANCE:
2974         case MOD_REDUNDANT_LOAD_BALANCE:
2975                 if (!g->children) {
2976                         cf_log_err_cs(g->cs, "%s sections cannot be empty",
2977                                       cf_section_name1(g->cs));
2978                         talloc_free(c);
2979                         return NULL;
2980                 }
2981         }
2982
2983         /*
2984          *      FIXME: If there are no children, return NULL?
2985          */
2986         return mod_grouptocallable(g);
2987 }
2988
2989 modcallable *compile_modgroup(modcallable *parent,
2990                               rlm_components_t component, CONF_SECTION *cs)
2991 {
2992         modcallable *ret = do_compile_modgroup(parent, component, cs,
2993                                                GROUPTYPE_SIMPLE,
2994                                                GROUPTYPE_SIMPLE, MOD_GROUP);
2995
2996         if (rad_debug_lvl > 3) {
2997                 modcall_debug(ret, 2);
2998         }
2999
3000         return ret;
3001 }
3002
3003 void add_to_modcallable(modcallable *parent, modcallable *this)
3004 {
3005         modgroup *g;
3006
3007         rad_assert(this != NULL);
3008         rad_assert(parent != NULL);
3009
3010         g = mod_callabletogroup(parent);
3011
3012         add_child(g, this);
3013 }
3014
3015
3016 #ifdef WITH_UNLANG
3017 static bool pass2_xlat_compile(CONF_ITEM const *ci, vp_tmpl_t **pvpt, bool convert,
3018                                DICT_ATTR const *da)
3019 {
3020         ssize_t slen;
3021         char *fmt;
3022         char const *error;
3023         xlat_exp_t *head;
3024         vp_tmpl_t *vpt;
3025
3026         vpt = *pvpt;
3027
3028         rad_assert(vpt->type == TMPL_TYPE_XLAT);
3029
3030         fmt = talloc_typed_strdup(vpt, vpt->name);
3031         slen = xlat_tokenize(vpt, fmt, &head, &error);
3032
3033         if (slen < 0) {
3034                 char *spaces, *text;
3035
3036                 fr_canonicalize_error(vpt, &spaces, &text, slen, vpt->name);
3037
3038                 cf_log_err(ci, "Failed parsing expanded string:");
3039                 cf_log_err(ci, "%s", text);
3040                 cf_log_err(ci, "%s^ %s", spaces, error);
3041
3042                 talloc_free(spaces);
3043                 talloc_free(text);
3044                 return false;
3045         }
3046
3047         /*
3048          *      Convert %{Attribute-Name} to &Attribute-Name
3049          */
3050         if (convert) {
3051                 vp_tmpl_t *attr;
3052
3053                 attr = xlat_to_tmpl_attr(talloc_parent(vpt), head);
3054                 if (attr) {
3055                         /*
3056                          *      If it's a virtual attribute, leave it
3057                          *      alone.
3058                          */
3059                         if (attr->tmpl_da->flags.virtual) {
3060                                 talloc_free(attr);
3061                                 return true;
3062                         }
3063
3064                         /*
3065                          *      If the attribute is of incompatible
3066                          *      type, leave it alone.
3067                          */
3068                         if (da && (da->type != attr->tmpl_da->type)) {
3069                                 talloc_free(attr);
3070                                 return true;
3071                         }
3072
3073                         if (cf_item_is_pair(ci)) {
3074                                 CONF_PAIR *cp = cf_item_to_pair(ci);
3075
3076                                 WARN("%s[%d]: Please change \"%%{%s}\" to &%s",
3077                                        cf_pair_filename(cp), cf_pair_lineno(cp),
3078                                        attr->name, attr->name);
3079                         } else {
3080                                 CONF_SECTION *cs = cf_item_to_section(ci);
3081
3082                                 WARN("%s[%d]: Please change \"%%{%s}\" to &%s",
3083                                        cf_section_filename(cs), cf_section_lineno(cs),
3084                                        attr->name, attr->name);
3085                         }
3086                         TALLOC_FREE(*pvpt);
3087                         *pvpt = attr;
3088                         return true;
3089                 }
3090         }
3091
3092         /*
3093          *      Re-write it to be a pre-parsed XLAT structure.
3094          */
3095         vpt->type = TMPL_TYPE_XLAT_STRUCT;
3096         vpt->tmpl_xlat = head;
3097
3098         return true;
3099 }
3100
3101
3102 #ifdef HAVE_REGEX
3103 static bool pass2_regex_compile(CONF_ITEM const *ci, vp_tmpl_t *vpt)
3104 {
3105         ssize_t slen;
3106         regex_t *preg;
3107
3108         rad_assert(vpt->type == TMPL_TYPE_REGEX);
3109
3110         /*
3111          *      It's a dynamic expansion.  We can't expand the string,
3112          *      but we can pre-parse it as an xlat struct.  In that
3113          *      case, we convert it to a pre-compiled XLAT.
3114          *
3115          *      This is a little more complicated than it needs to be
3116          *      because radius_evaluate_map() keys off of the src
3117          *      template type, instead of the operators.  And, the
3118          *      pass2_xlat_compile() function expects to get passed an
3119          *      XLAT instead of a REGEX.
3120          */
3121         if (strchr(vpt->name, '%')) {
3122                 vpt->type = TMPL_TYPE_XLAT;
3123                 return pass2_xlat_compile(ci, &vpt, false, NULL);
3124         }
3125
3126         slen = regex_compile(vpt, &preg, vpt->name, vpt->len,
3127                              vpt->tmpl_iflag, vpt->tmpl_mflag, true, false);
3128         if (slen <= 0) {
3129                 char *spaces, *text;
3130
3131                 fr_canonicalize_error(vpt, &spaces, &text, slen, vpt->name);
3132
3133                 cf_log_err(ci, "Invalid regular expression:");
3134                 cf_log_err(ci, "%s", text);
3135                 cf_log_err(ci, "%s^ %s", spaces, fr_strerror());
3136
3137                 talloc_free(spaces);
3138                 talloc_free(text);
3139
3140                 return false;
3141         }
3142
3143         vpt->type = TMPL_TYPE_REGEX_STRUCT;
3144         vpt->tmpl_preg = preg;
3145
3146         return true;
3147 }
3148 #endif
3149
3150 static bool pass2_fixup_undefined(CONF_ITEM const *ci, vp_tmpl_t *vpt)
3151 {
3152         DICT_ATTR const *da;
3153
3154         rad_assert(vpt->type == TMPL_TYPE_ATTR_UNDEFINED);
3155
3156         da = dict_attrbyname(vpt->tmpl_unknown_name);
3157         if (!da) {
3158                 cf_log_err(ci, "Unknown attribute '%s'", vpt->tmpl_unknown_name);
3159                 return false;
3160         }
3161
3162         vpt->tmpl_da = da;
3163         vpt->type = TMPL_TYPE_ATTR;
3164         return true;
3165 }
3166
3167 static bool pass2_callback(void *ctx, fr_cond_t *c)
3168 {
3169         vp_map_t *map;
3170         vp_tmpl_t *vpt;
3171
3172         /*
3173          *      These don't get optimized.
3174          */
3175         if ((c->type == COND_TYPE_TRUE) ||
3176             (c->type == COND_TYPE_FALSE)) {
3177                 return true;
3178         }
3179
3180         /*
3181          *      Call children.
3182          */
3183         if (c->type == COND_TYPE_CHILD) return pass2_callback(ctx, c->data.child);
3184
3185         /*
3186          *      A few simple checks here.
3187          */
3188         if (c->type == COND_TYPE_EXISTS) {
3189                 if (c->data.vpt->type == TMPL_TYPE_XLAT) {
3190                         return pass2_xlat_compile(c->ci, &c->data.vpt, true, NULL);
3191                 }
3192
3193                 rad_assert(c->data.vpt->type != TMPL_TYPE_REGEX);
3194
3195                 /*
3196                  *      The existence check might have been &Foo-Bar,
3197                  *      where Foo-Bar is defined by a module.
3198                  */
3199                 if (c->pass2_fixup == PASS2_FIXUP_ATTR) {
3200                         if (!pass2_fixup_undefined(c->ci, c->data.vpt)) return false;
3201                         c->pass2_fixup = PASS2_FIXUP_NONE;
3202                 }
3203                 return true;
3204         }
3205
3206         /*
3207          *      And tons of complicated checks.
3208          */
3209         rad_assert(c->type == COND_TYPE_MAP);
3210
3211         map = c->data.map;      /* shorter */
3212
3213         /*
3214          *      Auth-Type := foo
3215          *
3216          *      Where "foo" is dynamically defined.
3217          */
3218         if (c->pass2_fixup == PASS2_FIXUP_TYPE) {
3219                 if (!dict_valbyname(map->lhs->tmpl_da->attr,
3220                                     map->lhs->tmpl_da->vendor,
3221                                     map->rhs->name)) {
3222                         cf_log_err(map->ci, "Invalid reference to non-existent %s %s { ... }",
3223                                    map->lhs->tmpl_da->name,
3224                                    map->rhs->name);
3225                         return false;
3226                 }
3227
3228                 /*
3229                  *      These guys can't have a paircompare fixup applied.
3230                  */
3231                 c->pass2_fixup = PASS2_FIXUP_NONE;
3232                 return true;
3233         }
3234
3235         if (c->pass2_fixup == PASS2_FIXUP_ATTR) {
3236                 if (map->lhs->type == TMPL_TYPE_ATTR_UNDEFINED) {
3237                         if (!pass2_fixup_undefined(map->ci, map->lhs)) return false;
3238                 }
3239
3240                 if (map->rhs->type == TMPL_TYPE_ATTR_UNDEFINED) {
3241                         if (!pass2_fixup_undefined(map->ci, map->rhs)) return false;
3242                 }
3243
3244                 c->pass2_fixup = PASS2_FIXUP_NONE;
3245         }
3246
3247         /*
3248          *      Just in case someone adds a new fixup later.
3249          */
3250         rad_assert((c->pass2_fixup == PASS2_FIXUP_NONE) ||
3251                    (c->pass2_fixup == PASS2_PAIRCOMPARE));
3252
3253         /*
3254          *      Precompile xlat's
3255          */
3256         if (map->lhs->type == TMPL_TYPE_XLAT) {
3257                 /*
3258                  *      Compile the LHS to an attribute reference only
3259                  *      if the RHS is a literal.
3260                  *
3261                  *      @todo v3.1: allow anything anywhere.
3262                  */
3263                 if (map->rhs->type != TMPL_TYPE_LITERAL) {
3264                         if (!pass2_xlat_compile(map->ci, &map->lhs, false, NULL)) {
3265                                 return false;
3266                         }
3267                 } else {
3268                         if (!pass2_xlat_compile(map->ci, &map->lhs, true, NULL)) {
3269                                 return false;
3270                         }
3271
3272                         /*
3273                          *      Attribute compared to a literal gets
3274                          *      the literal cast to the data type of
3275                          *      the attribute.
3276                          *
3277                          *      The code in parser.c did this for
3278                          *
3279                          *              &Attr == data
3280                          *
3281                          *      But now we've just converted "%{Attr}"
3282                          *      to &Attr, so we've got to do it again.
3283                          */
3284                         if ((map->lhs->type == TMPL_TYPE_ATTR) &&
3285                             (map->rhs->type == TMPL_TYPE_LITERAL)) {
3286                                 /*
3287                                  *      RHS is hex, try to parse it as
3288                                  *      type-specific data.
3289                                  */
3290                                 if (map->lhs->auto_converted &&
3291                                     (map->rhs->name[0] == '0') && (map->rhs->name[1] == 'x') &&
3292                                     (map->rhs->len > 2) && ((map->rhs->len & 0x01) == 0)) {
3293                                         vpt = map->rhs;
3294                                         map->rhs = NULL;
3295
3296                                         if (!map_cast_from_hex(map, T_BARE_WORD, vpt->name)) {
3297                                                 map->rhs = vpt;
3298                                                 cf_log_err(map->ci, "%s", fr_strerror());
3299                                                 return -1;
3300                                         }
3301                                         talloc_free(vpt);
3302
3303                                 } else if ((map->rhs->len > 0) ||
3304                                            (map->op != T_OP_CMP_EQ) ||
3305                                            (map->lhs->tmpl_da->type == PW_TYPE_STRING) ||
3306                                            (map->lhs->tmpl_da->type == PW_TYPE_OCTETS)) {
3307
3308                                         if (tmpl_cast_in_place(map->rhs, map->lhs->tmpl_da->type, map->lhs->tmpl_da) < 0) {
3309                                                 cf_log_err(map->ci, "Failed to parse data type %s from string: %s",
3310                                                            fr_int2str(dict_attr_types, map->lhs->tmpl_da->type, "<UNKNOWN>"),
3311                                                            map->rhs->name);
3312                                                 return false;
3313                                         } /* else the cast was successful */
3314
3315                                 } else {        /* RHS is empty, it's just a check for empty / non-empty string */
3316                                         vpt = talloc_steal(c, map->lhs);
3317                                         map->lhs = NULL;
3318                                         talloc_free(c->data.map);
3319
3320                                         /*
3321                                          *      "%{Foo}" == '' ---> !Foo
3322                                          *      "%{Foo}" != '' ---> Foo
3323                                          */
3324                                         c->type = COND_TYPE_EXISTS;
3325                                         c->data.vpt = vpt;
3326                                         c->negate = !c->negate;
3327
3328                                         WARN("%s[%d]: Please change (\"%%{%s}\" %s '') to %c&%s",
3329                                              cf_section_filename(cf_item_to_section(c->ci)),
3330                                              cf_section_lineno(cf_item_to_section(c->ci)),
3331                                              vpt->name, c->negate ? "==" : "!=",
3332                                              c->negate ? '!' : ' ', vpt->name);
3333
3334                                         /*
3335                                          *      No more RHS, so we can't do more optimizations
3336                                          */
3337                                         return true;
3338                                 }
3339                         }
3340                 }
3341         }
3342
3343         if (map->rhs->type == TMPL_TYPE_XLAT) {
3344                 /*
3345                  *      Convert the RHS to an attribute reference only
3346                  *      if the LHS is an attribute reference, AND is
3347                  *      of the same type as the RHS.
3348                  *
3349                  *      We can fix this when the code in evaluate.c
3350                  *      can handle strings on the LHS, and attributes
3351                  *      on the RHS.  For now, the code in parser.c
3352                  *      forbids this.
3353                  */
3354                 if (map->lhs->type == TMPL_TYPE_ATTR) {
3355                         DICT_ATTR const *da = c->cast;
3356
3357                         if (!c->cast) da = map->lhs->tmpl_da;
3358
3359                         if (!pass2_xlat_compile(map->ci, &map->rhs, true, da)) {
3360                                 return false;
3361                         }
3362
3363                 } else {
3364                         if (!pass2_xlat_compile(map->ci, &map->rhs, false, NULL)) {
3365                                 return false;
3366                         }
3367                 }
3368         }
3369
3370         /*
3371          *      Convert bare refs to %{Foreach-Variable-N}
3372          */
3373         if ((map->lhs->type == TMPL_TYPE_LITERAL) &&
3374             (strncmp(map->lhs->name, "Foreach-Variable-", 17) == 0)) {
3375                 char *fmt;
3376                 ssize_t slen;
3377
3378                 fmt = talloc_asprintf(map->lhs, "%%{%s}", map->lhs->name);
3379                 slen = tmpl_afrom_str(map, &vpt, fmt, talloc_array_length(fmt) - 1,
3380                                       T_DOUBLE_QUOTED_STRING, REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
3381                 if (slen < 0) {
3382                         char *spaces, *text;
3383
3384                         fr_canonicalize_error(map->ci, &spaces, &text, slen, fr_strerror());
3385
3386                         cf_log_err(map->ci, "Failed converting %s to xlat", map->lhs->name);
3387                         cf_log_err(map->ci, "%s", fmt);
3388                         cf_log_err(map->ci, "%s^ %s", spaces, text);
3389
3390                         talloc_free(spaces);
3391                         talloc_free(text);
3392                         talloc_free(fmt);
3393
3394                         return false;
3395                 }
3396                 talloc_free(map->lhs);
3397                 map->lhs = vpt;
3398         }
3399
3400 #ifdef HAVE_REGEX
3401         if (map->rhs->type == TMPL_TYPE_REGEX) {
3402                 if (!pass2_regex_compile(map->ci, map->rhs)) {
3403                         return false;
3404                 }
3405         }
3406         rad_assert(map->lhs->type != TMPL_TYPE_REGEX);
3407 #endif
3408
3409         /*
3410          *      Convert &Packet-Type to "%{Packet-Type}", because
3411          *      these attributes don't really exist.  The code to
3412          *      find an attribute reference doesn't work, but the
3413          *      xlat code does.
3414          */
3415         vpt = c->data.map->lhs;
3416         if ((vpt->type == TMPL_TYPE_ATTR) && vpt->tmpl_da->flags.virtual) {
3417                 if (!c->cast) c->cast = vpt->tmpl_da;
3418                 vpt->tmpl_xlat = xlat_from_tmpl_attr(vpt, vpt);
3419                 vpt->type = TMPL_TYPE_XLAT_STRUCT;
3420         }
3421
3422         /*
3423          *      @todo v3.1: do the same thing for the RHS...
3424          */
3425
3426         /*
3427          *      Only attributes can have a paircompare registered, and
3428          *      they can only be with the current REQUEST, and only
3429          *      with the request pairs.
3430          */
3431         if ((map->lhs->type != TMPL_TYPE_ATTR) ||
3432             (map->lhs->tmpl_request != REQUEST_CURRENT) ||
3433             (map->lhs->tmpl_list != PAIR_LIST_REQUEST)) {
3434                 return true;
3435         }
3436
3437         if (!radius_find_compare(map->lhs->tmpl_da)) return true;
3438
3439         if (map->rhs->type == TMPL_TYPE_ATTR) {
3440                 cf_log_err(map->ci, "Cannot compare virtual attribute %s to another attribute",
3441                            map->lhs->name);
3442                 return false;
3443         }
3444
3445         if (map->rhs->type == TMPL_TYPE_REGEX) {
3446                 cf_log_err(map->ci, "Cannot compare virtual attribute %s via a regex",
3447                            map->lhs->name);
3448                 return false;
3449         }
3450
3451         if (c->cast) {
3452                 cf_log_err(map->ci, "Cannot cast virtual attribute %s",
3453                            map->lhs->name);
3454                 return false;
3455         }
3456
3457         if (map->op != T_OP_CMP_EQ) {
3458                 cf_log_err(map->ci, "Must use '==' for comparisons with virtual attribute %s",
3459                            map->lhs->name);
3460                 return false;
3461         }
3462
3463         /*
3464          *      Mark it as requiring a paircompare() call, instead of
3465          *      fr_pair_cmp().
3466          */
3467         c->pass2_fixup = PASS2_PAIRCOMPARE;
3468
3469         return true;
3470 }
3471
3472
3473 /*
3474  *      Compile the RHS of update sections to xlat_exp_t
3475  */
3476 static bool modcall_pass2_update(modgroup *g)
3477 {
3478         vp_map_t *map;
3479
3480         for (map = g->map; map != NULL; map = map->next) {
3481                 if (map->rhs->type == TMPL_TYPE_XLAT) {
3482                         rad_assert(map->rhs->tmpl_xlat == NULL);
3483
3484                         /*
3485                          *      FIXME: compile to attribute && handle
3486                          *      the conversion in map_to_vp().
3487                          */
3488                         if (!pass2_xlat_compile(map->ci, &map->rhs, false, NULL)) {
3489                                 return false;
3490                         }
3491                 }
3492
3493                 rad_assert(map->rhs->type != TMPL_TYPE_REGEX);
3494
3495                 /*
3496                  *      Deal with undefined attributes now.
3497                  */
3498                 if (map->lhs->type == TMPL_TYPE_ATTR_UNDEFINED) {
3499                         if (!pass2_fixup_undefined(map->ci, map->lhs)) return false;
3500                 }
3501
3502                 if (map->rhs->type == TMPL_TYPE_ATTR_UNDEFINED) {
3503                         if (!pass2_fixup_undefined(map->ci, map->rhs)) return false;
3504                 }
3505         }
3506
3507         return true;
3508 }
3509 #endif
3510
3511 /*
3512  *      Do a second-stage pass on compiling the modules.
3513  */
3514 bool modcall_pass2(modcallable *mc)
3515 {
3516         ssize_t slen;
3517         char const *name2;
3518         modcallable *c;
3519         modgroup *g;
3520
3521         for (c = mc; c != NULL; c = c->next) {
3522                 switch (c->type) {
3523                 default:
3524                         rad_assert(0 == 1);
3525                         break;
3526
3527 #ifdef WITH_UNLANG
3528                 case MOD_UPDATE:
3529                         g = mod_callabletogroup(c);
3530                         if (g->done_pass2) goto do_next;
3531
3532                         name2 = cf_section_name2(g->cs);
3533                         if (!name2) {
3534                                 c->debug_name = unlang_keyword[c->type];
3535                         } else {
3536                                 c->debug_name = talloc_asprintf(c, "update %s", name2);
3537                         }
3538
3539                         if (!modcall_pass2_update(g)) {
3540                                 return false;
3541                         }
3542                         g->done_pass2 = true;
3543                         break;
3544
3545                 case MOD_XLAT:   /* @todo: pre-parse xlat's */
3546                 case MOD_REFERENCE:
3547                 case MOD_BREAK:
3548                 case MOD_RETURN:
3549 #endif
3550
3551                 case MOD_SINGLE:
3552                         c->debug_name = c->name;
3553                         break;  /* do nothing */
3554
3555 #ifdef WITH_UNLANG
3556                 case MOD_IF:
3557                 case MOD_ELSIF:
3558                         g = mod_callabletogroup(c);
3559                         if (g->done_pass2) goto do_next;
3560
3561                         name2 = cf_section_name2(g->cs);
3562                         c->debug_name = talloc_asprintf(c, "%s %s", unlang_keyword[c->type], name2);
3563
3564                         /*
3565                          *      The compilation code takes care of
3566                          *      simplifying 'true' and 'false'
3567                          *      conditions.  For others, we have to do
3568                          *      a second pass to parse && compile
3569                          *      xlats.
3570                          */
3571                         if (!((g->cond->type == COND_TYPE_TRUE) ||
3572                               (g->cond->type == COND_TYPE_FALSE))) {
3573                                 if (!fr_condition_walk(g->cond, pass2_callback, NULL)) {
3574                                         return false;
3575                                 }
3576                         }
3577
3578                         if (!modcall_pass2(g->children)) return false;
3579                         g->done_pass2 = true;
3580                         break;
3581 #endif
3582
3583 #ifdef WITH_UNLANG
3584                 case MOD_SWITCH:
3585                         g = mod_callabletogroup(c);
3586                         if (g->done_pass2) goto do_next;
3587
3588                         name2 = cf_section_name2(g->cs);
3589                         c->debug_name = talloc_asprintf(c, "%s %s", unlang_keyword[c->type], name2);
3590
3591                         /*
3592                          *      We had &Foo-Bar, where Foo-Bar is
3593                          *      defined by a module.
3594                          */
3595                         if (!g->vpt) {
3596                                 rad_assert(c->name != NULL);
3597                                 rad_assert(c->name[0] == '&');
3598                                 rad_assert(cf_section_name2_type(g->cs) == T_BARE_WORD);
3599
3600                                 slen = tmpl_afrom_str(g->cs, &g->vpt, c->name, strlen(c->name),
3601                                                       cf_section_name2_type(g->cs),
3602                                                       REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
3603                                 if (slen < 0) {
3604                                         char *spaces, *text;
3605
3606                                 parse_error:
3607                                         fr_canonicalize_error(g->cs, &spaces, &text, slen, fr_strerror());
3608
3609                                         cf_log_err_cs(g->cs, "Syntax error");
3610                                         cf_log_err_cs(g->cs, "%s", c->name);
3611                                         cf_log_err_cs(g->cs, "%s^ %s", spaces, text);
3612
3613                                         talloc_free(spaces);
3614                                         talloc_free(text);
3615
3616                                         return false;
3617                                 }
3618
3619                                 goto do_children;
3620                         }
3621
3622                         /*
3623                          *      Statically compile xlats
3624                          */
3625                         if (g->vpt->type == TMPL_TYPE_XLAT) {
3626                                 if (!pass2_xlat_compile(cf_section_to_item(g->cs),
3627                                                         &g->vpt, true, NULL)) {
3628                                         return false;
3629                                 }
3630
3631                                 goto do_children;
3632                         }
3633
3634                         /*
3635                          *      We may have: switch Foo-Bar {
3636                          *
3637                          *      where Foo-Bar is an attribute defined
3638                          *      by a module.  Since there's no leading
3639                          *      &, it's parsed as a literal.  But if
3640                          *      we can parse it as an attribute,
3641                          *      switch to using that.
3642                          */
3643                         if (g->vpt->type == TMPL_TYPE_LITERAL) {
3644                                 vp_tmpl_t *vpt;
3645
3646                                 slen = tmpl_afrom_str(g->cs, &vpt, c->name, strlen(c->name), cf_section_name2_type(g->cs),
3647                                                       REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
3648                                 if (slen < 0) goto parse_error;
3649                                 if (vpt->type == TMPL_TYPE_ATTR) {
3650                                         talloc_free(g->vpt);
3651                                         g->vpt = vpt;
3652                                 }
3653
3654                                 goto do_children;
3655                         }
3656
3657                         /*
3658                          *      Warn about old-style configuration.
3659                          *
3660                          *      DEPRECATED: switch User-Name { ...
3661                          *      ALLOWED   : switch &User-Name { ...
3662                          */
3663                         if ((g->vpt->type == TMPL_TYPE_ATTR) &&
3664                             (c->name[0] != '&')) {
3665                                 WARN("%s[%d]: Please change %s to &%s",
3666                                      cf_section_filename(g->cs),
3667                                      cf_section_lineno(g->cs),
3668                                      c->name, c->name);
3669                         }
3670
3671                 do_children:
3672                         if (!modcall_pass2(g->children)) return false;
3673                         g->done_pass2 = true;
3674                         break;
3675
3676                 case MOD_CASE:
3677                         g = mod_callabletogroup(c);
3678                         if (g->done_pass2) goto do_next;
3679
3680                         name2 = cf_section_name2(g->cs);
3681                         if (!name2) {
3682                                 c->debug_name = unlang_keyword[c->type];
3683                         } else {
3684                                 c->debug_name = talloc_asprintf(c, "%s %s", unlang_keyword[c->type], name2);
3685                         }
3686
3687                         rad_assert(c->parent != NULL);
3688                         rad_assert(c->parent->type == MOD_SWITCH);
3689
3690                         /*
3691                          *      The statement may refer to an
3692                          *      attribute which doesn't exist until
3693                          *      all of the modules have been loaded.
3694                          *      Check for that now.
3695                          */
3696                         if (!g->vpt && c->name &&
3697                             (c->name[0] == '&') &&
3698                             (cf_section_name2_type(g->cs) == T_BARE_WORD)) {
3699                                 slen = tmpl_afrom_str(g->cs, &g->vpt, c->name, strlen(c->name),
3700                                                       cf_section_name2_type(g->cs),
3701                                                       REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
3702                                 if (slen < 0) goto parse_error;
3703                         }
3704
3705                         /*
3706                          *      We have "case {...}".  There's no
3707                          *      argument, so we don't need to check
3708                          *      it.
3709                          */
3710                         if (!g->vpt) goto do_children;
3711
3712                         /*
3713                          *      Do type-specific checks on the case statement
3714                          */
3715                         if (g->vpt->type == TMPL_TYPE_LITERAL) {
3716                                 modgroup *f;
3717
3718                                 f = mod_callabletogroup(mc->parent);
3719                                 rad_assert(f->vpt != NULL);
3720
3721                                 /*
3722                                  *      We're switching over an
3723                                  *      attribute.  Check that the
3724                                  *      values match.
3725                                  */
3726                                 if (f->vpt->type == TMPL_TYPE_ATTR) {
3727                                         rad_assert(f->vpt->tmpl_da != NULL);
3728
3729                                         if (tmpl_cast_in_place(g->vpt, f->vpt->tmpl_da->type, f->vpt->tmpl_da) < 0) {
3730                                                 cf_log_err_cs(g->cs, "Invalid argument for case statement: %s",
3731                                                               fr_strerror());
3732                                                 return false;
3733                                         }
3734                                 }
3735
3736                                 goto do_children;
3737                         }
3738
3739                         /*
3740                          *      Compile and sanity check xlat
3741                          *      expansions.
3742                          */
3743                         if (g->vpt->type == TMPL_TYPE_XLAT) {
3744                                 modgroup *f;
3745
3746                                 f = mod_callabletogroup(mc->parent);
3747                                 rad_assert(f->vpt != NULL);
3748
3749                                 /*
3750                                  *      Don't expand xlat's into an
3751                                  *      attribute of a different type.
3752                                  */
3753                                 if (f->vpt->type == TMPL_TYPE_ATTR) {
3754                                         if (!pass2_xlat_compile(cf_section_to_item(g->cs),
3755                                                                 &g->vpt, true, f->vpt->tmpl_da)) {
3756                                                 return false;
3757                                         }
3758                                 } else {
3759                                         if (!pass2_xlat_compile(cf_section_to_item(g->cs),
3760                                                                 &g->vpt, true, NULL)) {
3761                                                 return false;
3762                                         }
3763                                 }
3764                         }
3765
3766                         if (!modcall_pass2(g->children)) return false;
3767                         g->done_pass2 = true;
3768                         break;
3769
3770                 case MOD_FOREACH:
3771                         g = mod_callabletogroup(c);
3772                         if (g->done_pass2) goto do_next;
3773
3774                         name2 = cf_section_name2(g->cs);
3775                         c->debug_name = talloc_asprintf(c, "%s %s", unlang_keyword[c->type], name2);
3776
3777                         /*
3778                          *      Already parsed, handle the children.
3779                          */
3780                         if (g->vpt) goto check_children;
3781
3782                         /*
3783                          *      We had &Foo-Bar, where Foo-Bar is
3784                          *      defined by a module.
3785                          */
3786                         rad_assert(c->name != NULL);
3787                         rad_assert(c->name[0] == '&');
3788                         rad_assert(cf_section_name2_type(g->cs) == T_BARE_WORD);
3789
3790                         /*
3791                          *      The statement may refer to an
3792                          *      attribute which doesn't exist until
3793                          *      all of the modules have been loaded.
3794                          *      Check for that now.
3795                          */
3796                         slen = tmpl_afrom_str(g->cs, &g->vpt, c->name, strlen(c->name), cf_section_name2_type(g->cs),
3797                                               REQUEST_CURRENT, PAIR_LIST_REQUEST, true);
3798                         if (slen < 0) goto parse_error;
3799
3800                 check_children:
3801                         rad_assert((g->vpt->type == TMPL_TYPE_ATTR) || (g->vpt->type == TMPL_TYPE_LIST));
3802                         if (g->vpt->tmpl_num != NUM_ALL) {
3803                                 cf_log_err_cs(g->cs, "MUST NOT use instance selectors in 'foreach'");
3804                                 return false;
3805                         }
3806                         if (!modcall_pass2(g->children)) return false;
3807                         g->done_pass2 = true;
3808                         break;
3809
3810                 case MOD_ELSE:
3811                         c->debug_name = unlang_keyword[c->type];
3812                         goto do_recurse;
3813
3814                 case MOD_POLICY:
3815                         g = mod_callabletogroup(c);
3816                         c->debug_name = talloc_asprintf(c, "%s %s", unlang_keyword[c->type], cf_section_name1(g->cs));
3817                         goto do_recurse;
3818 #endif
3819
3820                 case MOD_GROUP:
3821                 case MOD_LOAD_BALANCE:
3822                 case MOD_REDUNDANT_LOAD_BALANCE:
3823                         c->debug_name = unlang_keyword[c->type];
3824
3825 #ifdef WITH_UNLANG
3826                 do_recurse:
3827 #endif
3828                         g = mod_callabletogroup(c);
3829                         if (!g->cs) {
3830                                 c->debug_name = mc->name; /* for authorize, etc. */
3831
3832                         } else if (c->type == MOD_GROUP) { /* for Auth-Type, etc. */
3833                                 char const *name1 = cf_section_name1(g->cs);
3834
3835                                 if (strcmp(name1, unlang_keyword[c->type]) != 0) {
3836                                         c->debug_name = talloc_asprintf(c, "%s %s", name1, cf_section_name2(g->cs));
3837                                 }
3838                         }
3839
3840                         if (g->done_pass2) goto do_next;
3841                         if (!modcall_pass2(g->children)) return false;
3842                         g->done_pass2 = true;
3843                         break;
3844                 }
3845
3846         do_next:
3847                 rad_assert(c->debug_name != NULL);
3848         }
3849
3850         return true;
3851 }
3852
3853 void modcall_debug(modcallable *mc, int depth)
3854 {
3855         modcallable *this;
3856         modgroup *g;
3857         vp_map_t *map;
3858         char buffer[1024];
3859
3860         for (this = mc; this != NULL; this = this->next) {
3861                 switch (this->type) {
3862                 default:
3863                         break;
3864
3865                 case MOD_SINGLE: {
3866                         modsingle *single = mod_callabletosingle(this);
3867
3868                         DEBUG("%.*s%s", depth, modcall_spaces,
3869                                 single->modinst->name);
3870                         }
3871                         break;
3872
3873 #ifdef WITH_UNLANG
3874                 case MOD_UPDATE:
3875                         g = mod_callabletogroup(this);
3876                         DEBUG("%.*s%s {", depth, modcall_spaces,
3877                                 unlang_keyword[this->type]);
3878
3879                         for (map = g->map; map != NULL; map = map->next) {
3880                                 map_prints(buffer, sizeof(buffer), map);
3881                                 DEBUG("%.*s%s", depth + 1, modcall_spaces, buffer);
3882                         }
3883
3884                         DEBUG("%.*s}", depth, modcall_spaces);
3885                         break;
3886
3887                 case MOD_ELSE:
3888                         g = mod_callabletogroup(this);
3889                         DEBUG("%.*s%s {", depth, modcall_spaces,
3890                                 unlang_keyword[this->type]);
3891                         modcall_debug(g->children, depth + 1);
3892                         DEBUG("%.*s}", depth, modcall_spaces);
3893                         break;
3894
3895                 case MOD_IF:
3896                 case MOD_ELSIF:
3897                         g = mod_callabletogroup(this);
3898                         fr_cond_sprint(buffer, sizeof(buffer), g->cond);
3899                         DEBUG("%.*s%s (%s) {", depth, modcall_spaces,
3900                                 unlang_keyword[this->type], buffer);
3901                         modcall_debug(g->children, depth + 1);
3902                         DEBUG("%.*s}", depth, modcall_spaces);
3903                         break;
3904
3905                 case MOD_SWITCH:
3906                 case MOD_CASE:
3907                         g = mod_callabletogroup(this);
3908                         tmpl_prints(buffer, sizeof(buffer), g->vpt, NULL);
3909                         DEBUG("%.*s%s %s {", depth, modcall_spaces,
3910                                 unlang_keyword[this->type], buffer);
3911                         modcall_debug(g->children, depth + 1);
3912                         DEBUG("%.*s}", depth, modcall_spaces);
3913                         break;
3914
3915                 case MOD_POLICY:
3916                 case MOD_FOREACH:
3917                         g = mod_callabletogroup(this);
3918                         DEBUG("%.*s%s %s {", depth, modcall_spaces,
3919                                 unlang_keyword[this->type], this->name);
3920                         modcall_debug(g->children, depth + 1);
3921                         DEBUG("%.*s}", depth, modcall_spaces);
3922                         break;
3923
3924                 case MOD_BREAK:
3925                         DEBUG("%.*sbreak", depth, modcall_spaces);
3926                         break;
3927
3928 #endif
3929                 case MOD_GROUP:
3930                         g = mod_callabletogroup(this);
3931                         DEBUG("%.*s%s {", depth, modcall_spaces,
3932                               unlang_keyword[this->type]);
3933                         modcall_debug(g->children, depth + 1);
3934                         DEBUG("%.*s}", depth, modcall_spaces);
3935                         break;
3936
3937
3938                 case MOD_LOAD_BALANCE:
3939                 case MOD_REDUNDANT_LOAD_BALANCE:
3940                         g = mod_callabletogroup(this);
3941                         DEBUG("%.*s%s {", depth, modcall_spaces,
3942                                 unlang_keyword[this->type]);
3943                         modcall_debug(g->children, depth + 1);
3944                         DEBUG("%.*s}", depth, modcall_spaces);
3945                         break;
3946                 }
3947         }
3948 }