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