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