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