Ignore non-pairs when instantiating modules in "instantiate"
[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 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                                         modcallable_free(&this);
626                                         cf_log_err(cf_sectiontoitem(cs),
627                                                    "Errors parsing %s sub-section.\n",
628                                                    cf_section_name1(scs));
629                                         return -1;
630                                 }
631                         }
632
633                         dval = dict_valbyname(PW_AUTH_TYPE, modrefname);
634                         if (!dval) {
635                                 /*
636                                  *      It's a section, but nothing we
637                                  *      recognize.  Die!
638                                  */
639                                 modcallable_free(&this);
640                                 cf_log_err(cf_sectiontoitem(cs),
641                                            "Unknown Auth-Type \"%s\" in %s sub-section.",
642                                            modrefname, section_type_value[comp].section);
643                                 return -1;
644                         }
645                         idx = dval->value;
646                 } else {
647                         /* See the comment in new_sublist() for explanation
648                          * of the special index 0 */
649                         idx = 0;
650                 }
651
652                 subcomp = new_sublist(server, comp, idx);
653                 if (subcomp == NULL) {
654                         modcallable_free(&this);
655                         continue;
656                 }
657
658                 /* If subcomp->modulelist is NULL, add_to_modcallable will
659                  * create it */
660                 visiblename = cf_section_name2(cs);
661                 if (visiblename == NULL)
662                         visiblename = cf_section_name1(cs);
663                 add_to_modcallable(&subcomp->modulelist, this,
664                                    comp, visiblename);
665         }
666
667         return 0;
668 }
669
670 static int load_byserver(CONF_SECTION *cs)
671 {
672         int comp, flag;
673         const char *server = cf_section_name2(cs);
674
675         cf_log_info(cs, " modules {");
676
677         /*
678          *      Define types first.
679          */
680         for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) {
681                 CONF_SECTION *subcs;
682                 CONF_ITEM *modref;
683                 DICT_ATTR *dattr;
684
685                 subcs = cf_section_sub_find(cs,
686                                             section_type_value[comp].section);
687                 if (!subcs) continue;
688                         
689                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
690
691                 /*
692                  *      Find the attribute used to store VALUEs for this section.
693                  */
694                 dattr = dict_attrbyvalue(section_type_value[comp].attr);
695                 if (!dattr) {
696                         cf_log_err(cf_sectiontoitem(subcs),
697                                    "No such attribute %s",
698                                    section_type_value[comp].typename);
699                         cf_log_info(cs, " }");
700                         return -1;
701                 }
702
703                 /*
704                  *      Define dynamic types, so that others can reference
705                  *      them.
706                  */
707                 for (modref = cf_item_find_next(subcs, NULL);
708                      modref != NULL;
709                      modref = cf_item_find_next(subcs, modref)) {
710                         const char *name1;
711                         CONF_SECTION *subsubcs;
712
713                         /*
714                          *      Create types for simple references
715                          *      only when parsing the authenticate
716                          *      section.
717                          */
718                         if ((section_type_value[comp].attr == PW_AUTH_TYPE) &&
719                             cf_item_is_pair(modref)) {
720                                 CONF_PAIR *cp = cf_itemtopair(modref);
721                                 if (!define_type(dattr, cf_pair_attr(cp))) {
722                                         return -1;
723                                 }
724
725                                 continue;
726                         }
727
728                         if (!cf_item_is_section(modref)) continue;
729                         
730                         subsubcs = cf_itemtosection(modref);
731                         name1 = cf_section_name1(subsubcs);
732                 
733                         if (strcmp(name1, section_type_value[comp].typename) == 0) {
734                                 if (!define_type(dattr,
735                                                  cf_section_name2(subsubcs))) {
736                                         cf_log_info(cs, " }");
737                                         return -1;
738                                 }
739                         }
740                 }
741         } /* loop over components */
742
743         /*
744          *      Loop over all of the known components, finding their
745          *      configuration section, and loading it.
746          */
747         flag = 0;
748         for (comp = 0; comp < RLM_COMPONENT_COUNT; ++comp) {
749                 CONF_SECTION *subcs;
750
751                 subcs = cf_section_sub_find(cs,
752                                             section_type_value[comp].section);
753                 if (!subcs) continue;
754                         
755                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
756                         
757                 cf_log_module(cs, "Checking %s {...} for more modules to load",
758                        section_type_value[comp].section);
759
760                 if (load_component_section(subcs, server, comp) < 0) {
761                         cf_log_info(cs, " }");
762                         return -1;
763                 }
764                 flag = 1;
765         } /* loop over components */
766
767         /*
768          *      We haven't loaded any of the normal sections.  Maybe we're
769          *      supposed to load the vmps section.
770          *
771          *      This is a bit of a hack...
772          */
773         if (!flag) {
774                 CONF_SECTION *subcs;
775
776                 subcs = cf_section_sub_find(cs, "vmps");
777                 if (subcs) {
778                         cf_log_module(cs, "Checking vmps {...} for more modules to load");              
779                         if (load_component_section(subcs, server,
780                                                    RLM_COMPONENT_POST_AUTH) < 0) {
781                                 return -1;
782                         }
783                         flag = 1;
784                 }
785         }
786
787         cf_log_info(cs, " }");
788
789         if (!flag && server) {
790                 DEBUG("WARNING: Server %s is empty, and will do nothing!",
791                       server);
792         }
793
794         return 0;
795 }
796
797
798 int module_hup(CONF_SECTION *modules)
799 {
800         time_t when;
801         CONF_ITEM *ci;
802         CONF_SECTION *cs;
803         module_instance_t *node;
804
805         static int insthandle_counter = -1;
806         static time_t hup_times[16];
807
808         if (!modules) return 0;
809
810         if (insthandle_counter < 0) {
811                 memset(hup_times, 0, sizeof(hup_times));
812                 insthandle_counter = 0;
813         }
814
815         when = time(NULL);
816
817         /*
818          *      Loop over the modules
819          */
820         for (ci=cf_item_find_next(modules, NULL);
821              ci != NULL;
822              ci=cf_item_find_next(modules, ci)) {
823                 int i;
824                 void *insthandle = NULL;
825                 const char *instname;
826                 module_instance_t myNode;
827
828                 /*
829                  *      If it's not a section, ignore it.
830                  */
831                 if (!cf_item_is_section(ci)) continue;
832
833                 cs = cf_itemtosection(ci);
834                 instname = cf_section_name2(cs);
835                 if (!instname) instname = cf_section_name1(cs);
836
837                 strlcpy(myNode.name, instname, sizeof(myNode.name));
838                 node = rbtree_finddata(instance_tree, &myNode);
839                 if (!node ||
840                     !node->entry->module->instantiate ||
841                     ((node->entry->module->type & RLM_TYPE_HUP_SAFE) == 0)) {
842                         continue;
843                 }
844
845                 cf_log_module(cs, "Trying to reload module \"%s\"", node->name);
846
847                 if ((node->entry->module->instantiate)(cs, &insthandle) < 0) {
848                         cf_log_err(cf_sectiontoitem(cs),
849                                    "HUP failed for module \"%s\".  Using old configuration.",
850                                    node->name);
851                         continue;
852                 }
853
854                 radlog(L_INFO, " Module: Reloaded module \"%s\"", node->name);
855
856                 /*
857                  *      Free all configurations old enough to be
858                  *      deleted.  This is slightly wasteful, but easy
859                  *      to do.
860                  *
861                  *      We permit HUPs every 5s, and we cache the last
862                  *      16 configurations.  So the current entry at
863                  *      insthandle_counter will either be empty, OR will
864                  *      be at least (5*16) = 80s old.  The following check
865                  *      ensures that it will be deleted.
866                  */
867                 for (i = 0; i < 16; i++) {
868                         if ((int) (when - hup_times[insthandle_counter]) < 60)
869                                 continue;
870
871                         if (!node->old_insthandle[i]) continue;
872
873                         cf_section_parse_free(cs, node->old_insthandle[i]);
874                         
875                         if (node->entry->module->detach) {
876                                 (node->entry->module->detach)(node->old_insthandle[i]);
877                         }
878                         node->old_insthandle[i] = NULL;
879                 }
880
881                 /*
882                  *      Save the old instance handle for later deletion.
883                  */
884                 node->old_insthandle[insthandle_counter] = node->insthandle;
885                 node->insthandle = insthandle;
886
887                 /*
888                  *      FIXME: Set a timeout to come back in 60s, so that
889                  *      we can pro-actively clean up the old instances.
890                  */
891         }
892
893         /*
894          *      Remember when we were last HUP'd.
895          */
896         hup_times[insthandle_counter] = when;
897         insthandle_counter++;
898         insthandle_counter &= 0x0f;
899
900         return 1;
901 }
902
903
904 /*
905  *      Parse the module config sections, and load
906  *      and call each module's init() function.
907  *
908  *      Libtool makes your life a LOT easier, especially with libltdl.
909  *      see: http://www.gnu.org/software/libtool/
910  */
911 int setup_modules(int reload, CONF_SECTION *config)
912 {
913         CONF_SECTION    *cs, *modules;
914         rad_listen_t    *listener;
915         int             null_server = FALSE;
916
917         if (reload) return 0;
918
919         /*
920          *      If necessary, initialize libltdl.
921          */
922         if (!reload) {
923                 /*
924                  *      Set the default list of preloaded symbols.
925                  *      This is used to initialize libltdl's list of
926                  *      preloaded modules.
927                  *
928                  *      i.e. Static modules.
929                  */
930                 LTDL_SET_PRELOADED_SYMBOLS();
931
932                 if (lt_dlinit() != 0) {
933                         radlog(L_ERR, "Failed to initialize libraries: %s\n",
934                                         lt_dlerror());
935                         return -1;
936                 }
937
938                 /*
939                  *      Set the search path to ONLY our library directory.
940                  *      This prevents the modules from being found from
941                  *      any location on the disk.
942                  */
943                 lt_dlsetsearchpath(radlib_dir);
944
945                 /*
946                  *      Set up the internal module struct.
947                  */
948                 module_tree = rbtree_create(module_entry_cmp,
949                                             module_entry_free, 0);
950                 if (!module_tree) {
951                         radlog(L_ERR, "Failed to initialize modules\n");
952                         return -1;
953                 }
954
955                 instance_tree = rbtree_create(module_instance_cmp,
956                                               module_instance_free, 0);
957                 if (!instance_tree) {
958                         radlog(L_ERR, "Failed to initialize modules\n");
959                         return -1;
960                 }
961         }
962
963         components = rbtree_create(indexed_modcallable_cmp,
964                                    indexed_modcallable_free, 0);
965         if (!components) {
966                 radlog(L_ERR, "Failed to initialize components\n");
967                 return -1;
968         }
969
970         /*
971          *      Remember where the modules were stored.
972          */
973         modules = cf_section_sub_find(config, "modules");
974         if (!modules) {
975                 radlog(L_ERR, "Cannot find a \"modules\" section in the configuration file!");
976                 return -1;
977         }
978
979         DEBUG2("%s: #### Instantiating modules ####", mainconfig.name);
980
981         /*
982          *  Look for the 'instantiate' section, which tells us
983          *  the instantiation order of the modules, and also allows
984          *  us to load modules with no authorize/authenticate/etc.
985          *  sections.
986          */
987         cs = cf_section_sub_find(config, "instantiate");
988         if (cs != NULL) {
989                 CONF_ITEM *ci;
990                 CONF_PAIR *cp;
991                 module_instance_t *module;
992                 const char *name;
993
994                 cf_log_info(cs, " instantiate {");
995
996                 /*
997                  *  Loop over the items in the 'instantiate' section.
998                  */
999                 for (ci=cf_item_find_next(cs, NULL);
1000                      ci != NULL;
1001                      ci=cf_item_find_next(cs, ci)) {
1002
1003                         /*
1004                          *      Skip sections and "other" stuff.
1005                          *      Sections will be handled later, if
1006                          *      they're referenced at all...
1007                          */
1008                         if (!cf_item_is_pair(ci)) {
1009                                 continue;
1010                         }
1011
1012                         cp = cf_itemtopair(ci);
1013                         name = cf_pair_attr(cp);
1014                         module = find_module_instance(modules, name);
1015                         if (!module) {
1016                                 return -1;
1017                         }
1018                 } /* loop over items in the subsection */
1019
1020                 cf_log_info(cs, " }");
1021         } /* if there's an 'instantiate' section. */
1022
1023         /*
1024          *      Loop over the listeners, figuring out which sections
1025          *      to load.
1026          */
1027         for (listener = mainconfig.listen;
1028              listener != NULL;
1029              listener = listener->next) {
1030                 char buffer[256];
1031
1032                 if (listener->type == RAD_LISTEN_PROXY) continue;
1033
1034                 cs = cf_section_sub_find_name2(config,
1035                                                "server", listener->server);
1036                 if (!cs && (listener->server != NULL)) {
1037                         listener->print(listener, buffer, sizeof(buffer));
1038
1039                         radlog(L_ERR, "No server has been defined for %s", buffer);
1040                         return -1;
1041                 }
1042         }
1043
1044         DEBUG2("%s: #### Loading Virtual Servers ####", mainconfig.name);
1045
1046         /*
1047          *      Load all of the virtual servers.
1048          */
1049         for (cs = cf_subsection_find_next(config, NULL, "server");
1050              cs != NULL;
1051              cs = cf_subsection_find_next(config, cs, "server")) {
1052                 const char *name2 = cf_section_name2(cs);
1053
1054                 if (name2) {
1055                         cf_log_info(cs, "server %s {", name2);
1056                 } else {
1057                         cf_log_info(cs, "server {");
1058                         null_server = TRUE;
1059                 }
1060                 if (load_byserver(cs) < 0) {
1061                         cf_log_info(cs, "}");
1062                         return -1;
1063                 }
1064                 cf_log_info(cs, "}");
1065         }
1066
1067         /*
1068          *      No empty server defined.  Try to load an old-style
1069          *      one for backwards compatibility.
1070          */
1071         if (!null_server) {
1072                 cf_log_info(cs, "server {");
1073                 if (load_byserver(config) < 0) {
1074                         cf_log_info(cs, "}");
1075                         return -1;
1076                 }
1077                 cf_log_info(cs, "}");
1078         }
1079
1080         return 0;
1081 }
1082
1083 /*
1084  *      Call all authorization modules until one returns
1085  *      somethings else than RLM_MODULE_OK
1086  */
1087 int module_authorize(int autz_type, REQUEST *request)
1088 {
1089         return indexed_modcall(RLM_COMPONENT_AUTZ, autz_type, request);
1090 }
1091
1092 /*
1093  *      Authenticate a user/password with various methods.
1094  */
1095 int module_authenticate(int auth_type, REQUEST *request)
1096 {
1097         return indexed_modcall(RLM_COMPONENT_AUTH, auth_type, request);
1098 }
1099
1100 /*
1101  *      Do pre-accounting for ALL configured sessions
1102  */
1103 int module_preacct(REQUEST *request)
1104 {
1105         return indexed_modcall(RLM_COMPONENT_PREACCT, 0, request);
1106 }
1107
1108 /*
1109  *      Do accounting for ALL configured sessions
1110  */
1111 int module_accounting(int acct_type, REQUEST *request)
1112 {
1113         return indexed_modcall(RLM_COMPONENT_ACCT, acct_type, request);
1114 }
1115
1116 /*
1117  *      See if a user is already logged in.
1118  *
1119  *      Returns: 0 == OK, 1 == double logins, 2 == multilink attempt
1120  */
1121 int module_checksimul(int sess_type, REQUEST *request, int maxsimul)
1122 {
1123         int rcode;
1124
1125         if(!request->username)
1126                 return 0;
1127
1128         request->simul_count = 0;
1129         request->simul_max = maxsimul;
1130         request->simul_mpp = 1;
1131
1132         rcode = indexed_modcall(RLM_COMPONENT_SESS, sess_type, request);
1133
1134         if (rcode != RLM_MODULE_OK) {
1135                 /* FIXME: Good spot for a *rate-limited* warning to the log */
1136                 return 0;
1137         }
1138
1139         return (request->simul_count < maxsimul) ? 0 : request->simul_mpp;
1140 }
1141
1142 /*
1143  *      Do pre-proxying for ALL configured sessions
1144  */
1145 int module_pre_proxy(int type, REQUEST *request)
1146 {
1147         return indexed_modcall(RLM_COMPONENT_PRE_PROXY, type, request);
1148 }
1149
1150 /*
1151  *      Do post-proxying for ALL configured sessions
1152  */
1153 int module_post_proxy(int type, REQUEST *request)
1154 {
1155         return indexed_modcall(RLM_COMPONENT_POST_PROXY, type, request);
1156 }
1157
1158 /*
1159  *      Do post-authentication for ALL configured sessions
1160  */
1161 int module_post_auth(int postauth_type, REQUEST *request)
1162 {
1163         return indexed_modcall(RLM_COMPONENT_POST_AUTH, postauth_type, request);
1164 }