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