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