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