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