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