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