Print out error for non-server "authorize" etc. sections
[freeradius.git] / src / main / modules.c
1 /*
2  * modules.c    Radius module support.
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 2003,2006  The FreeRADIUS server project
21  * Copyright 2000  Alan DeKok <aland@ox.org>
22  * Copyright 2000  Alan Curry <pacman@world.std.com>
23  */
24
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modpriv.h>
29 #include <freeradius-devel/modcall.h>
30 #include <freeradius-devel/parser.h>
31 #include <freeradius-devel/rad_assert.h>
32
33 typedef struct indexed_modcallable {
34         rlm_components_t        comp;
35         int                     idx;
36         modcallable             *modulelist;
37 } indexed_modcallable;
38
39 typedef struct virtual_server_t {
40         char const      *name;
41         time_t          created;
42         int             can_free;
43         CONF_SECTION    *cs;
44         rbtree_t        *components;
45         modcallable     *mc[RLM_COMPONENT_COUNT];
46         CONF_SECTION    *subcs[RLM_COMPONENT_COUNT];
47         struct virtual_server_t *next;
48 } virtual_server_t;
49
50 /*
51  *      Keep a hash of virtual servers, so that we can reload them.
52  */
53 #define VIRTUAL_SERVER_HASH_SIZE (256)
54 static virtual_server_t *virtual_servers[VIRTUAL_SERVER_HASH_SIZE];
55
56 static rbtree_t *module_tree = NULL;
57
58 static rbtree_t *instance_tree = NULL;
59
60 struct fr_module_hup_t {
61         module_instance_t       *mi;
62         time_t                  when;
63         void                    *insthandle;
64         fr_module_hup_t         *next;
65 };
66
67 /*
68  *      Ordered by component
69  */
70 const section_type_value_t section_type_value[RLM_COMPONENT_COUNT] = {
71         { "authenticate", "Auth-Type",       PW_AUTH_TYPE },
72         { "authorize",    "Autz-Type",       PW_AUTZ_TYPE },
73         { "preacct",      "Pre-Acct-Type",   PW_PRE_ACCT_TYPE },
74         { "accounting",   "Acct-Type",       PW_ACCT_TYPE },
75         { "session",      "Session-Type",    PW_SESSION_TYPE },
76         { "pre-proxy",    "Pre-Proxy-Type",  PW_PRE_PROXY_TYPE },
77         { "post-proxy",   "Post-Proxy-Type", PW_POST_PROXY_TYPE },
78         { "post-auth",    "Post-Auth-Type",  PW_POST_AUTH_TYPE }
79 #ifdef WITH_COA
80         ,
81         { "recv-coa",     "Recv-CoA-Type",   PW_RECV_COA_TYPE },
82         { "send-coa",     "Send-CoA-Type",   PW_SEND_COA_TYPE }
83 #endif
84 };
85
86 #ifndef RTLD_NOW
87 #define RTLD_NOW (0)
88 #endif
89 #ifndef RTLD_LOCAL
90 #define RTLD_LOCAL (0)
91 #endif
92
93 #ifdef __APPLE__
94 #  define LT_SHREXT ".dylib"
95 #elif defined (WIN32)
96 #  define LT_SHREXT ".dll"
97 #else
98 #  define LT_SHREXT ".so"
99 #endif
100
101 /** Check if the magic number in the module matches the one in the library
102  *
103  * This is used to detect potential ABI issues caused by running with modules which
104  * were built for a different version of the server.
105  *
106  * @param cs being parsed.
107  * @param module being loaded.
108  * @returns 0 on success, -1 if prefix mismatch, -2 if version mismatch, -3 if commit mismatch.
109  */
110 static int check_module_magic(CONF_SECTION *cs, module_t const *module)
111 {
112         if (MAGIC_PREFIX(module->magic) != MAGIC_PREFIX(RADIUSD_MAGIC_NUMBER)) {
113                 cf_log_err_cs(cs, "Application and rlm_%s magic number (prefix) mismatch."
114                               "  application: %x module: %x", module->name,
115                               MAGIC_PREFIX(RADIUSD_MAGIC_NUMBER),
116                               MAGIC_PREFIX(module->magic));
117                 return -1;
118         }
119
120         if (MAGIC_VERSION(module->magic) != MAGIC_VERSION(RADIUSD_MAGIC_NUMBER)) {
121                 cf_log_err_cs(cs, "Application and rlm_%s magic number (version) mismatch."
122                               "  application: %lx module: %lx", module->name,
123                               (unsigned long) MAGIC_VERSION(RADIUSD_MAGIC_NUMBER),
124                               (unsigned long) MAGIC_VERSION(module->magic));
125                 return -2;
126         }
127
128         if (MAGIC_COMMIT(module->magic) != MAGIC_COMMIT(RADIUSD_MAGIC_NUMBER)) {
129                 cf_log_err_cs(cs, "Application and rlm_%s magic number (commit) mismatch."
130                               "  application: %lx module: %lx", module->name,
131                               (unsigned long) MAGIC_COMMIT(RADIUSD_MAGIC_NUMBER),
132                               (unsigned long) MAGIC_COMMIT(module->magic));
133                 return -3;
134         }
135
136         return 0;
137 }
138
139 lt_dlhandle lt_dlopenext(char const *name)
140 {
141         int flags = RTLD_NOW;
142         void *handle;
143         char buffer[2048];
144         char *env;
145
146 #ifdef RTLD_GLOBAL
147         if (strcmp(name, "rlm_perl") == 0) {
148                 flags |= RTLD_GLOBAL;
149         } else
150 #endif
151                 flags |= RTLD_LOCAL;
152
153 #ifndef NDEBUG
154         /*
155          *      Bind all the symbols *NOW* so we don't hit errors later
156          */
157         flags |= RTLD_NOW;
158 #endif
159         /*
160          *      Prefer loading our libraries by absolute path.
161          */
162         snprintf(buffer, sizeof(buffer), "%s/%s%s", radlib_dir, name, LT_SHREXT);
163
164         DEBUG4("Loading library using absolute path \"%s\"", name);
165
166         handle = dlopen(buffer, flags);
167         if (handle) return handle;
168
169         /*
170          *      Because dlopen produces really shitty and inaccurate error messages
171          */
172         if (access(name, R_OK) < 0) switch (errno) {
173         case EACCES:
174                 WARN("Library file found, but we don't have permission to read it");
175                 break;
176
177         case ENOENT:
178                 DEBUG4("Library file not found");
179                 break;
180
181         default:
182                 DEBUG4("Issue accessing library file: %s", fr_syserror(errno));
183                 break;
184         }
185
186         DEBUG4("Falling back to linker search path(s)");
187         if (DEBUG_ENABLED4) {
188 #ifdef __APPLE__
189                 env = getenv("LD_LIBRARY_PATH");
190                 if (env) {
191                         DEBUG4("LD_LIBRARY_PATH            : %s", env);
192                 }
193                 env = getenv("DYLD_LIBRARY_PATH");
194                 if (env) {
195                         DEBUG4("DYLB_LIBRARY_PATH          : %s", env);
196                 }
197                 env = getenv("DYLD_FALLBACK_LIBRARY_PATH");
198                 if (env) {
199                         DEBUG4("DYLD_FALLBACK_LIBRARY_PATH : %s", env);
200                 }
201                 env = getcwd(buffer, sizeof(buffer));
202                 if (env) {
203                         DEBUG4("Current directory          : %s", env);
204                 }
205 #else
206                 env = getenv("LD_LIBRARY_PATH");
207                 if (env) {
208                         DEBUG4("LD_LIBRARY_PATH  : %s", env);
209                 }
210                 DEBUG4("Defaults         : /lib:/usr/lib");
211 #endif
212         }
213
214         strlcpy(buffer, name, sizeof(buffer));
215         /*
216          *      FIXME: Make this configurable...
217          */
218         strlcat(buffer, LT_SHREXT, sizeof(buffer));
219
220         return dlopen(buffer, flags);
221 }
222
223 void *lt_dlsym(lt_dlhandle handle, char const *symbol)
224 {
225         return dlsym(handle, symbol);
226 }
227
228 int lt_dlclose(lt_dlhandle handle)
229 {
230         if (!handle) return 0;
231
232         return dlclose(handle);
233 }
234
235 char const *lt_dlerror(void)
236 {
237         return dlerror();
238 }
239
240 static int virtual_server_idx(char const *name)
241 {
242         uint32_t hash;
243
244         if (!name) return 0;
245
246         hash = fr_hash_string(name);
247
248         return hash & (VIRTUAL_SERVER_HASH_SIZE - 1);
249 }
250
251 static virtual_server_t *virtual_server_find(char const *name)
252 {
253         rlm_rcode_t rcode;
254         virtual_server_t *server;
255
256         rcode = virtual_server_idx(name);
257         for (server = virtual_servers[rcode];
258              server != NULL;
259              server = server->next) {
260                 if (!name && !server->name) break;
261
262                 if ((name && server->name) &&
263                     (strcmp(name, server->name) == 0)) break;
264         }
265
266         return server;
267 }
268
269 static int _virtual_server_free(virtual_server_t *server)
270 {
271         if (server->components) rbtree_free(server->components);
272         return 0;
273 }
274
275 void virtual_servers_free(time_t when)
276 {
277         int i;
278         virtual_server_t **last;
279
280         for (i = 0; i < VIRTUAL_SERVER_HASH_SIZE; i++) {
281                 virtual_server_t *server, *next;
282
283                 last = &virtual_servers[i];
284                 for (server = virtual_servers[i];
285                      server != NULL;
286                      server = next) {
287                         next = server->next;
288
289                         /*
290                          *      If we delete it, fix the links so that
291                          *      we don't orphan anything.  Also,
292                          *      delete it if it's old, AND a newer one
293                          *      was defined.
294                          *
295                          *      Otherwise, the last pointer gets set to
296                          *      the one we didn't delete.
297                          */
298                         if ((when == 0) ||
299                             ((server->created < when) && server->can_free)) {
300                                 *last = server->next;
301                                 talloc_free(server);
302                         } else {
303                                 last = &(server->next);
304                         }
305                 }
306         }
307 }
308
309 static int indexed_modcallable_cmp(void const *one, void const *two)
310 {
311         indexed_modcallable const *a = one;
312         indexed_modcallable const *b = two;
313
314         if (a->comp < b->comp) return -1;
315         if (a->comp >  b->comp) return +1;
316
317         return a->idx - b->idx;
318 }
319
320
321 /*
322  *      Compare two module entries
323  */
324 static int module_instance_cmp(void const *one, void const *two)
325 {
326         module_instance_t const *a = one;
327         module_instance_t const *b = two;
328
329         return strcmp(a->name, b->name);
330 }
331
332
333 static void module_instance_free_old(UNUSED CONF_SECTION *cs, module_instance_t *node, time_t when)
334 {
335         fr_module_hup_t *mh, **last;
336
337         /*
338          *      Walk the list, freeing up old instances.
339          */
340         last = &(node->mh);
341         while (*last) {
342                 mh = *last;
343
344                 /*
345                  *      Free only every 60 seconds.
346                  */
347                 if ((when - mh->when) < 60) {
348                         last = &(mh->next);
349                         continue;
350                 }
351
352                 talloc_free(mh->insthandle);
353
354                 *last = mh->next;
355                 talloc_free(mh);
356         }
357 }
358
359
360 /*
361  *      Free a module instance.
362  */
363 static void module_instance_free(void *data)
364 {
365         module_instance_t *module = talloc_get_type_abort(data, module_instance_t);
366
367         module_instance_free_old(module->cs, module, time(NULL) + 100);
368
369 #ifdef HAVE_PTHREAD_H
370         if (module->mutex) {
371                 /*
372                  *      FIXME
373                  *      The mutex MIGHT be locked...
374                  *      we'll check for that later, I guess.
375                  */
376                 pthread_mutex_destroy(module->mutex);
377                 talloc_free(module->mutex);
378         }
379 #endif
380
381         /*
382          *      Remove any registered paircompares.
383          */
384         paircompare_unregister_instance(module->insthandle);
385
386         xlat_unregister(module->name, NULL, module->insthandle);
387         /*
388          *      Remove all xlat's registered to module instance.
389          */
390         if (module->insthandle) xlat_unregister_module(module->insthandle);
391         talloc_free(module);
392 }
393
394
395 /*
396  *      Compare two module entries
397  */
398 static int module_entry_cmp(void const *one, void const *two)
399 {
400         module_entry_t const *a = one;
401         module_entry_t const *b = two;
402
403         return strcmp(a->name, b->name);
404 }
405
406 /*
407  *      Free a module entry.
408  */
409 static int _module_entry_free(module_entry_t *this)
410 {
411 #ifndef NDEBUG
412         /*
413          *      Don't dlclose() modules if we're doing memory
414          *      debugging.  This removes the symbols needed by
415          *      valgrind.
416          */
417         if (!main_config.debug_memory)
418 #endif
419                 dlclose(this->handle);  /* ignore any errors */
420         return 0;
421 }
422
423
424 /*
425  *      Remove the module lists.
426  */
427 int modules_free(void)
428 {
429         rbtree_free(instance_tree);
430         rbtree_free(module_tree);
431
432         return 0;
433 }
434
435
436 /*
437  *      Find a module on disk or in memory, and link to it.
438  */
439 static module_entry_t *linkto_module(char const *module_name, CONF_SECTION *cs)
440 {
441         module_entry_t myentry;
442         module_entry_t *node;
443         void *handle = NULL;
444         module_t const *module;
445
446         strlcpy(myentry.name, module_name, sizeof(myentry.name));
447         node = rbtree_finddata(module_tree, &myentry);
448         if (node) return node;
449
450         /*
451          *      Link to the module's rlm_FOO{} structure, the same as
452          *      the module name.
453          */
454
455 #if !defined(WITH_LIBLTDL) && defined(HAVE_DLFCN_H) && defined(RTLD_SELF)
456         module = dlsym(RTLD_SELF, module_name);
457         if (module) goto open_self;
458 #endif
459
460         /*
461          *      Keep the handle around so we can dlclose() it.
462          */
463         handle = lt_dlopenext(module_name);
464         if (!handle) {
465                 cf_log_err_cs(cs, "Failed to link to module '%s': %s", module_name, dlerror());
466                 return NULL;
467         }
468
469         DEBUG3("Loaded %s, checking if it's valid", module_name);
470
471         module = dlsym(handle, module_name);
472         if (!module) {
473                 cf_log_err_cs(cs, "Failed linking to %s structure: %s", module_name, dlerror());
474                 dlclose(handle);
475                 return NULL;
476         }
477
478 #if !defined(WITH_LIBLTDL) && defined (HAVE_DLFCN_H) && defined(RTLD_SELF)
479  open_self:
480 #endif
481         /*
482          *      Before doing anything else, check if it's sane.
483          */
484         if (check_module_magic(cs, module) < 0) {
485                 dlclose(handle);
486                 return NULL;
487         }
488
489         /* make room for the module type */
490         node = talloc_zero(cs, module_entry_t);
491         talloc_set_destructor(node, _module_entry_free);
492         strlcpy(node->name, module_name, sizeof(node->name));
493         node->module = module;
494         node->handle = handle;
495
496         cf_log_module(cs, "Loaded module %s", module_name);
497
498         /*
499          *      Add the module as "rlm_foo-version" to the configuration
500          *      section.
501          */
502         if (!rbtree_insert(module_tree, node)) {
503                 ERROR("Failed to cache module %s", module_name);
504                 dlclose(handle);
505                 talloc_free(node);
506                 return NULL;
507         }
508
509         return node;
510 }
511
512 /** Parse module's configuration section and setup destructors
513  *
514  */
515 static int module_conf_parse(module_instance_t *node, void **handle)
516 {
517         *handle = NULL;
518
519         /*
520          *      If there is supposed to be instance data, allocate it now.
521          *      Also parse the configuration data, if required.
522          */
523         if (node->entry->module->inst_size) {
524                 /* FIXME: make this rlm_config_t ?? */
525                 *handle = talloc_zero_array(node, uint8_t, node->entry->module->inst_size);
526                 rad_assert(handle);
527
528                 /*
529                  *      So we can see where this configuration is from
530                  *      FIXME: set it to rlm_NAME_t, or some such thing
531                  */
532                 talloc_set_name(*handle, "rlm_config_t");
533
534                 if (node->entry->module->config &&
535                     (cf_section_parse(node->cs, *handle, node->entry->module->config) < 0)) {
536                         cf_log_err_cs(node->cs,"Invalid configuration for module \"%s\"", node->name);
537                         talloc_free(*handle);
538
539                         return -1;
540                 }
541
542                 /*
543                  *      Set the destructor.
544                  */
545                 if (node->entry->module->detach) {
546                         talloc_set_destructor(*handle, node->entry->module->detach);
547                 }
548         }
549
550         return 0;
551 }
552
553 /*
554  *      Find a module instance.
555  */
556 module_instance_t *find_module_instance(CONF_SECTION *modules,
557                                         char const *askedname, bool do_link)
558 {
559         bool check_config_safe = false;
560         CONF_SECTION *cs;
561         char const *name1, *instname;
562         module_instance_t *node, myNode;
563         char module_name[256];
564
565         if (!modules) return NULL;
566
567         /*
568          *      Look for the real name.  Ignore the first character,
569          *      which tells the server "it's OK for this module to not
570          *      exist."
571          */
572         instname = askedname;
573         if (instname[0] == '-') {
574                 instname++;
575         }
576
577         /*
578          *      Module instances are declared in the modules{} block
579          *      and referenced later by their name, which is the
580          *      name2 from the config section, or name1 if there was
581          *      no name2.
582          */
583         cs = cf_section_sub_find_name2(modules, NULL, instname);
584         if (!cs) {
585                 ERROR("Cannot find a configuration entry for module \"%s\"", instname);
586                 return NULL;
587         }
588
589         /*
590          *      If there's already a module instance, return it.
591          */
592         strlcpy(myNode.name, instname, sizeof(myNode.name));
593
594         node = rbtree_finddata(instance_tree, &myNode);
595         if (node) {
596                 return node;
597         }
598
599         if (!do_link) {
600                 return NULL;
601         }
602
603         name1 = cf_section_name1(cs);
604
605         /*
606          *      Found the configuration entry, hang the node struct off of the
607          *      configuration section. If the CS is free'd the instance will
608          *      be too.
609          */
610         node = talloc_zero(cs, module_instance_t);
611         node->cs = cs;
612
613         /*
614          *      Names in the "modules" section aren't prefixed
615          *      with "rlm_", so we add it here.
616          */
617         snprintf(module_name, sizeof(module_name), "rlm_%s", name1);
618
619         /*
620          *      Pull in the module object
621          */
622         node->entry = linkto_module(module_name, cs);
623         if (!node->entry) {
624                 talloc_free(node);
625                 /* linkto_module logs any errors */
626                 return NULL;
627         }
628
629         if (check_config && (node->entry->module->instantiate) &&
630             (node->entry->module->type & RLM_TYPE_CHECK_CONFIG_UNSAFE) != 0) {
631                 char const *value = NULL;
632                 CONF_PAIR *cp;
633
634                 cp = cf_pair_find(cs, "force_check_config");
635                 if (cp) {
636                         value = cf_pair_value(cp);
637                 }
638
639                 if (value && (strcmp(value, "yes") == 0)) goto print_inst;
640
641                 cf_log_module(cs, "Skipping instantiation of %s", instname);
642         } else {
643         print_inst:
644                 check_config_safe = true;
645                 cf_log_module(cs, "Instantiating module \"%s\" from file %s", instname,
646                               cf_section_filename(cs));
647         }
648
649         strlcpy(node->name, instname, sizeof(node->name));
650
651         /*
652          *      Parse the module configuration, and setup destructors so the
653          *      module's detach method is called when it's instance data is
654          *      about to be freed.
655          */
656         if (module_conf_parse(node, &node->insthandle) < 0) {
657                 talloc_free(node);
658
659                 return NULL;
660         }
661
662         /*
663          *      Call the module's instantiation routine.
664          */
665         if ((node->entry->module->instantiate) &&
666             (!check_config || check_config_safe) &&
667             ((node->entry->module->instantiate)(cs, node->insthandle) < 0)) {
668                 cf_log_err_cs(cs, "Instantiation failed for module \"%s\"", node->name);
669                 talloc_free(node);
670
671                 return NULL;
672         }
673
674 #ifdef HAVE_PTHREAD_H
675         /*
676          *      If we're threaded, check if the module is thread-safe.
677          *
678          *      If it isn't, we create a mutex.
679          */
680         if ((node->entry->module->type & RLM_TYPE_THREAD_UNSAFE) != 0) {
681                 node->mutex = talloc_zero(node, pthread_mutex_t);
682
683                 /*
684                  *      Initialize the mutex.
685                  */
686                 pthread_mutex_init(node->mutex, NULL);
687         } else {
688                 /*
689                  *      The module is thread-safe.  Don't give it a mutex.
690                  */
691                 node->mutex = NULL;
692         }
693
694 #endif
695         rbtree_insert(instance_tree, node);
696
697         return node;
698 }
699
700 /** Resolve polymorphic item's from a module's CONF_SECTION to a subsection in another module
701  *
702  * This allows certain module sections to reference module sections in other instances
703  * of the same module and share CONF_DATA associated with them.
704  *
705  * @verbatim
706 example {
707         data {
708                 ...
709         }
710 }
711
712 example inst {
713         data = example
714 }
715  * @endverbatim
716  *
717  * @param out where to write the pointer to a module's config section.  May be NULL on success, indicating the config
718  *        item was not found within the module CONF_SECTION, or the chain of module references was followed and the
719  *        module at the end of the chain did not a subsection.
720  * @param module CONF_SECTION.
721  * @param name of the polymorphic sub-section.
722  * @return 0 on success with referenced section, 1 on success with local section, or -1 on failure.
723  */
724 int find_module_sibling_section(CONF_SECTION **out, CONF_SECTION *module, char const *name)
725 {
726         static bool loop = true;        /* not used, we just need a valid pointer to quiet static analysis */
727
728         CONF_PAIR *cp;
729         CONF_SECTION *cs;
730
731         module_instance_t *inst;
732         char const *inst_name;
733
734 #define FIND_SIBLING_CF_KEY "find_sibling"
735
736         *out = NULL;
737
738         /*
739          *      Is a real section (not referencing sibling module).
740          */
741         cs = cf_section_sub_find(module, name);
742         if (cs) {
743                 *out = cs;
744
745                 return 0;
746         }
747
748         /*
749          *      Item omitted completely from module config.
750          */
751         cp = cf_pair_find(module, name);
752         if (!cp) return 0;
753
754         if (cf_data_find(module, FIND_SIBLING_CF_KEY)) {
755                 cf_log_err_cp(cp, "Module reference loop found");
756
757                 return -1;
758         }
759         cf_data_add(module, FIND_SIBLING_CF_KEY, &loop, NULL);
760
761         /*
762          *      Item found, resolve it to a module instance.
763          *      This triggers module loading, so we don't have
764          *      instantiation order issues.
765          */
766         inst_name = cf_pair_value(cp);
767         inst = find_module_instance(cf_item_parent(cf_section_to_item(module)), inst_name, true);
768
769         /*
770          *      Remove the config data we added for loop
771          *      detection.
772          */
773         cf_data_remove(module, FIND_SIBLING_CF_KEY);
774         if (!inst) {
775                 cf_log_err_cp(cp, "Unknown module instance \"%s\"", inst_name);
776
777                 return -1;
778         }
779
780         /*
781          *      Check the module instances are of the same type.
782          */
783         if (strcmp(cf_section_name1(inst->cs), cf_section_name1(module)) != 0) {
784                 cf_log_err_cp(cp, "Referenced module is a rlm_%s instance, must be a rlm_%s instance",
785                               cf_section_name1(inst->cs), cf_section_name1(module));
786
787                 return -1;
788         }
789
790         *out = cf_section_sub_find(inst->cs, name);
791
792         return 1;
793 }
794
795 static indexed_modcallable *lookup_by_index(rbtree_t *components,
796                                             rlm_components_t comp, int idx)
797 {
798         indexed_modcallable myc;
799
800         myc.comp = comp;
801         myc.idx = idx;
802
803         return rbtree_finddata(components, &myc);
804 }
805
806 /*
807  *      Create a new sublist.
808  */
809 static indexed_modcallable *new_sublist(CONF_SECTION *cs,
810                                         rbtree_t *components, rlm_components_t comp, int idx)
811 {
812         indexed_modcallable *c;
813
814         c = lookup_by_index(components, comp, idx);
815
816         /* It is an error to try to create a sublist that already
817          * exists. It would almost certainly be caused by accidental
818          * duplication in the config file.
819          *
820          * index 0 is the exception, because it is used when we want
821          * to collect _all_ listed modules under a single index by
822          * default, which is currently the case in all components
823          * except authenticate. */
824         if (c) {
825                 if (idx == 0) {
826                         return c;
827                 }
828                 return NULL;
829         }
830
831         c = talloc_zero(cs, indexed_modcallable);
832         c->modulelist = NULL;
833         c->comp = comp;
834         c->idx = idx;
835
836         if (!rbtree_insert(components, c)) {
837                 talloc_free(c);
838                 return NULL;
839         }
840
841         return c;
842 }
843
844 rlm_rcode_t indexed_modcall(rlm_components_t comp, int idx, REQUEST *request)
845 {
846         rlm_rcode_t rcode;
847         modcallable *list = NULL;
848         virtual_server_t *server;
849
850         /*
851          *      Hack to find the correct virtual server.
852          */
853         server = virtual_server_find(request->server);
854         if (!server) {
855                 RDEBUG("No such virtual server \"%s\"", request->server);
856                 return RLM_MODULE_FAIL;
857         }
858
859         if (idx == 0) {
860                 list = server->mc[comp];
861                 if (!list) RDEBUG3("Empty %s section.  Using default return values.", section_type_value[comp].section);
862
863         } else {
864                 indexed_modcallable *this;
865
866                 this = lookup_by_index(server->components, comp, idx);
867                 if (this) {
868                         list = this->modulelist;
869                 } else {
870                         RDEBUG3("%s sub-section not found.  Ignoring.",
871                                 section_type_value[comp].typename);
872                 }
873         }
874
875         if (server->subcs[comp]) {
876                 if (idx == 0) {
877                         RDEBUG("# Executing section %s from file %s",
878                                section_type_value[comp].section,
879                                cf_section_filename(server->subcs[comp]));
880                 } else {
881                         RDEBUG("# Executing group from file %s",
882                                cf_section_filename(server->subcs[comp]));
883                 }
884         }
885         request->component = section_type_value[comp].section;
886
887         rcode = modcall(comp, list, request);
888
889         request->module = "";
890         request->component = "<core>";
891         return rcode;
892 }
893
894 /*
895  *      Load a sub-module list, as found inside an Auth-Type foo {}
896  *      block
897  */
898 static int load_subcomponent_section(CONF_SECTION *cs,
899                                      rbtree_t *components,
900                                      DICT_ATTR const *da, rlm_components_t comp)
901 {
902         indexed_modcallable *subcomp;
903         modcallable *ml;
904         DICT_VALUE *dval;
905         char const *name2 = cf_section_name2(cs);
906
907         /*
908          *      Sanity check.
909          */
910         if (!name2) {
911                 return 1;
912         }
913
914         /*
915          *      Compile the group.
916          */
917         ml = compile_modgroup(NULL, comp, cs);
918         if (!ml) {
919                 return 0;
920         }
921
922         /*
923          *      We must assign a numeric index to this subcomponent.
924          *      It is generated and placed in the dictionary
925          *      automatically.  If it isn't found, it's a serious
926          *      error.
927          */
928         dval = dict_valbyname(da->attr, da->vendor, name2);
929         if (!dval) {
930                 talloc_free(ml);
931                 cf_log_err_cs(cs,
932                            "The %s attribute has no VALUE defined for %s",
933                               section_type_value[comp].typename, name2);
934                 return 0;
935         }
936
937         subcomp = new_sublist(cs, components, comp, dval->value);
938         if (!subcomp) {
939                 talloc_free(ml);
940                 return 1;
941         }
942
943         /*
944          *      Link it into the talloc hierarchy.
945          */
946         subcomp->modulelist = talloc_steal(subcomp, ml);
947         return 1;               /* OK */
948 }
949
950 /*
951  *      Don't complain too often.
952  */
953 #define MAX_IGNORED (32)
954 static int last_ignored = -1;
955 static char const *ignored[MAX_IGNORED];
956
957 static int load_component_section(CONF_SECTION *cs,
958                                   rbtree_t *components, rlm_components_t comp)
959 {
960         modcallable *this;
961         CONF_ITEM *modref;
962         int idx;
963         indexed_modcallable *subcomp;
964         char const *modname;
965         DICT_ATTR const *da;
966
967         /*
968          *      Find the attribute used to store VALUEs for this section.
969          */
970         da = dict_attrbyvalue(section_type_value[comp].attr, 0);
971         if (!da) {
972                 cf_log_err_cs(cs,
973                            "No such attribute %s",
974                            section_type_value[comp].typename);
975                 return -1;
976         }
977
978         /*
979          *      Loop over the entries in the named section, loading
980          *      the sections this time.
981          */
982         for (modref = cf_item_find_next(cs, NULL);
983              modref != NULL;
984              modref = cf_item_find_next(cs, modref)) {
985                 char const *name1;
986                 CONF_PAIR *cp = NULL;
987                 CONF_SECTION *scs = NULL;
988
989                 if (cf_item_is_section(modref)) {
990                         scs = cf_item_to_section(modref);
991
992                         name1 = cf_section_name1(scs);
993
994                         if (strcmp(name1,
995                                    section_type_value[comp].typename) == 0) {
996                                 if (!load_subcomponent_section(scs,
997                                                                components,
998                                                                da,
999                                                                comp)) {
1000
1001                                         return -1; /* FIXME: memleak? */
1002                                 }
1003                                 continue;
1004                         }
1005
1006                         cp = NULL;
1007
1008                 } else if (cf_item_is_pair(modref)) {
1009                         cp = cf_item_to_pair(modref);
1010
1011                 } else {
1012                         continue; /* ignore it */
1013                 }
1014
1015                 /*
1016                  *      Look for Auth-Type foo {}, which are special
1017                  *      cases of named sections, and allowable ONLY
1018                  *      at the top-level.
1019                  *
1020                  *      i.e. They're not allowed in a "group" or "redundant"
1021                  *      subsection.
1022                  */
1023                 if (comp == RLM_COMPONENT_AUTH) {
1024                         DICT_VALUE *dval;
1025                         char const *modrefname = NULL;
1026                         if (cp) {
1027                                 modrefname = cf_pair_attr(cp);
1028                         } else {
1029                                 modrefname = cf_section_name2(scs);
1030                                 if (!modrefname) {
1031                                         cf_log_err_cs(cs,
1032                                                    "Errors parsing %s sub-section.\n",
1033                                                    cf_section_name1(scs));
1034                                         return -1;
1035                                 }
1036                         }
1037
1038                         dval = dict_valbyname(PW_AUTH_TYPE, 0, modrefname);
1039                         if (!dval) {
1040                                 /*
1041                                  *      It's a section, but nothing we
1042                                  *      recognize.  Die!
1043                                  */
1044                                 cf_log_err_cs(cs,
1045                                            "Unknown Auth-Type \"%s\" in %s sub-section.",
1046                                            modrefname, section_type_value[comp].section);
1047                                 return -1;
1048                         }
1049                         idx = dval->value;
1050                 } else {
1051                         /* See the comment in new_sublist() for explanation
1052                          * of the special index 0 */
1053                         idx = 0;
1054                 }
1055
1056                 subcomp = new_sublist(cs, components, comp, idx);
1057                 if (!subcomp) continue;
1058
1059                 /*
1060                  *      Try to compile one entry.
1061                  */
1062                 this = compile_modsingle(subcomp, &subcomp->modulelist, comp, modref, &modname);
1063
1064                 /*
1065                  *      It's OK for the module to not exist.
1066                  */
1067                 if (!this && modname && (modname[0] == '-')) {
1068                         int i;
1069
1070                         if (last_ignored < 0) {
1071                         save_complain:
1072                                 last_ignored++;
1073                                 ignored[last_ignored] = modname;
1074
1075                         complain:
1076                                 WARN("Ignoring \"%s\" (see raddb/mods-available/README.rst)", modname + 1);
1077                                 continue;
1078                         }
1079
1080                         if (last_ignored >= MAX_IGNORED) goto complain;
1081
1082                         for (i = 0; i <= last_ignored; i++) {
1083                                 if (strcmp(ignored[i], modname) == 0) {
1084                                         break;
1085                                 }
1086                         }
1087
1088                         if (i > last_ignored) goto save_complain;
1089                         continue;
1090                 }
1091
1092                 if (!this) {
1093                         cf_log_err_cs(cs,
1094                                    "Errors parsing %s section.\n",
1095                                    cf_section_name1(cs));
1096                         return -1;
1097                 }
1098
1099                 if (debug_flag > 2) modcall_debug(this, 2);
1100
1101                 add_to_modcallable(subcomp->modulelist, this);
1102         }
1103
1104
1105         return 0;
1106 }
1107
1108 static int load_byserver(CONF_SECTION *cs)
1109 {
1110         rlm_components_t comp, found;
1111         char const *name = cf_section_name2(cs);
1112         rbtree_t *components;
1113         virtual_server_t *server = NULL;
1114         indexed_modcallable *c;
1115
1116         if (name) {
1117                 cf_log_info(cs, "server %s { # from file %s",
1118                             name, cf_section_filename(cs));
1119         } else {
1120                 cf_log_info(cs, "server { # from file %s",
1121                             cf_section_filename(cs));
1122         }
1123
1124         server = talloc_zero(cs, virtual_server_t);
1125         server->name = name;
1126         server->created = time(NULL);
1127         server->cs = cs;
1128         server->components = components = rbtree_create(server, indexed_modcallable_cmp, NULL, 0);
1129         if (!components) {
1130                 ERROR("Failed to initialize components");
1131
1132         error:
1133                 if (debug_flag == 0) {
1134                         ERROR("Failed to load virtual server %s",
1135                               (name != NULL) ? name : "<default>");
1136                 }
1137                 return -1;
1138         }
1139         talloc_set_destructor(server, _virtual_server_free);
1140
1141         /*
1142          *      Loop over all of the known components, finding their
1143          *      configuration section, and loading it.
1144          */
1145         found = 0;
1146         for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) {
1147                 CONF_SECTION *subcs;
1148
1149                 subcs = cf_section_sub_find(cs,
1150                                             section_type_value[comp].section);
1151                 if (!subcs) continue;
1152
1153                 if (!name) {
1154                         cf_log_err_cs(subcs, "The %s section should be inside of a 'server { ... }' block!",
1155                                       section_type_value[comp].section);
1156                 }
1157
1158                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
1159
1160                 /*
1161                  *      Skip pre/post-proxy sections if we're not
1162                  *      proxying.
1163                  */
1164                 if (
1165 #ifdef WITH_PROXY
1166                     !main_config.proxy_requests &&
1167 #endif
1168                     ((comp == RLM_COMPONENT_PRE_PROXY) ||
1169                      (comp == RLM_COMPONENT_POST_PROXY))) {
1170                         continue;
1171                 }
1172
1173 #ifndef WITH_ACCOUNTING
1174                 if (comp == RLM_COMPONENT_ACCT) continue;
1175 #endif
1176
1177 #ifndef WITH_SESSION_MGMT
1178                 if (comp == RLM_COMPONENT_SESS) continue;
1179 #endif
1180
1181                 if (debug_flag <= 3) {
1182                         cf_log_module(cs, "Loading %s {...}",
1183                                       section_type_value[comp].section);
1184                 } else {
1185                         DEBUG(" %s {", section_type_value[comp].section);
1186                 }
1187
1188                 if (load_component_section(subcs, components, comp) < 0) {
1189                         goto error;
1190                 }
1191
1192                 if (debug_flag > 3) {
1193                         DEBUG(" } # %s", section_type_value[comp].section);
1194                 }
1195
1196                 /*
1197                  *      Cache a default, if it exists.  Some people
1198                  *      put empty sections for some reason...
1199                  */
1200                 c = lookup_by_index(components, comp, 0);
1201                 if (c) server->mc[comp] = c->modulelist;
1202
1203                 server->subcs[comp] = subcs;
1204
1205                 found = 1;
1206         } /* loop over components */
1207
1208         /*
1209          *      We haven't loaded any of the normal sections.  Maybe we're
1210          *      supposed to load the vmps section.
1211          *
1212          *      This is a bit of a hack...
1213          */
1214         if (!found) do {
1215 #if defined(WITH_VMPS) || defined(WITH_DHCP)
1216                 CONF_SECTION *subcs;
1217 #endif
1218 #ifdef WITH_DHCP
1219                 DICT_ATTR const *da;
1220 #endif
1221
1222 #ifdef WITH_VMPS
1223                 subcs = cf_section_sub_find(cs, "vmps");
1224                 if (subcs) {
1225                         cf_log_module(cs, "Loading vmps {...}");
1226                         if (load_component_section(subcs, components,
1227                                                    RLM_COMPONENT_POST_AUTH) < 0) {
1228                                 goto error;
1229                         }
1230                         c = lookup_by_index(components,
1231                                             RLM_COMPONENT_POST_AUTH, 0);
1232                         if (c) server->mc[RLM_COMPONENT_POST_AUTH] = c->modulelist;
1233                         break;
1234                 }
1235 #endif
1236
1237 #ifdef WITH_DHCP
1238                 /*
1239                  *      It's OK to not have DHCP.
1240                  */
1241                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1242                 if (!subcs) break;
1243
1244                 da = dict_attrbyname("DHCP-Message-Type");
1245
1246                 /*
1247                  *      Handle each DHCP Message type separately.
1248                  */
1249                 while (subcs) {
1250                         char const *name2 = cf_section_name2(subcs);
1251
1252                         if (name2) {
1253                                 cf_log_module(cs, "Loading dhcp %s {...}", name2);
1254                         } else {
1255                                 cf_log_module(cs, "Loading dhcp {...}");
1256                         }
1257                         if (!load_subcomponent_section(subcs,
1258                                                        components,
1259                                                        da,
1260                                                        RLM_COMPONENT_POST_AUTH)) {
1261                                 goto error; /* FIXME: memleak? */
1262                         }
1263                         c = lookup_by_index(components,
1264                                             RLM_COMPONENT_POST_AUTH, 0);
1265                         if (c) server->mc[RLM_COMPONENT_POST_AUTH] = c->modulelist;
1266
1267                         subcs = cf_subsection_find_next(cs, subcs, "dhcp");
1268                 }
1269 #endif
1270         } while (0);
1271
1272         if (name) {
1273                 cf_log_info(cs, "} # server %s", name);
1274         } else {
1275                 cf_log_info(cs, "} # server");
1276         }
1277
1278         if (debug_flag == 0) {
1279                 INFO("Loaded virtual server %s",
1280                        (name != NULL) ? name : "<default>");
1281         }
1282
1283         /*
1284          *      Now that it is OK, insert it into the list.
1285          *
1286          *      This is thread-safe...
1287          */
1288         comp = virtual_server_idx(name);
1289         server->next = virtual_servers[comp];
1290         virtual_servers[comp] = server;
1291
1292         /*
1293          *      Mark OLDER ones of the same name as being unused.
1294          */
1295         server = server->next;
1296         while (server) {
1297                 if ((!name && !server->name) ||
1298                     (name && server->name &&
1299                      (strcmp(server->name, name) == 0))) {
1300                         server->can_free = true;
1301                         break;
1302                 }
1303                 server = server->next;
1304         }
1305
1306         return 0;
1307 }
1308
1309
1310 static int pass2_cb(UNUSED void *ctx, void *data)
1311 {
1312         indexed_modcallable *this = data;
1313
1314         if (!modcall_pass2(this->modulelist)) return -1;
1315
1316         return 0;
1317 }
1318
1319 static int pass2_instance_cb(UNUSED void *ctx, void *data)
1320 {
1321         module_instance_t *node = data;
1322
1323         if (!node->entry->module->config || !node->cs) return 0;
1324
1325         if (cf_section_parse_pass2(node->cs, node->insthandle,
1326                                    node->entry->module->config) < 0) {
1327                 return -1;
1328         }
1329
1330         return 0;
1331 }
1332
1333 /*
1334  *      Load all of the virtual servers.
1335  */
1336 int virtual_servers_load(CONF_SECTION *config)
1337 {
1338         CONF_SECTION *cs;
1339         virtual_server_t *server;
1340         static bool first_time = true;
1341
1342         DEBUG2("%s: #### Loading Virtual Servers ####", main_config.name);
1343
1344         /*
1345          *      If we have "server { ...}", then there SHOULD NOT be
1346          *      bare "authorize", etc. sections.  if there is no such
1347          *      server, then try to load the old-style sections first.
1348          *
1349          *      In either case, load the "default" virtual server first.
1350          *      this matches better with users expectations.
1351          */
1352         cs = cf_section_find_name2(cf_subsection_find_next(config, NULL,
1353                                                            "server"),
1354                                    "server", NULL);
1355         if (cs) {
1356                 if (load_byserver(cs) < 0) {
1357                         return -1;
1358                 }
1359         } else {
1360                 if (load_byserver(config) < 0) {
1361                         return -1;
1362                 }
1363         }
1364
1365         /*
1366          *      Load all of the virtual servers.
1367          */
1368         for (cs = cf_subsection_find_next(config, NULL, "server");
1369              cs != NULL;
1370              cs = cf_subsection_find_next(config, cs, "server")) {
1371                 char const *name2;
1372
1373                 name2 = cf_section_name2(cs);
1374                 if (!name2) continue; /* handled above */
1375
1376                 server = virtual_server_find(name2);
1377                 if (server &&
1378                     (cf_top_section(server->cs) == config)) {
1379                         ERROR("Duplicate virtual server \"%s\" in file %s:%d and file %s:%d",
1380                                server->name,
1381                                cf_section_filename(server->cs),
1382                                cf_section_lineno(server->cs),
1383                                cf_section_filename(cs),
1384                                cf_section_lineno(cs));
1385                         return -1;
1386                 }
1387
1388                 if (load_byserver(cs) < 0) {
1389                         /*
1390                          *      Once we successfully started once,
1391                          *      continue loading the OTHER servers,
1392                          *      even if one fails.
1393                          */
1394                         if (!first_time) continue;
1395                         return -1;
1396                 }
1397         }
1398
1399         /*
1400          *      Check all of the module config items which are xlat expanded.
1401          */
1402         if (rbtree_walk(instance_tree, RBTREE_IN_ORDER,
1403                         pass2_instance_cb, NULL) != 0) {
1404                 return -1;
1405         }
1406
1407         /*
1408          *      Try to compile the "authorize", etc. sections which
1409          *      aren't in a virtual server.
1410          */
1411         server = virtual_server_find(NULL);
1412         if (server) {
1413                 int i;
1414
1415                 for (i = RLM_COMPONENT_AUTH; i < RLM_COMPONENT_COUNT; i++) {
1416                         if (!modcall_pass2(server->mc[i])) return -1;
1417                 }
1418
1419                 if (server->components &&
1420                     (rbtree_walk(server->components, RBTREE_IN_ORDER,
1421                                  pass2_cb, NULL) != 0)) {
1422                         return -1;
1423                 }
1424         }
1425
1426         /*
1427          *      Now that we've loaded everything, run pass 2 over the
1428          *      conditions and xlats.
1429          */
1430         for (cs = cf_subsection_find_next(config, NULL, "server");
1431              cs != NULL;
1432              cs = cf_subsection_find_next(config, cs, "server")) {
1433                 int i;
1434                 char const *name2;
1435
1436                 name2 = cf_section_name2(cs);
1437
1438                 server = virtual_server_find(name2);
1439                 if (!server) continue;
1440
1441                 for (i = RLM_COMPONENT_AUTH; i < RLM_COMPONENT_COUNT; i++) {
1442                         if (!modcall_pass2(server->mc[i])) return -1;
1443                 }
1444
1445                 if (server->components &&
1446                     (rbtree_walk(server->components, RBTREE_IN_ORDER,
1447                                  pass2_cb, NULL) != 0)) {
1448                         return -1;
1449                 }
1450         }
1451
1452         /*
1453          *      If we succeed the first time around, remember that.
1454          */
1455         first_time = false;
1456
1457         return 0;
1458 }
1459
1460 int module_hup_module(CONF_SECTION *cs, module_instance_t *node, time_t when)
1461 {
1462         void *insthandle;
1463         fr_module_hup_t *mh;
1464
1465         if (!node ||
1466             !node->entry->module->instantiate ||
1467             ((node->entry->module->type & RLM_TYPE_HUP_SAFE) == 0)) {
1468                 return 1;
1469         }
1470
1471         cf_log_module(cs, "Trying to reload module \"%s\"", node->name);
1472
1473         /*
1474          *      Parse the module configuration, and setup destructors so the
1475          *      module's detach method is called when it's instance data is
1476          *      about to be freed.
1477          */
1478         if (module_conf_parse(node, &insthandle) < 0) {
1479                 cf_log_err_cs(cs, "HUP failed for module \"%s\" (parsing config failed). "
1480                               "Using old configuration", node->name);
1481
1482                 return 0;
1483         }
1484
1485         if ((node->entry->module->instantiate)(cs, insthandle) < 0) {
1486                 cf_log_err_cs(cs, "HUP failed for module \"%s\".  Using old configuration.", node->name);
1487                 talloc_free(insthandle);
1488
1489                 return 0;
1490         }
1491
1492         INFO(" Module: Reloaded module \"%s\"", node->name);
1493
1494         module_instance_free_old(cs, node, when);
1495
1496         /*
1497          *      Save the old instance handle for later deletion.
1498          */
1499         mh = talloc_zero(cs, fr_module_hup_t);
1500         mh->mi = node;
1501         mh->when = when;
1502         mh->insthandle = node->insthandle;
1503         mh->next = node->mh;
1504         node->mh = mh;
1505
1506         node->insthandle = insthandle;
1507
1508         /*
1509          *      FIXME: Set a timeout to come back in 60s, so that
1510          *      we can pro-actively clean up the old instances.
1511          */
1512
1513         return 1;
1514 }
1515
1516
1517 int modules_hup(CONF_SECTION *modules)
1518 {
1519         time_t when;
1520         CONF_ITEM *ci;
1521         CONF_SECTION *cs;
1522         module_instance_t *node;
1523
1524         if (!modules) return 0;
1525
1526         when = time(NULL);
1527
1528         /*
1529          *      Loop over the modules
1530          */
1531         for (ci=cf_item_find_next(modules, NULL);
1532              ci != NULL;
1533              ci=cf_item_find_next(modules, ci)) {
1534                 char const *instname;
1535                 module_instance_t myNode;
1536
1537                 /*
1538                  *      If it's not a section, ignore it.
1539                  */
1540                 if (!cf_item_is_section(ci)) continue;
1541
1542                 cs = cf_item_to_section(ci);
1543                 instname = cf_section_name2(cs);
1544                 if (!instname) instname = cf_section_name1(cs);
1545
1546                 strlcpy(myNode.name, instname, sizeof(myNode.name));
1547                 node = rbtree_finddata(instance_tree, &myNode);
1548
1549                 module_hup_module(cs, node, when);
1550         }
1551
1552         return 1;
1553 }
1554
1555
1556 static int define_type(CONF_SECTION *cs, DICT_ATTR const *da, char const *name)
1557 {
1558         uint32_t value;
1559         DICT_VALUE *dval;
1560
1561         /*
1562          *      If the value already exists, don't
1563          *      create it again.
1564          */
1565         dval = dict_valbyname(da->attr, da->vendor, name);
1566         if (dval) return 1;
1567
1568         /*
1569          *      Create a new unique value with a
1570          *      meaningless number.  You can't look at
1571          *      it from outside of this code, so it
1572          *      doesn't matter.  The only requirement
1573          *      is that it's unique.
1574          */
1575         do {
1576                 value = fr_rand() & 0x00ffffff;
1577         } while (dict_valbyattr(da->attr, da->vendor, value));
1578
1579         cf_log_module(cs, "Creating %s = %s", da->name, name);
1580         if (dict_addvalue(name, da->name, value) < 0) {
1581                 ERROR("%s", fr_strerror());
1582                 return 0;
1583         }
1584
1585         return 1;
1586 }
1587
1588 /*
1589  *      Define Auth-Type, etc. in a server.
1590  */
1591 static bool server_define_types(CONF_SECTION *cs)
1592 {
1593         rlm_components_t        comp;
1594
1595         /*
1596          *      Loop over all of the components
1597          */
1598         for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) {
1599                 CONF_SECTION *subcs;
1600                 CONF_ITEM *modref;
1601                 DICT_ATTR const *da;
1602
1603                 subcs = cf_section_sub_find(cs,
1604                                             section_type_value[comp].section);
1605                 if (!subcs) continue;
1606
1607                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
1608
1609                 /*
1610                  *      Find the attribute used to store VALUEs for this section.
1611                  */
1612                 da = dict_attrbyvalue(section_type_value[comp].attr, 0);
1613                 if (!da) {
1614                         cf_log_err_cs(subcs,
1615                                    "No such attribute %s",
1616                                    section_type_value[comp].typename);
1617                         return false;
1618                 }
1619
1620                 /*
1621                  *      Define dynamic types, so that others can reference
1622                  *      them.
1623                  */
1624                 for (modref = cf_item_find_next(subcs, NULL);
1625                      modref != NULL;
1626                      modref = cf_item_find_next(subcs, modref)) {
1627                         char const *name1;
1628                         CONF_SECTION *subsubcs;
1629
1630                         /*
1631                          *      Create types for simple references
1632                          *      only when parsing the authenticate
1633                          *      section.
1634                          */
1635                         if ((section_type_value[comp].attr == PW_AUTH_TYPE) &&
1636                             cf_item_is_pair(modref)) {
1637                                 CONF_PAIR *cp = cf_item_to_pair(modref);
1638                                 if (!define_type(cs, da, cf_pair_attr(cp))) {
1639                                         return false;
1640                                 }
1641
1642                                 continue;
1643                         }
1644
1645                         if (!cf_item_is_section(modref)) continue;
1646
1647                         subsubcs = cf_item_to_section(modref);
1648                         name1 = cf_section_name1(subsubcs);
1649
1650                         if (strcmp(name1, section_type_value[comp].typename) == 0) {
1651                           if (!define_type(cs, da,
1652                                            cf_section_name2(subsubcs))) {
1653                                   return false;
1654                           }
1655                         }
1656                 }
1657         } /* loop over components */
1658
1659         return true;
1660 }
1661
1662 extern char const *unlang_keyword[];
1663
1664 static bool is_reserved_word(const char *name)
1665 {
1666         int i;
1667
1668         if (!name || !*name) return false;
1669
1670         for (i = 1; unlang_keyword[i] != NULL; i++) {
1671                 if (strcmp(name, unlang_keyword[i]) == 0) return true;
1672         }
1673
1674         return false;
1675 }
1676
1677
1678 /*
1679  *      Parse the module config sections, and load
1680  *      and call each module's init() function.
1681  */
1682 int modules_init(CONF_SECTION *config)
1683 {
1684         CONF_ITEM       *ci, *next;
1685         CONF_SECTION    *cs, *modules;
1686
1687         /*
1688          *      Set up the internal module struct.
1689          */
1690         module_tree = rbtree_create(NULL, module_entry_cmp, NULL, 0);
1691         if (!module_tree) {
1692                 ERROR("Failed to initialize modules\n");
1693                 return -1;
1694         }
1695
1696         instance_tree = rbtree_create(NULL, module_instance_cmp,
1697                                       module_instance_free, 0);
1698         if (!instance_tree) {
1699                 ERROR("Failed to initialize modules\n");
1700                 return -1;
1701         }
1702
1703         memset(virtual_servers, 0, sizeof(virtual_servers));
1704
1705         /*
1706          *      Remember where the modules were stored.
1707          */
1708         modules = cf_section_sub_find(config, "modules");
1709         if (!modules) {
1710                 WARN("Cannot find a \"modules\" section in the configuration file!");
1711         }
1712
1713         /*
1714          *      Load dictionaries.
1715          */
1716         for (cs = cf_subsection_find_next(config, NULL, "server");
1717              cs != NULL;
1718              cs = cf_subsection_find_next(config, cs, "server")) {
1719                 CONF_SECTION *subcs;
1720                 DICT_ATTR const *da;
1721
1722 #ifdef WITH_VMPS
1723                 /*
1724                  *      Auto-load the VMPS/VQP dictionary.
1725                  */
1726                 subcs = cf_section_sub_find(cs, "vmps");
1727                 if (subcs) {
1728                         da = dict_attrbyname("VQP-Packet-Type");
1729                         if (!da) {
1730                                 if (dict_read(main_config.dictionary_dir, "dictionary.vqp") < 0) {
1731                                         ERROR("Failed reading dictionary.vqp: %s",
1732                                               fr_strerror());
1733                                         return -1;
1734                                 }
1735                                 cf_log_module(cs, "Loading dictionary.vqp");
1736
1737                                 da = dict_attrbyname("VQP-Packet-Type");
1738                                 if (!da) {
1739                                         ERROR("No VQP-Packet-Type in dictionary.vqp");
1740                                         return -1;
1741                                 }
1742                         }
1743                 }
1744 #endif
1745
1746 #ifdef WITH_DHCP
1747                 /*
1748                  *      Auto-load the DHCP dictionary.
1749                  */
1750                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1751                 if (subcs) {
1752                         da = dict_attrbyname("DHCP-Message-Type");
1753                         if (!da) {
1754                                 cf_log_module(cs, "Loading dictionary.dhcp");
1755                                 if (dict_read(main_config.dictionary_dir, "dictionary.dhcp") < 0) {
1756                                         ERROR("Failed reading dictionary.dhcp: %s",
1757                                               fr_strerror());
1758                                         return -1;
1759                                 }
1760
1761                                 da = dict_attrbyname("DHCP-Message-Type");
1762                                 if (!da) {
1763                                         ERROR("No DHCP-Message-Type in dictionary.dhcp");
1764                                         return -1;
1765                                 }
1766                         }
1767                 }
1768 #endif
1769                 /*
1770                  *      Else it's a RADIUS virtual server, and the
1771                  *      dictionaries are already loaded.
1772                  */
1773
1774                 /*
1775                  *      Root through each virtual server, defining
1776                  *      Autz-Type and Auth-Type.  This is so that the
1777                  *      modules can reference a particular type.
1778                  */
1779                 if (!server_define_types(cs)) return -1;
1780         }
1781
1782         DEBUG2("%s: #### Instantiating modules ####", main_config.name);
1783
1784         /*
1785          *      Loop over module definitions, looking for duplicates.
1786          *
1787          *      This is O(N^2) in the number of modules, but most
1788          *      systems should have less than 100 modules.
1789          */
1790         for (ci=cf_item_find_next(modules, NULL);
1791              ci != NULL;
1792              ci=next) {
1793                 char const *name1, *name2;
1794                 CONF_SECTION *subcs, *duplicate;
1795
1796                 next = cf_item_find_next(modules, ci);
1797
1798                 if (!cf_item_is_section(ci)) continue;
1799
1800                 if (!next || !cf_item_is_section(next)) continue;
1801
1802                 subcs = cf_item_to_section(ci);
1803                 name1 = cf_section_name1(subcs);
1804                 name2 = cf_section_name2(subcs);
1805
1806                 if (is_reserved_word(name1)) {
1807                         cf_log_err_cs(subcs, "Module cannot be named for an 'unlang' keyword");
1808                         return -1;
1809                 }
1810
1811                 duplicate = cf_section_find_name2(cf_item_to_section(next),
1812                                                   name1, name2);
1813                 if (!duplicate) continue;
1814
1815                 if (!name2) name2 = "";
1816
1817                 ERROR("Duplicate module \"%s %s\", in file %s:%d and file %s:%d",
1818                        name1, name2,
1819                        cf_section_filename(subcs),
1820                        cf_section_lineno(subcs),
1821                        cf_section_filename(duplicate),
1822                        cf_section_lineno(duplicate));
1823                 return -1;
1824         }
1825
1826         /*
1827          *  Look for the 'instantiate' section, which tells us
1828          *  the instantiation order of the modules, and also allows
1829          *  us to load modules with no authorize/authenticate/etc.
1830          *  sections.
1831          */
1832         cs = cf_section_sub_find(config, "instantiate");
1833         if (cs) {
1834                 CONF_PAIR *cp;
1835                 module_instance_t *module;
1836                 char const *name;
1837
1838                 cf_log_info(cs, " instantiate {");
1839
1840                 /*
1841                  *  Loop over the items in the 'instantiate' section.
1842                  */
1843                 for (ci=cf_item_find_next(cs, NULL);
1844                      ci != NULL;
1845                      ci=cf_item_find_next(cs, ci)) {
1846
1847                         /*
1848                          *      Skip sections and "other" stuff.
1849                          *      Sections will be handled later, if
1850                          *      they're referenced at all...
1851                          */
1852                         if (cf_item_is_pair(ci)) {
1853                                 cp = cf_item_to_pair(ci);
1854                                 name = cf_pair_attr(cp);
1855
1856                                 module = find_module_instance(modules, name, true);
1857                                 if (!module && (name[0] != '-')) {
1858                                         return -1;
1859                                 }
1860                         }
1861
1862                         /*
1863                          *      Can only be "redundant" or
1864                          *      "load-balance" or
1865                          *      "redundant-load-balance"
1866                          */
1867                         if (cf_item_is_section(ci)) {
1868                                 bool all_same = true;
1869                                 module_t const *last = NULL;
1870                                 CONF_SECTION *subcs;
1871                                 CONF_ITEM *subci;
1872
1873                                 subcs = cf_item_to_section(ci);
1874                                 name = cf_section_name1(subcs);
1875
1876                                 /*
1877                                  *      Groups, etc. must have a name.
1878                                  */
1879                                 if (((strcmp(name, "group") == 0) ||
1880                                      (strcmp(name, "redundant") == 0) ||
1881                                      (strcmp(name, "redundant-load-balance") == 0) ||
1882                                      strcmp(name, "load-balance") == 0)) {
1883                                         name = cf_section_name2(subcs);
1884                                         if (!name) {
1885                                                 cf_log_err_cs(subcs, "Subsection must have a name");
1886                                                 return -1;
1887                                         }
1888
1889                                         if (is_reserved_word(name)) {
1890                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
1891                                                 return -1;
1892                                         }
1893                                 } else {
1894                                         if (is_reserved_word(name)) {
1895                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
1896                                                 return -1;
1897                                         }
1898                                 }
1899
1900                                 /*
1901                                  *      Ensure that the modules we reference here exist.
1902                                  */
1903                                 for (subci=cf_item_find_next(subcs, NULL);
1904                                      subci != NULL;
1905                                      subci=cf_item_find_next(subcs, subci)) {
1906                                         if (cf_item_is_pair(subci)) {
1907                                                 cp = cf_item_to_pair(subci);
1908                                                 if (cf_pair_value(cp)) {
1909                                                         cf_log_err(subci, "Cannot set return codes in a %s block",
1910                                                                    cf_section_name1(subcs));
1911                                                         return -1;
1912                                                 }
1913
1914                                                 module = find_module_instance(modules, cf_pair_attr(cp), true);
1915                                                 if (!module) {
1916                                                         return -1;
1917                                                 }
1918
1919                                                 if (all_same) {
1920                                                         if (!last) {
1921                                                                 last = module->entry->module;
1922                                                         } else if (last != module->entry->module) {
1923                                                                 last = NULL;
1924                                                                 all_same = false;
1925                                                         }
1926                                                 }
1927                                         } else {
1928                                                 all_same = false;
1929                                         }
1930
1931                                         /*
1932                                          *      Don't check subsections for now.
1933                                          */
1934                                 } /* loop over modules in a "redundant foo" section */
1935
1936                                 /*
1937                                  *      Register a redundant xlat
1938                                  */
1939                                 if (all_same) {
1940                                         if (!xlat_register_redundant(cf_item_to_section(ci))) {
1941                                                 WARN("%s[%d] Not registering expansions for %s",
1942                                                      cf_section_filename(subcs), cf_section_lineno(subcs),
1943                                                      cf_section_name2(subcs));
1944                                         }
1945                                 }
1946                         }  /* handle subsections */
1947                 } /* loop over the "instantiate" section */
1948
1949                 cf_log_info(cs, " }");
1950         } /* if there's an 'instantiate' section. */
1951
1952         /*
1953          *      Now that we've loaded the explicitly ordered modules,
1954          *      load everything in the "modules" section.  This is
1955          *      because we've now split up the modules into
1956          *      mods-enabled.
1957          */
1958         cf_log_info(cs, " modules {");
1959         for (ci=cf_item_find_next(modules, NULL);
1960              ci != NULL;
1961              ci=next) {
1962                 char const *name;
1963                 module_instance_t *module;
1964                 CONF_SECTION *subcs;
1965
1966                 next = cf_item_find_next(modules, ci);
1967
1968                 if (!cf_item_is_section(ci)) continue;
1969
1970                 subcs = cf_item_to_section(ci);
1971                 name = cf_section_name2(subcs);
1972                 if (!name) name = cf_section_name1(subcs);
1973
1974                 module = find_module_instance(modules, name, true);
1975                 if (!module) return -1;
1976         }
1977         cf_log_info(cs, " } # modules");
1978
1979         if (virtual_servers_load(config) < 0) return -1;
1980
1981         return 0;
1982 }
1983
1984 /*
1985  *      Call all authorization modules until one returns
1986  *      somethings else than RLM_MODULE_OK
1987  */
1988 rlm_rcode_t process_authorize(int autz_type, REQUEST *request)
1989 {
1990         return indexed_modcall(RLM_COMPONENT_AUTZ, autz_type, request);
1991 }
1992
1993 /*
1994  *      Authenticate a user/password with various methods.
1995  */
1996 rlm_rcode_t process_authenticate(int auth_type, REQUEST *request)
1997 {
1998         return indexed_modcall(RLM_COMPONENT_AUTH, auth_type, request);
1999 }
2000
2001 #ifdef WITH_ACCOUNTING
2002 /*
2003  *      Do pre-accounting for ALL configured sessions
2004  */
2005 rlm_rcode_t module_preacct(REQUEST *request)
2006 {
2007         return indexed_modcall(RLM_COMPONENT_PREACCT, 0, request);
2008 }
2009
2010 /*
2011  *      Do accounting for ALL configured sessions
2012  */
2013 rlm_rcode_t process_accounting(int acct_type, REQUEST *request)
2014 {
2015         return indexed_modcall(RLM_COMPONENT_ACCT, acct_type, request);
2016 }
2017 #endif
2018
2019 #ifdef WITH_SESSION_MGMT
2020 /*
2021  *      See if a user is already logged in.
2022  *
2023  *      Returns: 0 == OK, 1 == double logins, 2 == multilink attempt
2024  */
2025 int process_checksimul(int sess_type, REQUEST *request, int maxsimul)
2026 {
2027         rlm_rcode_t rcode;
2028
2029         if(!request->username)
2030                 return 0;
2031
2032         request->simul_count = 0;
2033         request->simul_max = maxsimul;
2034         request->simul_mpp = 1;
2035
2036         rcode = indexed_modcall(RLM_COMPONENT_SESS, sess_type, request);
2037
2038         if (rcode != RLM_MODULE_OK) {
2039                 /* FIXME: Good spot for a *rate-limited* warning to the log */
2040                 return 0;
2041         }
2042
2043         return (request->simul_count < maxsimul) ? 0 : request->simul_mpp;
2044 }
2045 #endif
2046
2047 #ifdef WITH_PROXY
2048 /*
2049  *      Do pre-proxying for ALL configured sessions
2050  */
2051 rlm_rcode_t process_pre_proxy(int type, REQUEST *request)
2052 {
2053         return indexed_modcall(RLM_COMPONENT_PRE_PROXY, type, request);
2054 }
2055
2056 /*
2057  *      Do post-proxying for ALL configured sessions
2058  */
2059 rlm_rcode_t process_post_proxy(int type, REQUEST *request)
2060 {
2061         return indexed_modcall(RLM_COMPONENT_POST_PROXY, type, request);
2062 }
2063 #endif
2064
2065 /*
2066  *      Do post-authentication for ALL configured sessions
2067  */
2068 rlm_rcode_t process_post_auth(int postauth_type, REQUEST *request)
2069 {
2070         return indexed_modcall(RLM_COMPONENT_POST_AUTH, postauth_type, request);
2071 }
2072
2073 #ifdef WITH_COA
2074 rlm_rcode_t process_recv_coa(int recv_coa_type, REQUEST *request)
2075 {
2076         return indexed_modcall(RLM_COMPONENT_RECV_COA, recv_coa_type, request);
2077 }
2078
2079 rlm_rcode_t process_send_coa(int send_coa_type, REQUEST *request)
2080 {
2081         return indexed_modcall(RLM_COMPONENT_SEND_COA, send_coa_type, request);
2082 }
2083 #endif