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