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