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