Replaced DEBUG2 stuff with log of config/modules, to make it
[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 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/modpriv.h>
30 #include <freeradius-devel/modcall.h>
31 #include <freeradius-devel/rad_assert.h>
32
33 extern int check_config;
34
35 typedef struct indexed_modcallable {
36         const           char *server;
37         int             comp;
38         int             idx;
39         modcallable     *modulelist;
40 } indexed_modcallable;
41
42 /*
43  *      For each component, keep an ordered list of ones to call.
44  */
45 static rbtree_t *components = NULL;
46
47 static rbtree_t *module_tree = NULL;
48
49 static rbtree_t *instance_tree = NULL;
50
51 typedef struct section_type_value_t {
52         const char      *section;
53         const char      *typename;
54         int             attr;
55 } section_type_value_t;
56
57
58 /*
59  *      Ordered by component
60  */
61 static const section_type_value_t section_type_value[RLM_COMPONENT_COUNT] = {
62         { "authenticate", "Auth-Type",       PW_AUTH_TYPE },
63         { "authorize",    "Autz-Type",       PW_AUTZ_TYPE },
64         { "preacct",      "Pre-Acct-Type",   PW_PRE_ACCT_TYPE },
65         { "accounting",   "Acct-Type",       PW_ACCT_TYPE },
66         { "session",      "Session-Type",    PW_SESSION_TYPE },
67         { "pre-proxy",    "Pre-Proxy-Type",  PW_PRE_PROXY_TYPE },
68         { "post-proxy",   "Post-Proxy-Type", PW_POST_PROXY_TYPE },
69         { "post-auth",    "Post-Auth-Type",  PW_POST_AUTH_TYPE },
70 };
71
72 static void indexed_modcallable_free(void *data)
73 {
74         indexed_modcallable *c = data;
75
76         modcallable_free(&c->modulelist);
77         free(c);
78 }
79
80 static int indexed_modcallable_cmp(const void *one, const void *two)
81 {
82         int rcode;
83         const indexed_modcallable *a = one;
84         const indexed_modcallable *b = two;
85
86         if (a->server && !b->server) return -1;
87         if (!a->server && b->server) return +1;
88         if (a->server && b->server) {
89                 rcode = strcmp(a->server, b->server);
90                 if (rcode != 0) return rcode;
91         }
92
93         if (a->comp < b->comp) return -1;
94         if (a->comp >  b->comp) return +1;
95
96         return a->idx - b->idx;
97 }
98
99
100 /*
101  *      Compare two module entries
102  */
103 static int module_instance_cmp(const void *one, const void *two)
104 {
105         const module_instance_t *a = one;
106         const module_instance_t *b = two;
107
108         return strcmp(a->name, b->name);
109 }
110
111
112 /*
113  *      Free a module instance.
114  */
115 static void module_instance_free(void *data)
116 {
117         module_instance_t *this = data;
118
119         if (this->entry->module->detach) {
120                 int i;
121
122                 (this->entry->module->detach)(this->insthandle);
123                 for (i = 0; i < 16; i++) {
124                         if (this->old_insthandle[i]) {
125                                 (this->entry->module->detach)(this->old_insthandle[i]);
126                         }
127                 }
128         }
129
130 #ifdef HAVE_PTHREAD_H
131         if (this->mutex) {
132                 /*
133                  *      FIXME
134                  *      The mutex MIGHT be locked...
135                  *      we'll check for that later, I guess.
136                  */
137                 pthread_mutex_destroy(this->mutex);
138                 free(this->mutex);
139         }
140 #endif
141         memset(this, 0, sizeof(*this));
142         free(this);
143 }
144
145
146 /*
147  *      Compare two module entries
148  */
149 static int module_entry_cmp(const void *one, const void *two)
150 {
151         const module_entry_t *a = one;
152         const module_entry_t *b = two;
153
154         return strcmp(a->name, b->name);
155 }
156
157 /*
158  *      Free a module entry.
159  */
160 static void module_entry_free(void *data)
161 {
162         module_entry_t *this = data;
163
164         lt_dlclose(this->handle);       /* ignore any errors */
165         memset(this, 0, sizeof(*this));
166         free(this);
167 }
168
169
170 /*
171  *      Remove the module lists.
172  */
173 int detach_modules(void)
174 {
175         rbtree_free(instance_tree);
176         rbtree_free(components);
177         rbtree_free(module_tree);
178
179         lt_dlexit();
180
181         return 0;
182 }
183
184
185 /*
186  *      Find a module on disk or in memory, and link to it.
187  */
188 static module_entry_t *linkto_module(const char *module_name,
189                                      CONF_SECTION *cs)
190 {
191         module_entry_t myentry;
192         module_entry_t *node;
193         lt_dlhandle handle;
194         char module_struct[256];
195         char *p;
196         const module_t *module;
197
198         strlcpy(myentry.name, module_name, sizeof(myentry.name));
199         node = rbtree_finddata(module_tree, &myentry);
200         if (node) return node;
201
202         /*
203          *      Keep the handle around so we can dlclose() it.
204          */
205         handle = lt_dlopenext(module_name);
206         if (handle == NULL) {
207                 cf_log_err(cf_sectiontoitem(cs),
208                            "Failed to link to module '%s': %s\n",
209                            module_name, lt_dlerror());
210                 return NULL;
211         }
212
213         /*
214          *      Link to the module's rlm_FOO{} module structure.
215          *
216          *      The module_name variable has the version number
217          *      embedded in it, and we don't want that here.
218          */
219         strcpy(module_struct, module_name);
220         p = strrchr(module_struct, '-');
221         if (p) *p = '\0';
222
223         DEBUG3("    (Loaded %s, checking if it's valid)", module_name);
224
225         /*
226          *      libltld MAY core here, if the handle it gives us contains
227          *      garbage data.
228          */
229         module = lt_dlsym(handle, module_struct);
230         if (!module) {
231                 cf_log_err(cf_sectiontoitem(cs),
232                            "Failed linking to %s structure: %s\n",
233                            module_name, lt_dlerror());
234                 lt_dlclose(handle);
235                 return NULL;
236         }
237         /*
238          *      Before doing anything else, check if it's sane.
239          */
240         if (module->magic != RLM_MODULE_MAGIC_NUMBER) {
241                 lt_dlclose(handle);
242                 cf_log_err(cf_sectiontoitem(cs),
243                            "Invalid version in module '%s'",
244                            module_name);
245                 return NULL;
246
247         }
248
249         /* make room for the module type */
250         node = rad_malloc(sizeof(*node));
251         memset(node, 0, sizeof(*node));
252         strlcpy(node->name, module_name, sizeof(node->name));
253         node->module = module;
254         node->handle = handle;
255
256         cf_log_module(cs, "Linked to module %s", module_name);
257
258         /*
259          *      Add the module as "rlm_foo-version" to the configuration
260          *      section.
261          */
262         if (!rbtree_insert(module_tree, node)) {
263                 radlog(L_ERR, "Failed to cache module %s", module_name);
264                 lt_dlclose(handle);
265                 free(node);
266                 return NULL;
267         }
268
269         return node;
270 }
271
272 /*
273  *      Find a module instance.
274  */
275 module_instance_t *find_module_instance(CONF_SECTION *modules,
276                                         const char *instname)
277 {
278         CONF_SECTION *cs;
279         const char *name1, *name2;
280         module_instance_t *node, myNode;
281         char module_name[256];
282
283         if (!modules) return NULL;
284
285         /*
286          *      Module instances are declared in the modules{} block
287          *      and referenced later by their name, which is the
288          *      name2 from the config section, or name1 if there was
289          *      no name2.
290          */
291         cs = cf_section_sub_find_name2(modules, NULL, instname);
292         if (cs == NULL) {
293                 radlog(L_ERR, "ERROR: Cannot find a configuration entry for module \"%s\".\n", instname);
294                 return NULL;
295         }
296
297         /*
298          *      If there's already a module instance, return it.
299          */
300         strlcpy(myNode.name, instname, sizeof(myNode.name));
301         node = rbtree_finddata(instance_tree, &myNode);
302         if (node) return node;
303
304         name1 = cf_section_name1(cs);
305         name2 = cf_section_name2(cs);
306
307         /*
308          *      Found the configuration entry.
309          */
310         node = rad_malloc(sizeof(*node));
311         memset(node, 0, sizeof(*node));
312
313         node->insthandle = NULL;
314
315         /*
316          *      Names in the "modules" section aren't prefixed
317          *      with "rlm_", so we add it here.
318          */
319         snprintf(module_name, sizeof(module_name), "rlm_%s", name1);
320
321         node->entry = linkto_module(module_name, cs);
322         if (!node->entry) {
323                 free(node);
324                 /* linkto_module logs any errors */
325                 return NULL;
326         }
327
328         if (check_config && (node->entry->module->instantiate) &&
329             (node->entry->module->type & RLM_TYPE_CHECK_CONFIG_SAFE) == 0) {
330                 cf_log_module(cs, "Skipping instantiation of %s", instname);
331         } else {
332                 cf_log_module(cs, "Instantiating %s", instname);
333         }
334
335         /*
336          *      Call the module's instantiation routine.
337          */
338         if ((node->entry->module->instantiate) &&
339             (!check_config ||
340              ((node->entry->module->type & RLM_TYPE_CHECK_CONFIG_SAFE) != 0)) &&
341             ((node->entry->module->instantiate)(cs, &node->insthandle) < 0)) {
342                 cf_log_err(cf_sectiontoitem(cs),
343                            "Instantiation failed for module \"%s\"",
344                            instname);
345                 free(node);
346                 return NULL;
347         }
348
349         /*
350          *      We're done.  Fill in the rest of the data structure,
351          *      and link it to the module instance list.
352          */
353         strlcpy(node->name, instname, sizeof(node->name));
354
355 #ifdef HAVE_PTHREAD_H
356         /*
357          *      If we're threaded, check if the module is thread-safe.
358          *
359          *      If it isn't, we create a mutex.
360          */
361         if ((node->entry->module->type & RLM_TYPE_THREAD_UNSAFE) != 0) {
362                 node->mutex = (pthread_mutex_t *) rad_malloc(sizeof(pthread_mutex_t));
363                 /*
364                  *      Initialize the mutex.
365                  */
366                 pthread_mutex_init(node->mutex, NULL);
367         } else {
368                 /*
369                  *      The module is thread-safe.  Don't give it a mutex.
370                  */
371                 node->mutex = NULL;
372         }
373
374 #endif
375         rbtree_insert(instance_tree, node);
376
377         return node;
378 }
379
380 static indexed_modcallable *lookup_by_index(const char *server, int comp,
381                                             int idx)
382 {
383         indexed_modcallable myc;
384         
385         myc.comp = comp;
386         myc.idx = idx;
387         myc.server = server;
388
389         return rbtree_finddata(components, &myc);
390 }
391
392 /*
393  *      Create a new sublist.
394  */
395 static indexed_modcallable *new_sublist(const char *server, int comp, int idx)
396 {
397         indexed_modcallable *c;
398
399         c = lookup_by_index(server, comp, idx);
400
401         /* It is an error to try to create a sublist that already
402          * exists. It would almost certainly be caused by accidental
403          * duplication in the config file.
404          *
405          * index 0 is the exception, because it is used when we want
406          * to collect _all_ listed modules under a single index by
407          * default, which is currently the case in all components
408          * except authenticate. */
409         if (c) {
410                 if (idx == 0) {
411                         return c;
412                 }
413                 return NULL;
414         }
415
416         c = rad_malloc(sizeof(*c));
417         c->modulelist = NULL;
418         c->server = server;
419         c->comp = comp;
420         c->idx = idx;
421
422         if (!rbtree_insert(components, c)) {
423                 free(c);
424                 return NULL;
425         }
426
427         return c;
428 }
429
430 static int indexed_modcall(int comp, int idx, REQUEST *request)
431 {
432         int rcode;
433         indexed_modcallable *this;
434         modcallable *list = NULL;
435
436         this = lookup_by_index(request->server, comp, idx);
437         if (!this) {
438                 if (idx != 0) DEBUG2("  WARNING: Unknown value specified for %s.  Cannot perform requested action.",
439                                      section_type_value[comp].typename);
440         } else {
441                 list = this->modulelist;
442         }
443
444         request->component = section_type_value[comp].section;
445
446         rcode = modcall(comp, list, request);
447
448         request->module = "<server-core>";
449         request->component = "<server-core>";
450         return rcode;
451 }
452
453 /*
454  *      Load a sub-module list, as found inside an Auth-Type foo {}
455  *      block
456  */
457 static int load_subcomponent_section(modcallable *parent, CONF_SECTION *cs,
458                                      const char *server, int comp)
459 {
460         indexed_modcallable *subcomp;
461         modcallable *ml;
462         DICT_VALUE *dval;
463         const char *name2 = cf_section_name2(cs);
464
465         rad_assert(comp >= RLM_COMPONENT_AUTH);
466         rad_assert(comp <= RLM_COMPONENT_COUNT);
467
468         /*
469          *      Sanity check.
470          */
471         if (!name2) {
472                 cf_log_err(cf_sectiontoitem(cs),
473                            "No name specified for %s block",
474                            section_type_value[comp].typename);
475                 return 1;
476         }
477
478         /*
479          *      Compile the group.
480          */
481         ml = compile_modgroup(parent, comp, cs);
482         if (!ml) {
483                 return 0;
484         }
485
486         /*
487          *      We must assign a numeric index to this subcomponent.
488          *      It is generated and placed in the dictionary
489          *      automatically.  If it isn't found, it's a serious
490          *      error.
491          */
492         dval = dict_valbyname(section_type_value[comp].attr, name2);
493         if (!dval) {
494                 cf_log_err(cf_sectiontoitem(cs),
495                            "%s %s Not previously configured",
496                            section_type_value[comp].typename, name2);
497                 modcallable_free(&ml);
498                 return 0;
499         }
500
501         subcomp = new_sublist(server, comp, dval->value);
502         if (!subcomp) {
503                 modcallable_free(&ml);
504                 return 1;
505         }
506
507         subcomp->modulelist = ml;
508         return 1;               /* OK */
509 }
510
511 static int define_type(const DICT_ATTR *dattr, const char *name)
512 {
513         uint32_t value;
514         DICT_VALUE *dval;
515
516         /*
517          *      If the value already exists, don't
518          *      create it again.
519          */
520         dval = dict_valbyname(dattr->attr, name);
521         if (dval) return 1;
522
523         /*
524          *      Create a new unique value with a
525          *      meaningless number.  You can't look at
526          *      it from outside of this code, so it
527          *      doesn't matter.  The only requirement
528          *      is that it's unique.
529          */
530         do {
531                 value = fr_rand() & 0x00ffffff;
532         } while (dict_valbyattr(dattr->attr, value));
533
534         if (dict_addvalue(name, dattr->name, value) < 0) {
535                 radlog(L_ERR, "%s", librad_errstr);
536                 return 0;
537         }
538
539         return 1;
540 }
541
542 static int load_component_section(CONF_SECTION *cs,
543                                   const char *server, int comp)
544 {
545         modcallable *this;
546         CONF_ITEM *modref;
547         int idx;
548         indexed_modcallable *subcomp;
549         const char *modname;
550         const char *visiblename;
551         const DICT_ATTR *dattr;
552
553         /*
554          *      Find the attribute used to store VALUEs for this section.
555          */
556         dattr = dict_attrbyvalue(section_type_value[comp].attr);
557         if (!dattr) {
558                 cf_log_err(cf_sectiontoitem(cs),
559                            "No such attribute %s",
560                            section_type_value[comp].typename);
561                 return -1;
562         }
563
564         /*
565          *      Loop over the entries in the named section, loading
566          *      the sections this time.
567          */
568         for (modref = cf_item_find_next(cs, NULL);
569              modref != NULL;
570              modref = cf_item_find_next(cs, modref)) {
571                 const char *name1;
572                 CONF_PAIR *cp = NULL;
573                 CONF_SECTION *scs = NULL;
574
575                 if (cf_item_is_section(modref)) {
576                         scs = cf_itemtosection(modref);
577
578                         name1 = cf_section_name1(scs);
579
580                         if (strcmp(name1,
581                                    section_type_value[comp].typename) == 0) {
582                                 if (!load_subcomponent_section(NULL, scs,
583                                                                server, comp)) {
584                                         return -1; /* FIXME: memleak? */
585                                 }
586                                 continue;
587                         }
588
589                         cp = NULL;
590
591                 } else if (cf_item_is_pair(modref)) {
592                         cp = cf_itemtopair(modref);
593
594                 } else {
595                         continue; /* ignore it */
596                 }
597
598                 /*
599                  *      Try to compile one entry.
600                  */
601                 this = compile_modsingle(NULL, comp, modref, &modname);
602                 if (!this) {
603                         cf_log_err(cf_sectiontoitem(cs),
604                                    "Errors parsing %s section.\n",
605                                    cf_section_name1(cs));
606                         return -1;
607                 }
608
609                 /*
610                  *      Look for Auth-Type foo {}, which are special
611                  *      cases of named sections, and allowable ONLY
612                  *      at the top-level.
613                  *
614                  *      i.e. They're not allowed in a "group" or "redundant"
615                  *      subsection.
616                  */
617                 if (comp == RLM_COMPONENT_AUTH) {
618                         DICT_VALUE *dval;
619                         const char *modrefname = NULL;
620                         if (cp) {
621                                 modrefname = cf_pair_attr(cp);
622                         } else {
623                                 modrefname = cf_section_name2(scs);
624                                 if (!modrefname) {
625                                         cf_log_err(cf_sectiontoitem(cs),
626                                                    "Errors parsing %s sub-section.\n",
627                                                    cf_section_name1(scs));
628                                         return -1;
629                                 }
630                         }
631
632                         dval = dict_valbyname(PW_AUTH_TYPE, modrefname);
633                         if (!dval) {
634                                 /*
635                                  *      It's a section, but nothing we
636                                  *      recognize.  Die!
637                                  */
638                                 cf_log_err(cf_sectiontoitem(cs),
639                                            "Unknown Auth-Type \"%s\" in %s sub-section.",
640                                            modrefname, section_type_value[comp].section);
641                                 return -1;
642                         }
643                         idx = dval->value;
644                 } else {
645                         /* See the comment in new_sublist() for explanation
646                          * of the special index 0 */
647                         idx = 0;
648                 }
649
650                 subcomp = new_sublist(server, comp, idx);
651                 if (subcomp == NULL) {
652                         modcallable_free(&this);
653                         continue;
654                 }
655
656                 /* If subcomp->modulelist is NULL, add_to_modcallable will
657                  * create it */
658                 visiblename = cf_section_name2(cs);
659                 if (visiblename == NULL)
660                         visiblename = cf_section_name1(cs);
661                 add_to_modcallable(&subcomp->modulelist, this,
662                                    comp, visiblename);
663         }
664
665         return 0;
666 }
667
668 static int load_byserver(CONF_SECTION *cs)
669 {
670         int comp, flag;
671         const char *server = cf_section_name2(cs);
672
673         cf_log_info(cs, " modules {");
674
675         /*
676          *      Define types first.
677          */
678         for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) {
679                 CONF_SECTION *subcs;
680                 CONF_ITEM *modref;
681                 DICT_ATTR *dattr;
682
683                 subcs = cf_section_sub_find(cs,
684                                             section_type_value[comp].section);
685                 if (!subcs) continue;
686                         
687                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
688
689                 /*
690                  *      Find the attribute used to store VALUEs for this section.
691                  */
692                 dattr = dict_attrbyvalue(section_type_value[comp].attr);
693                 if (!dattr) {
694                         cf_log_err(cf_sectiontoitem(subcs),
695                                    "No such attribute %s",
696                                    section_type_value[comp].typename);
697                         cf_log_info(cs, " }");
698                         return -1;
699                 }
700
701                 /*
702                  *      Define dynamic types, so that others can reference
703                  *      them.
704                  */
705                 for (modref = cf_item_find_next(subcs, NULL);
706                      modref != NULL;
707                      modref = cf_item_find_next(subcs, modref)) {
708                         const char *name1;
709                         CONF_SECTION *subsubcs;
710
711                         /*
712                          *      Create types for simple references
713                          *      only when parsing the authenticate
714                          *      section.
715                          */
716                         if ((section_type_value[comp].attr == PW_AUTH_TYPE) &&
717                             cf_item_is_pair(modref)) {
718                                 CONF_PAIR *cp = cf_itemtopair(modref);
719                                 if (!define_type(dattr, cf_pair_attr(cp))) {
720                                         return -1;
721                                 }
722
723                                 continue;
724                         }
725
726                         if (!cf_item_is_section(modref)) continue;
727                         
728                         subsubcs = cf_itemtosection(modref);
729                         name1 = cf_section_name1(subsubcs);
730                 
731                         if (strcmp(name1, section_type_value[comp].typename) == 0) {
732                                 if (!define_type(dattr,
733                                                  cf_section_name2(subsubcs))) {
734                                         cf_log_info(cs, " }");
735                                         return -1;
736                                 }
737                         }
738                 }
739         } /* loop over components */
740
741         /*
742          *      Loop over all of the known components, finding their
743          *      configuration section, and loading it.
744          */
745         flag = 0;
746         for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) {
747                 CONF_SECTION *subcs;
748
749                 subcs = cf_section_sub_find(cs,
750                                             section_type_value[comp].section);
751                 if (!subcs) continue;
752                         
753                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
754                         
755                 cf_log_module(cs, "Checking %s {...} for more modules to load",
756                        section_type_value[comp].section);
757
758                 if (load_component_section(subcs, server, comp) < 0) {
759                         cf_log_info(cs, " }");
760                         return -1;
761                 }
762                 flag = 1;
763         } /* loop over components */
764
765         /*
766          *      We haven't loaded any of the normal sections.  Maybe we're
767          *      supposed to load the vmps section.
768          *
769          *      This is a bit of a hack...
770          */
771         if (!flag) {
772                 CONF_SECTION *subcs;
773
774                 subcs = cf_section_sub_find(cs, "vmps");
775                 if (subcs) {
776                         cf_log_module(cs, "Checking vmps {...} for more modules to load");              
777                         if (load_component_section(subcs, server,
778                                                    RLM_COMPONENT_POST_AUTH) < 0) {
779                                 return -1;
780                         }
781                         flag = 1;
782                 }
783         }
784
785         cf_log_info(cs, " }");
786
787         if (!flag && server) {
788                 DEBUG("WARNING: Server %s is empty, and will do nothing!",
789                       server);
790         }
791
792         return 0;
793 }
794
795
796 int module_hup(CONF_SECTION *modules)
797 {
798         time_t when;
799         CONF_ITEM *ci;
800         CONF_SECTION *cs;
801         module_instance_t *node;
802
803         static int insthandle_counter = -1;
804         static time_t hup_times[16];
805
806         if (!modules) return 0;
807
808         if (insthandle_counter < 0) {
809                 memset(hup_times, 0, sizeof(hup_times));
810                 insthandle_counter = 0;
811         }
812
813         when = time(NULL);
814
815         /*
816          *      Loop over the modules
817          */
818         for (ci=cf_item_find_next(modules, NULL);
819              ci != NULL;
820              ci=cf_item_find_next(modules, ci)) {
821                 int i;
822                 void *insthandle = NULL;
823                 const char *instname;
824                 module_instance_t myNode;
825
826                 /*
827                  *      If it's not a section, ignore it.
828                  */
829                 if (!cf_item_is_section(ci)) continue;
830
831                 cs = cf_itemtosection(ci);
832                 instname = cf_section_name2(cs);
833                 if (!instname) instname = cf_section_name1(cs);
834
835                 strlcpy(myNode.name, instname, sizeof(myNode.name));
836                 node = rbtree_finddata(instance_tree, &myNode);
837                 if (!node ||
838                     !node->entry->module->instantiate ||
839                     ((node->entry->module->type & RLM_TYPE_HUP_SAFE) == 0)) {
840                         continue;
841                 }
842
843                 cf_log_module(cs, "Trying to reload module \"%s\"", node->name);
844
845                 if ((node->entry->module->instantiate)(cs, &insthandle) < 0) {
846                         cf_log_err(cf_sectiontoitem(cs),
847                                    "HUP failed for module \"%s\".  Using old configuration.",
848                                    node->name);
849                         continue;
850                 }
851
852                 radlog(L_INFO, " Module: Reloaded module \"%s\"", node->name);
853
854                 /*
855                  *      Free all configurations old enough to be
856                  *      deleted.  This is slightly wasteful, but easy
857                  *      to do.
858                  *
859                  *      We permit HUPs every 5s, and we cache the last
860                  *      16 configurations.  So the current entry at
861                  *      insthandle_counter will either be empty, OR will
862                  *      be at least (5*16) = 80s old.  The following check
863                  *      ensures that it will be deleted.
864                  */
865                 for (i = 0; i < 16; i++) {
866                         if ((int) (when - hup_times[insthandle_counter]) < 60)
867                                 continue;
868
869                         if (!node->old_insthandle[i]) continue;
870
871                         cf_section_parse_free(cs, node->old_insthandle[i]);
872                         
873                         if (node->entry->module->detach) {
874                                 (node->entry->module->detach)(node->old_insthandle[i]);
875                         }
876                         node->old_insthandle[i] = NULL;
877                 }
878
879                 /*
880                  *      Save the old instance handle for later deletion.
881                  */
882                 node->old_insthandle[insthandle_counter] = node->insthandle;
883                 node->insthandle = insthandle;
884
885                 /*
886                  *      FIXME: Set a timeout to come back in 60s, so that
887                  *      we can pro-actively clean up the old instances.
888                  */
889         }
890
891         /*
892          *      Remember when we were last HUP'd.
893          */
894         hup_times[insthandle_counter] = when;
895         insthandle_counter++;
896         insthandle_counter &= 0x0f;
897
898         return 1;
899 }
900
901
902 /*
903  *      Parse the module config sections, and load
904  *      and call each module's init() function.
905  *
906  *      Libtool makes your life a LOT easier, especially with libltdl.
907  *      see: http://www.gnu.org/software/libtool/
908  */
909 int setup_modules(int reload, CONF_SECTION *config)
910 {
911         CONF_SECTION    *cs, *modules;
912         rad_listen_t    *listener;
913         int             null_server = FALSE;
914
915         if (reload) return 0;
916
917         /*
918          *      If necessary, initialize libltdl.
919          */
920         if (!reload) {
921                 /*
922                  *      Set the default list of preloaded symbols.
923                  *      This is used to initialize libltdl's list of
924                  *      preloaded modules.
925                  *
926                  *      i.e. Static modules.
927                  */
928                 LTDL_SET_PRELOADED_SYMBOLS();
929
930                 if (lt_dlinit() != 0) {
931                         radlog(L_ERR, "Failed to initialize libraries: %s\n",
932                                         lt_dlerror());
933                         return -1;
934                 }
935
936                 /*
937                  *      Set the search path to ONLY our library directory.
938                  *      This prevents the modules from being found from
939                  *      any location on the disk.
940                  */
941                 lt_dlsetsearchpath(radlib_dir);
942
943                 /*
944                  *      Set up the internal module struct.
945                  */
946                 module_tree = rbtree_create(module_entry_cmp,
947                                             module_entry_free, 0);
948                 if (!module_tree) {
949                         radlog(L_ERR, "Failed to initialize modules\n");
950                         return -1;
951                 }
952
953                 instance_tree = rbtree_create(module_instance_cmp,
954                                               module_instance_free, 0);
955                 if (!instance_tree) {
956                         radlog(L_ERR, "Failed to initialize modules\n");
957                         return -1;
958                 }
959         }
960
961         components = rbtree_create(indexed_modcallable_cmp,
962                                    indexed_modcallable_free, 0);
963         if (!components) {
964                 radlog(L_ERR, "Failed to initialize components\n");
965                 return -1;
966         }
967
968         /*
969          *      Remember where the modules were stored.
970          */
971         modules = cf_section_sub_find(config, "modules");
972         if (!modules) {
973                 radlog(L_ERR, "Cannot find a \"modules\" section in the configuration file!");
974                 return -1;
975         }
976
977         DEBUG2("radiusd: #### Instantiating modules ####");
978
979         /*
980          *  Look for the 'instantiate' section, which tells us
981          *  the instantiation order of the modules, and also allows
982          *  us to load modules with no authorize/authenticate/etc.
983          *  sections.
984          */
985         cs = cf_section_sub_find(config, "instantiate");
986         if (cs != NULL) {
987                 CONF_ITEM *ci;
988                 CONF_PAIR *cp;
989                 module_instance_t *module;
990                 const char *name;
991
992                 cf_log_info(cs, " instantiate {");
993
994                 /*
995                  *  Loop over the items in the 'instantiate' section.
996                  */
997                 for (ci=cf_item_find_next(cs, NULL);
998                      ci != NULL;
999                      ci=cf_item_find_next(cs, ci)) {
1000
1001                         /*
1002                          *      Skip sections.  They'll be handled
1003                          *      later, if they're referenced at all...
1004                          */
1005                         if (cf_item_is_section(ci)) {
1006                                 continue;
1007                         }
1008
1009                         cp = cf_itemtopair(ci);
1010                         name = cf_pair_attr(cp);
1011                         module = find_module_instance(modules, name);
1012                         if (!module) {
1013                                 return -1;
1014                         }
1015                 } /* loop over items in the subsection */
1016
1017                 cf_log_info(cs, " }");
1018         } /* if there's an 'instantiate' section. */
1019
1020         /*
1021          *      Loop over the listeners, figuring out which sections
1022          *      to load.
1023          */
1024         for (listener = mainconfig.listen;
1025              listener != NULL;
1026              listener = listener->next) {
1027                 char buffer[256];
1028
1029                 if (listener->type == RAD_LISTEN_PROXY) continue;
1030
1031                 cs = cf_section_sub_find_name2(config,
1032                                                "server", listener->server);
1033                 if (!cs && (listener->server != NULL)) {
1034                         listener->print(listener, buffer, sizeof(buffer));
1035
1036                         radlog(L_ERR, "No server has been defined for %s", buffer);
1037                         return -1;
1038                 }
1039         }
1040
1041         DEBUG2("radiusd: #### Loading Virtual Servers ####");
1042
1043         /*
1044          *      Load all of the virtual servers.
1045          */
1046         for (cs = cf_subsection_find_next(config, NULL, "server");
1047              cs != NULL;
1048              cs = cf_subsection_find_next(config, cs, "server")) {
1049                 const char *name2 = cf_section_name2(cs);
1050
1051                 if (name2) {
1052                         cf_log_info(cs, "server %s {", name2);
1053                 } else {
1054                         cf_log_info(cs, "server {");
1055                         null_server = TRUE;
1056                 }
1057                 if (load_byserver(cs) < 0) {
1058                         cf_log_info(cs, "}");
1059                         return -1;
1060                 }
1061                 cf_log_info(cs, "}");
1062         }
1063
1064         /*
1065          *      No empty server defined.  Try to load an old-style
1066          *      one for backwards compatibility.
1067          */
1068         if (!null_server) {
1069                 cf_log_info(cs, "server {");
1070                 if (load_byserver(config) < 0) {
1071                         cf_log_info(cs, "}");
1072                         return -1;
1073                 }
1074                 cf_log_info(cs, "}");
1075         }
1076
1077         return 0;
1078 }
1079
1080 /*
1081  *      Call all authorization modules until one returns
1082  *      somethings else than RLM_MODULE_OK
1083  */
1084 int module_authorize(int autz_type, REQUEST *request)
1085 {
1086         return indexed_modcall(RLM_COMPONENT_AUTZ, autz_type, request);
1087 }
1088
1089 /*
1090  *      Authenticate a user/password with various methods.
1091  */
1092 int module_authenticate(int auth_type, REQUEST *request)
1093 {
1094         return indexed_modcall(RLM_COMPONENT_AUTH, auth_type, request);
1095 }
1096
1097 /*
1098  *      Do pre-accounting for ALL configured sessions
1099  */
1100 int module_preacct(REQUEST *request)
1101 {
1102         return indexed_modcall(RLM_COMPONENT_PREACCT, 0, request);
1103 }
1104
1105 /*
1106  *      Do accounting for ALL configured sessions
1107  */
1108 int module_accounting(int acct_type, REQUEST *request)
1109 {
1110         return indexed_modcall(RLM_COMPONENT_ACCT, acct_type, request);
1111 }
1112
1113 /*
1114  *      See if a user is already logged in.
1115  *
1116  *      Returns: 0 == OK, 1 == double logins, 2 == multilink attempt
1117  */
1118 int module_checksimul(int sess_type, REQUEST *request, int maxsimul)
1119 {
1120         int rcode;
1121
1122         if(!request->username)
1123                 return 0;
1124
1125         request->simul_count = 0;
1126         request->simul_max = maxsimul;
1127         request->simul_mpp = 1;
1128
1129         rcode = indexed_modcall(RLM_COMPONENT_SESS, sess_type, request);
1130
1131         if (rcode != RLM_MODULE_OK) {
1132                 /* FIXME: Good spot for a *rate-limited* warning to the log */
1133                 return 0;
1134         }
1135
1136         return (request->simul_count < maxsimul) ? 0 : request->simul_mpp;
1137 }
1138
1139 /*
1140  *      Do pre-proxying for ALL configured sessions
1141  */
1142 int module_pre_proxy(int type, REQUEST *request)
1143 {
1144         return indexed_modcall(RLM_COMPONENT_PRE_PROXY, type, request);
1145 }
1146
1147 /*
1148  *      Do post-proxying for ALL configured sessions
1149  */
1150 int module_post_proxy(int type, REQUEST *request)
1151 {
1152         return indexed_modcall(RLM_COMPONENT_POST_PROXY, type, request);
1153 }
1154
1155 /*
1156  *      Do post-authentication for ALL configured sessions
1157  */
1158 int module_post_auth(int postauth_type, REQUEST *request)
1159 {
1160         return indexed_modcall(RLM_COMPONENT_POST_AUTH, postauth_type, request);
1161 }