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