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