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