Merge pull request #879 from mcnewton/manupdate
[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                            "%s %s Not previously configured",
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 (cf_item_find_next(subcs, NULL) == NULL) continue;
1154
1155                 /*
1156                  *      Skip pre/post-proxy sections if we're not
1157                  *      proxying.
1158                  */
1159                 if (
1160 #ifdef WITH_PROXY
1161                     !main_config.proxy_requests &&
1162 #endif
1163                     ((comp == RLM_COMPONENT_PRE_PROXY) ||
1164                      (comp == RLM_COMPONENT_POST_PROXY))) {
1165                         continue;
1166                 }
1167
1168 #ifndef WITH_ACCOUNTING
1169                 if (comp == RLM_COMPONENT_ACCT) continue;
1170 #endif
1171
1172 #ifndef WITH_SESSION_MGMT
1173                 if (comp == RLM_COMPONENT_SESS) continue;
1174 #endif
1175
1176                 if (debug_flag <= 3) {
1177                         cf_log_module(cs, "Loading %s {...}",
1178                                       section_type_value[comp].section);
1179                 } else {
1180                         DEBUG(" %s {", section_type_value[comp].section);
1181                 }
1182
1183                 if (load_component_section(subcs, components, comp) < 0) {
1184                         goto error;
1185                 }
1186
1187                 if (debug_flag > 3) {
1188                         DEBUG(" } # %s", section_type_value[comp].section);
1189                 }
1190
1191                 /*
1192                  *      Cache a default, if it exists.  Some people
1193                  *      put empty sections for some reason...
1194                  */
1195                 c = lookup_by_index(components, comp, 0);
1196                 if (c) server->mc[comp] = c->modulelist;
1197
1198                 server->subcs[comp] = subcs;
1199
1200                 found = 1;
1201         } /* loop over components */
1202
1203         /*
1204          *      We haven't loaded any of the normal sections.  Maybe we're
1205          *      supposed to load the vmps section.
1206          *
1207          *      This is a bit of a hack...
1208          */
1209         if (!found) do {
1210 #if defined(WITH_VMPS) || defined(WITH_DHCP)
1211                 CONF_SECTION *subcs;
1212 #endif
1213 #ifdef WITH_DHCP
1214                 DICT_ATTR const *da;
1215 #endif
1216
1217 #ifdef WITH_VMPS
1218                 subcs = cf_section_sub_find(cs, "vmps");
1219                 if (subcs) {
1220                         cf_log_module(cs, "Loading vmps {...}");
1221                         if (load_component_section(subcs, components,
1222                                                    RLM_COMPONENT_POST_AUTH) < 0) {
1223                                 goto error;
1224                         }
1225                         c = lookup_by_index(components,
1226                                             RLM_COMPONENT_POST_AUTH, 0);
1227                         if (c) server->mc[RLM_COMPONENT_POST_AUTH] = c->modulelist;
1228                         break;
1229                 }
1230 #endif
1231
1232 #ifdef WITH_DHCP
1233                 /*
1234                  *      It's OK to not have DHCP.
1235                  */
1236                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1237                 if (!subcs) break;
1238
1239                 da = dict_attrbyname("DHCP-Message-Type");
1240
1241                 /*
1242                  *      Handle each DHCP Message type separately.
1243                  */
1244                 while (subcs) {
1245                         char const *name2 = cf_section_name2(subcs);
1246
1247                         if (name2) {
1248                                 cf_log_module(cs, "Loading dhcp %s {...}", name2);
1249                         } else {
1250                                 cf_log_module(cs, "Loading dhcp {...}");
1251                         }
1252                         if (!load_subcomponent_section(subcs,
1253                                                        components,
1254                                                        da,
1255                                                        RLM_COMPONENT_POST_AUTH)) {
1256                                 goto error; /* FIXME: memleak? */
1257                         }
1258                         c = lookup_by_index(components,
1259                                             RLM_COMPONENT_POST_AUTH, 0);
1260                         if (c) server->mc[RLM_COMPONENT_POST_AUTH] = c->modulelist;
1261
1262                         subcs = cf_subsection_find_next(cs, subcs, "dhcp");
1263                 }
1264 #endif
1265         } while (0);
1266
1267         if (name) {
1268                 cf_log_info(cs, "} # server %s", name);
1269         } else {
1270                 cf_log_info(cs, "} # server");
1271         }
1272
1273         if (debug_flag == 0) {
1274                 INFO("Loaded virtual server %s",
1275                        (name != NULL) ? name : "<default>");
1276         }
1277
1278         /*
1279          *      Now that it is OK, insert it into the list.
1280          *
1281          *      This is thread-safe...
1282          */
1283         comp = virtual_server_idx(name);
1284         server->next = virtual_servers[comp];
1285         virtual_servers[comp] = server;
1286
1287         /*
1288          *      Mark OLDER ones of the same name as being unused.
1289          */
1290         server = server->next;
1291         while (server) {
1292                 if ((!name && !server->name) ||
1293                     (name && server->name &&
1294                      (strcmp(server->name, name) == 0))) {
1295                         server->can_free = true;
1296                         break;
1297                 }
1298                 server = server->next;
1299         }
1300
1301         return 0;
1302 }
1303
1304
1305 static int pass2_cb(UNUSED void *ctx, void *data)
1306 {
1307         indexed_modcallable *this = data;
1308
1309         if (!modcall_pass2(this->modulelist)) return -1;
1310
1311         return 0;
1312 }
1313
1314 static int pass2_instance_cb(UNUSED void *ctx, void *data)
1315 {
1316         module_instance_t *node = data;
1317
1318         if (!node->entry->module->config || !node->cs) return 0;
1319
1320         if (cf_section_parse_pass2(node->cs, node->insthandle,
1321                                    node->entry->module->config) < 0) {
1322                 return -1;
1323         }
1324
1325         return 0;
1326 }
1327
1328 /*
1329  *      Load all of the virtual servers.
1330  */
1331 int virtual_servers_load(CONF_SECTION *config)
1332 {
1333         CONF_SECTION *cs;
1334         virtual_server_t *server;
1335         static bool first_time = true;
1336
1337         DEBUG2("%s: #### Loading Virtual Servers ####", main_config.name);
1338
1339         /*
1340          *      If we have "server { ...}", then there SHOULD NOT be
1341          *      bare "authorize", etc. sections.  if there is no such
1342          *      server, then try to load the old-style sections first.
1343          *
1344          *      In either case, load the "default" virtual server first.
1345          *      this matches better with users expectations.
1346          */
1347         cs = cf_section_find_name2(cf_subsection_find_next(config, NULL,
1348                                                            "server"),
1349                                    "server", NULL);
1350         if (cs) {
1351                 if (load_byserver(cs) < 0) {
1352                         return -1;
1353                 }
1354         } else {
1355                 if (load_byserver(config) < 0) {
1356                         return -1;
1357                 }
1358         }
1359
1360         /*
1361          *      Load all of the virtual servers.
1362          */
1363         for (cs = cf_subsection_find_next(config, NULL, "server");
1364              cs != NULL;
1365              cs = cf_subsection_find_next(config, cs, "server")) {
1366                 char const *name2;
1367
1368                 name2 = cf_section_name2(cs);
1369                 if (!name2) continue; /* handled above */
1370
1371                 server = virtual_server_find(name2);
1372                 if (server &&
1373                     (cf_top_section(server->cs) == config)) {
1374                         ERROR("Duplicate virtual server \"%s\" in file %s:%d and file %s:%d",
1375                                server->name,
1376                                cf_section_filename(server->cs),
1377                                cf_section_lineno(server->cs),
1378                                cf_section_filename(cs),
1379                                cf_section_lineno(cs));
1380                         return -1;
1381                 }
1382
1383                 if (load_byserver(cs) < 0) {
1384                         /*
1385                          *      Once we successfully started once,
1386                          *      continue loading the OTHER servers,
1387                          *      even if one fails.
1388                          */
1389                         if (!first_time) continue;
1390                         return -1;
1391                 }
1392         }
1393
1394         /*
1395          *      Check all of the module config items which are xlat expanded.
1396          */
1397         if (rbtree_walk(instance_tree, RBTREE_IN_ORDER,
1398                         pass2_instance_cb, NULL) != 0) {
1399                 return -1;
1400         }
1401
1402         /*
1403          *      Now that we've loaded everything, run pass 2 over the
1404          *      conditions and xlats.
1405          */
1406         for (cs = cf_subsection_find_next(config, NULL, "server");
1407              cs != NULL;
1408              cs = cf_subsection_find_next(config, cs, "server")) {
1409                 int i;
1410                 char const *name2;
1411
1412                 name2 = cf_section_name2(cs);
1413
1414                 server = virtual_server_find(name2);
1415                 if (!server) continue;
1416
1417                 for (i = RLM_COMPONENT_AUTH; i < RLM_COMPONENT_COUNT; i++) {
1418                         if (!modcall_pass2(server->mc[i])) return -1;
1419
1420                 }
1421
1422                 if (server->components &&
1423                     (rbtree_walk(server->components, RBTREE_IN_ORDER,
1424                                  pass2_cb, NULL) != 0)) {
1425                         return -1;
1426                 }
1427         }
1428
1429         /*
1430          *      If we succeed the first time around, remember that.
1431          */
1432         first_time = false;
1433
1434         return 0;
1435 }
1436
1437 int module_hup_module(CONF_SECTION *cs, module_instance_t *node, time_t when)
1438 {
1439         void *insthandle;
1440         fr_module_hup_t *mh;
1441
1442         if (!node ||
1443             !node->entry->module->instantiate ||
1444             ((node->entry->module->type & RLM_TYPE_HUP_SAFE) == 0)) {
1445                 return 1;
1446         }
1447
1448         cf_log_module(cs, "Trying to reload module \"%s\"", node->name);
1449
1450         /*
1451          *      Parse the module configuration, and setup destructors so the
1452          *      module's detach method is called when it's instance data is
1453          *      about to be freed.
1454          */
1455         if (module_conf_parse(node, &insthandle) < 0) {
1456                 cf_log_err_cs(cs, "HUP failed for module \"%s\" (parsing config failed). "
1457                               "Using old configuration", node->name);
1458
1459                 return 0;
1460         }
1461
1462         if ((node->entry->module->instantiate)(cs, insthandle) < 0) {
1463                 cf_log_err_cs(cs, "HUP failed for module \"%s\".  Using old configuration.", node->name);
1464                 talloc_free(insthandle);
1465
1466                 return 0;
1467         }
1468
1469         INFO(" Module: Reloaded module \"%s\"", node->name);
1470
1471         module_instance_free_old(cs, node, when);
1472
1473         /*
1474          *      Save the old instance handle for later deletion.
1475          */
1476         mh = talloc_zero(cs, fr_module_hup_t);
1477         mh->mi = node;
1478         mh->when = when;
1479         mh->insthandle = node->insthandle;
1480         mh->next = node->mh;
1481         node->mh = mh;
1482
1483         node->insthandle = insthandle;
1484
1485         /*
1486          *      FIXME: Set a timeout to come back in 60s, so that
1487          *      we can pro-actively clean up the old instances.
1488          */
1489
1490         return 1;
1491 }
1492
1493
1494 int modules_hup(CONF_SECTION *modules)
1495 {
1496         time_t when;
1497         CONF_ITEM *ci;
1498         CONF_SECTION *cs;
1499         module_instance_t *node;
1500
1501         if (!modules) return 0;
1502
1503         when = time(NULL);
1504
1505         /*
1506          *      Loop over the modules
1507          */
1508         for (ci=cf_item_find_next(modules, NULL);
1509              ci != NULL;
1510              ci=cf_item_find_next(modules, ci)) {
1511                 char const *instname;
1512                 module_instance_t myNode;
1513
1514                 /*
1515                  *      If it's not a section, ignore it.
1516                  */
1517                 if (!cf_item_is_section(ci)) continue;
1518
1519                 cs = cf_item_to_section(ci);
1520                 instname = cf_section_name2(cs);
1521                 if (!instname) instname = cf_section_name1(cs);
1522
1523                 strlcpy(myNode.name, instname, sizeof(myNode.name));
1524                 node = rbtree_finddata(instance_tree, &myNode);
1525
1526                 module_hup_module(cs, node, when);
1527         }
1528
1529         return 1;
1530 }
1531
1532
1533 static int define_type(CONF_SECTION *cs, DICT_ATTR const *da, char const *name)
1534 {
1535         uint32_t value;
1536         DICT_VALUE *dval;
1537
1538         /*
1539          *      If the value already exists, don't
1540          *      create it again.
1541          */
1542         dval = dict_valbyname(da->attr, da->vendor, name);
1543         if (dval) return 1;
1544
1545         /*
1546          *      Create a new unique value with a
1547          *      meaningless number.  You can't look at
1548          *      it from outside of this code, so it
1549          *      doesn't matter.  The only requirement
1550          *      is that it's unique.
1551          */
1552         do {
1553                 value = fr_rand() & 0x00ffffff;
1554         } while (dict_valbyattr(da->attr, da->vendor, value));
1555
1556         cf_log_module(cs, "Creating %s = %s", da->name, name);
1557         if (dict_addvalue(name, da->name, value) < 0) {
1558                 ERROR("%s", fr_strerror());
1559                 return 0;
1560         }
1561
1562         return 1;
1563 }
1564
1565 /*
1566  *      Define Auth-Type, etc. in a server.
1567  */
1568 static bool server_define_types(CONF_SECTION *cs)
1569 {
1570         rlm_components_t        comp;
1571
1572         /*
1573          *      Loop over all of the components
1574          */
1575         for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) {
1576                 CONF_SECTION *subcs;
1577                 CONF_ITEM *modref;
1578                 DICT_ATTR const *da;
1579
1580                 subcs = cf_section_sub_find(cs,
1581                                             section_type_value[comp].section);
1582                 if (!subcs) continue;
1583
1584                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
1585
1586                 /*
1587                  *      Find the attribute used to store VALUEs for this section.
1588                  */
1589                 da = dict_attrbyvalue(section_type_value[comp].attr, 0);
1590                 if (!da) {
1591                         cf_log_err_cs(subcs,
1592                                    "No such attribute %s",
1593                                    section_type_value[comp].typename);
1594                         return false;
1595                 }
1596
1597                 /*
1598                  *      Define dynamic types, so that others can reference
1599                  *      them.
1600                  */
1601                 for (modref = cf_item_find_next(subcs, NULL);
1602                      modref != NULL;
1603                      modref = cf_item_find_next(subcs, modref)) {
1604                         char const *name1;
1605                         CONF_SECTION *subsubcs;
1606
1607                         /*
1608                          *      Create types for simple references
1609                          *      only when parsing the authenticate
1610                          *      section.
1611                          */
1612                         if ((section_type_value[comp].attr == PW_AUTH_TYPE) &&
1613                             cf_item_is_pair(modref)) {
1614                                 CONF_PAIR *cp = cf_item_to_pair(modref);
1615                                 if (!define_type(cs, da, cf_pair_attr(cp))) {
1616                                         return false;
1617                                 }
1618
1619                                 continue;
1620                         }
1621
1622                         if (!cf_item_is_section(modref)) continue;
1623
1624                         subsubcs = cf_item_to_section(modref);
1625                         name1 = cf_section_name1(subsubcs);
1626
1627                         if (strcmp(name1, section_type_value[comp].typename) == 0) {
1628                           if (!define_type(cs, da,
1629                                            cf_section_name2(subsubcs))) {
1630                                   return false;
1631                           }
1632                         }
1633                 }
1634         } /* loop over components */
1635
1636         return true;
1637 }
1638
1639 extern char const *unlang_keyword[];
1640
1641 static bool is_reserved_word(const char *name)
1642 {
1643         int i;
1644
1645         if (!name || !*name) return false;
1646
1647         for (i = 1; unlang_keyword[i] != NULL; i++) {
1648                 if (strcmp(name, unlang_keyword[i]) == 0) return true;
1649         }
1650
1651         return false;
1652 }
1653
1654
1655 /*
1656  *      Parse the module config sections, and load
1657  *      and call each module's init() function.
1658  */
1659 int modules_init(CONF_SECTION *config)
1660 {
1661         CONF_ITEM       *ci, *next;
1662         CONF_SECTION    *cs, *modules;
1663
1664         /*
1665          *      Set up the internal module struct.
1666          */
1667         module_tree = rbtree_create(NULL, module_entry_cmp, NULL, 0);
1668         if (!module_tree) {
1669                 ERROR("Failed to initialize modules\n");
1670                 return -1;
1671         }
1672
1673         instance_tree = rbtree_create(NULL, module_instance_cmp,
1674                                       module_instance_free, 0);
1675         if (!instance_tree) {
1676                 ERROR("Failed to initialize modules\n");
1677                 return -1;
1678         }
1679
1680         memset(virtual_servers, 0, sizeof(virtual_servers));
1681
1682         /*
1683          *      Remember where the modules were stored.
1684          */
1685         modules = cf_section_sub_find(config, "modules");
1686         if (!modules) {
1687                 WARN("Cannot find a \"modules\" section in the configuration file!");
1688         }
1689
1690         /*
1691          *      Load dictionaries.
1692          */
1693         for (cs = cf_subsection_find_next(config, NULL, "server");
1694              cs != NULL;
1695              cs = cf_subsection_find_next(config, cs, "server")) {
1696                 CONF_SECTION *subcs;
1697                 DICT_ATTR const *da;
1698
1699 #ifdef WITH_VMPS
1700                 /*
1701                  *      Auto-load the VMPS/VQP dictionary.
1702                  */
1703                 subcs = cf_section_sub_find(cs, "vmps");
1704                 if (subcs) {
1705                         da = dict_attrbyname("VQP-Packet-Type");
1706                         if (!da) {
1707                                 if (dict_read(main_config.dictionary_dir, "dictionary.vqp") < 0) {
1708                                         ERROR("Failed reading dictionary.vqp: %s",
1709                                               fr_strerror());
1710                                         return -1;
1711                                 }
1712                                 cf_log_module(cs, "Loading dictionary.vqp");
1713
1714                                 da = dict_attrbyname("VQP-Packet-Type");
1715                                 if (!da) {
1716                                         ERROR("No VQP-Packet-Type in dictionary.vqp");
1717                                         return -1;
1718                                 }
1719                         }
1720                 }
1721 #endif
1722
1723 #ifdef WITH_DHCP
1724                 /*
1725                  *      Auto-load the DHCP dictionary.
1726                  */
1727                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1728                 if (subcs) {
1729                         da = dict_attrbyname("DHCP-Message-Type");
1730                         if (!da) {
1731                                 cf_log_module(cs, "Loading dictionary.dhcp");
1732                                 if (dict_read(main_config.dictionary_dir, "dictionary.dhcp") < 0) {
1733                                         ERROR("Failed reading dictionary.dhcp: %s",
1734                                               fr_strerror());
1735                                         return -1;
1736                                 }
1737
1738                                 da = dict_attrbyname("DHCP-Message-Type");
1739                                 if (!da) {
1740                                         ERROR("No DHCP-Message-Type in dictionary.dhcp");
1741                                         return -1;
1742                                 }
1743                         }
1744                 }
1745 #endif
1746                 /*
1747                  *      Else it's a RADIUS virtual server, and the
1748                  *      dictionaries are already loaded.
1749                  */
1750
1751                 /*
1752                  *      Root through each virtual server, defining
1753                  *      Autz-Type and Auth-Type.  This is so that the
1754                  *      modules can reference a particular type.
1755                  */
1756                 if (!server_define_types(cs)) return -1;
1757         }
1758
1759         DEBUG2("%s: #### Instantiating modules ####", main_config.name);
1760
1761         /*
1762          *      Loop over module definitions, looking for duplicates.
1763          *
1764          *      This is O(N^2) in the number of modules, but most
1765          *      systems should have less than 100 modules.
1766          */
1767         for (ci=cf_item_find_next(modules, NULL);
1768              ci != NULL;
1769              ci=next) {
1770                 char const *name1, *name2;
1771                 CONF_SECTION *subcs, *duplicate;
1772
1773                 next = cf_item_find_next(modules, ci);
1774
1775                 if (!cf_item_is_section(ci)) continue;
1776
1777                 if (!next || !cf_item_is_section(next)) continue;
1778
1779                 subcs = cf_item_to_section(ci);
1780                 name1 = cf_section_name1(subcs);
1781                 name2 = cf_section_name2(subcs);
1782
1783                 if (is_reserved_word(name1)) {
1784                         cf_log_err_cs(subcs, "Module cannot be named for an 'unlang' keyword");
1785                         return -1;
1786                 }
1787
1788                 duplicate = cf_section_find_name2(cf_item_to_section(next),
1789                                                   name1, name2);
1790                 if (!duplicate) continue;
1791
1792                 if (!name2) name2 = "";
1793
1794                 ERROR("Duplicate module \"%s %s\", in file %s:%d and file %s:%d",
1795                        name1, name2,
1796                        cf_section_filename(subcs),
1797                        cf_section_lineno(subcs),
1798                        cf_section_filename(duplicate),
1799                        cf_section_lineno(duplicate));
1800                 return -1;
1801         }
1802
1803         /*
1804          *  Look for the 'instantiate' section, which tells us
1805          *  the instantiation order of the modules, and also allows
1806          *  us to load modules with no authorize/authenticate/etc.
1807          *  sections.
1808          */
1809         cs = cf_section_sub_find(config, "instantiate");
1810         if (cs) {
1811                 CONF_PAIR *cp;
1812                 module_instance_t *module;
1813                 char const *name;
1814
1815                 cf_log_info(cs, " instantiate {");
1816
1817                 /*
1818                  *  Loop over the items in the 'instantiate' section.
1819                  */
1820                 for (ci=cf_item_find_next(cs, NULL);
1821                      ci != NULL;
1822                      ci=cf_item_find_next(cs, ci)) {
1823
1824                         /*
1825                          *      Skip sections and "other" stuff.
1826                          *      Sections will be handled later, if
1827                          *      they're referenced at all...
1828                          */
1829                         if (cf_item_is_pair(ci)) {
1830                                 cp = cf_item_to_pair(ci);
1831                                 name = cf_pair_attr(cp);
1832
1833                                 module = find_module_instance(modules, name, true);
1834                                 if (!module && (name[0] != '-')) {
1835                                         return -1;
1836                                 }
1837                         }
1838
1839                         /*
1840                          *      Can only be "redundant" or
1841                          *      "load-balance" or
1842                          *      "redundant-load-balance"
1843                          */
1844                         if (cf_item_is_section(ci)) {
1845                                 bool all_same = true;
1846                                 module_t const *last = NULL;
1847                                 CONF_SECTION *subcs;
1848                                 CONF_ITEM *subci;
1849
1850                                 subcs = cf_item_to_section(ci);
1851                                 name = cf_section_name1(subcs);
1852
1853                                 /*
1854                                  *      Groups, etc. must have a name.
1855                                  */
1856                                 if (((strcmp(name, "group") == 0) ||
1857                                      (strcmp(name, "redundant") == 0) ||
1858                                      (strcmp(name, "redundant-load-balance") == 0) ||
1859                                      strcmp(name, "load-balance") == 0)) {
1860                                         name = cf_section_name2(subcs);
1861                                         if (!name) {
1862                                                 cf_log_err_cs(subcs, "Subsection must have a name");
1863                                                 return -1;
1864                                         }
1865
1866                                         if (is_reserved_word(name)) {
1867                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
1868                                                 return -1;
1869                                         }
1870                                 } else {
1871                                         if (is_reserved_word(name)) {
1872                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
1873                                                 return -1;
1874                                         }
1875                                 }
1876
1877                                 /*
1878                                  *      Ensure that the modules we reference here exist.
1879                                  */
1880                                 for (subci=cf_item_find_next(subcs, NULL);
1881                                      subci != NULL;
1882                                      subci=cf_item_find_next(subcs, subci)) {
1883                                         if (cf_item_is_pair(subci)) {
1884                                                 cp = cf_item_to_pair(subci);
1885                                                 if (cf_pair_value(cp)) {
1886                                                         cf_log_err(subci, "Cannot set return codes in a %s block",
1887                                                                    cf_section_name1(subcs));
1888                                                         return -1;
1889                                                 }
1890
1891                                                 module = find_module_instance(modules, cf_pair_attr(cp), true);
1892                                                 if (!module) {
1893                                                         return -1;
1894                                                 }
1895
1896                                                 if (all_same) {
1897                                                         if (!last) {
1898                                                                 last = module->entry->module;
1899                                                         } else if (last != module->entry->module) {
1900                                                                 last = NULL;
1901                                                                 all_same = false;
1902                                                         }
1903                                                 }
1904                                         } else {
1905                                                 all_same = false;
1906                                         }
1907
1908                                         /*
1909                                          *      Don't check subsections for now.
1910                                          */
1911                                 } /* loop over modules in a "redundant foo" section */
1912
1913                                 /*
1914                                  *      Register a redundant xlat
1915                                  */
1916                                 if (all_same) {
1917                                         if (!xlat_register_redundant(cf_item_to_section(ci))) {
1918                                                 WARN("%s[%d] Not registering expansions for %s",
1919                                                      cf_section_filename(subcs), cf_section_lineno(subcs),
1920                                                      cf_section_name2(subcs));
1921                                         }
1922                                 }
1923                         }  /* handle subsections */
1924                 } /* loop over the "instantiate" section */
1925
1926                 cf_log_info(cs, " }");
1927         } /* if there's an 'instantiate' section. */
1928
1929         /*
1930          *      Now that we've loaded the explicitly ordered modules,
1931          *      load everything in the "modules" section.  This is
1932          *      because we've now split up the modules into
1933          *      mods-enabled.
1934          */
1935         cf_log_info(cs, " modules {");
1936         for (ci=cf_item_find_next(modules, NULL);
1937              ci != NULL;
1938              ci=next) {
1939                 char const *name;
1940                 module_instance_t *module;
1941                 CONF_SECTION *subcs;
1942
1943                 next = cf_item_find_next(modules, ci);
1944
1945                 if (!cf_item_is_section(ci)) continue;
1946
1947                 subcs = cf_item_to_section(ci);
1948                 name = cf_section_name2(subcs);
1949                 if (!name) name = cf_section_name1(subcs);
1950
1951                 module = find_module_instance(modules, name, true);
1952                 if (!module) return -1;
1953         }
1954         cf_log_info(cs, " } # modules");
1955
1956         if (virtual_servers_load(config) < 0) return -1;
1957
1958         return 0;
1959 }
1960
1961 /*
1962  *      Call all authorization modules until one returns
1963  *      somethings else than RLM_MODULE_OK
1964  */
1965 rlm_rcode_t process_authorize(int autz_type, REQUEST *request)
1966 {
1967         return indexed_modcall(RLM_COMPONENT_AUTZ, autz_type, request);
1968 }
1969
1970 /*
1971  *      Authenticate a user/password with various methods.
1972  */
1973 rlm_rcode_t process_authenticate(int auth_type, REQUEST *request)
1974 {
1975         return indexed_modcall(RLM_COMPONENT_AUTH, auth_type, request);
1976 }
1977
1978 #ifdef WITH_ACCOUNTING
1979 /*
1980  *      Do pre-accounting for ALL configured sessions
1981  */
1982 rlm_rcode_t module_preacct(REQUEST *request)
1983 {
1984         return indexed_modcall(RLM_COMPONENT_PREACCT, 0, request);
1985 }
1986
1987 /*
1988  *      Do accounting for ALL configured sessions
1989  */
1990 rlm_rcode_t process_accounting(int acct_type, REQUEST *request)
1991 {
1992         return indexed_modcall(RLM_COMPONENT_ACCT, acct_type, request);
1993 }
1994 #endif
1995
1996 #ifdef WITH_SESSION_MGMT
1997 /*
1998  *      See if a user is already logged in.
1999  *
2000  *      Returns: 0 == OK, 1 == double logins, 2 == multilink attempt
2001  */
2002 int process_checksimul(int sess_type, REQUEST *request, int maxsimul)
2003 {
2004         rlm_rcode_t rcode;
2005
2006         if(!request->username)
2007                 return 0;
2008
2009         request->simul_count = 0;
2010         request->simul_max = maxsimul;
2011         request->simul_mpp = 1;
2012
2013         rcode = indexed_modcall(RLM_COMPONENT_SESS, sess_type, request);
2014
2015         if (rcode != RLM_MODULE_OK) {
2016                 /* FIXME: Good spot for a *rate-limited* warning to the log */
2017                 return 0;
2018         }
2019
2020         return (request->simul_count < maxsimul) ? 0 : request->simul_mpp;
2021 }
2022 #endif
2023
2024 #ifdef WITH_PROXY
2025 /*
2026  *      Do pre-proxying for ALL configured sessions
2027  */
2028 rlm_rcode_t process_pre_proxy(int type, REQUEST *request)
2029 {
2030         return indexed_modcall(RLM_COMPONENT_PRE_PROXY, type, request);
2031 }
2032
2033 /*
2034  *      Do post-proxying for ALL configured sessions
2035  */
2036 rlm_rcode_t process_post_proxy(int type, REQUEST *request)
2037 {
2038         return indexed_modcall(RLM_COMPONENT_POST_PROXY, type, request);
2039 }
2040 #endif
2041
2042 /*
2043  *      Do post-authentication for ALL configured sessions
2044  */
2045 rlm_rcode_t process_post_auth(int postauth_type, REQUEST *request)
2046 {
2047         return indexed_modcall(RLM_COMPONENT_POST_AUTH, postauth_type, request);
2048 }
2049
2050 #ifdef WITH_COA
2051 rlm_rcode_t process_recv_coa(int recv_coa_type, REQUEST *request)
2052 {
2053         return indexed_modcall(RLM_COMPONENT_RECV_COA, recv_coa_type, request);
2054 }
2055
2056 rlm_rcode_t process_send_coa(int send_coa_type, REQUEST *request)
2057 {
2058         return indexed_modcall(RLM_COMPONENT_SEND_COA, send_coa_type, request);
2059 }
2060 #endif