91218dd5fa03e69107fcb6cc679b639f9a79d6fa
[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 /** Path to search for modules in
34  *
35  */
36 char const *radlib_dir = NULL;
37
38 typedef struct indexed_modcallable {
39         rlm_components_t        comp;
40         int                     idx;
41         modcallable             *modulelist;
42 } indexed_modcallable;
43
44 typedef struct virtual_server_t {
45         char const      *name;
46         time_t          created;
47         int             can_free;
48         CONF_SECTION    *cs;
49         rbtree_t        *components;
50         modcallable     *mc[MOD_COUNT];
51         CONF_SECTION    *subcs[MOD_COUNT];
52         struct virtual_server_t *next;
53 } virtual_server_t;
54
55 /*
56  *      Keep a hash of virtual servers, so that we can reload them.
57  */
58 #define VIRTUAL_SERVER_HASH_SIZE (256)
59 static virtual_server_t *virtual_servers[VIRTUAL_SERVER_HASH_SIZE];
60
61 static rbtree_t *module_tree = NULL;
62
63 static rbtree_t *instance_tree = NULL;
64
65 struct fr_module_hup_t {
66         module_instance_t       *mi;
67         time_t                  when;
68         void                    *insthandle;
69         fr_module_hup_t         *next;
70 };
71
72 /*
73  *      Ordered by component
74  */
75 const section_type_value_t section_type_value[MOD_COUNT] = {
76         { "authenticate", "Auth-Type",       PW_AUTH_TYPE },
77         { "authorize",    "Autz-Type",       PW_AUTZ_TYPE },
78         { "preacct",      "Pre-Acct-Type",   PW_PRE_ACCT_TYPE },
79         { "accounting",   "Acct-Type",       PW_ACCT_TYPE },
80         { "session",      "Session-Type",    PW_SESSION_TYPE },
81         { "pre-proxy",    "Pre-Proxy-Type",  PW_PRE_PROXY_TYPE },
82         { "post-proxy",   "Post-Proxy-Type", PW_POST_PROXY_TYPE },
83         { "post-auth",    "Post-Auth-Type",  PW_POST_AUTH_TYPE }
84 #ifdef WITH_COA
85         ,
86         { "recv-coa",     "Recv-CoA-Type",   PW_RECV_COA_TYPE },
87         { "send-coa",     "Send-CoA-Type",   PW_SEND_COA_TYPE }
88 #endif
89 };
90
91 #ifndef RTLD_NOW
92 #define RTLD_NOW (0)
93 #endif
94 #ifndef RTLD_LOCAL
95 #define RTLD_LOCAL (0)
96 #endif
97
98 #ifdef __APPLE__
99 #  define LT_SHREXT ".dylib"
100 #elif defined (WIN32)
101 #  define LT_SHREXT ".dll"
102 #else
103 #  define LT_SHREXT ".so"
104 #endif
105
106 /** Check if the magic number in the module matches the one in the library
107  *
108  * This is used to detect potential ABI issues caused by running with modules which
109  * were built for a different version of the server.
110  *
111  * @param cs being parsed.
112  * @param module being loaded.
113  * @returns 0 on success, -1 if prefix mismatch, -2 if version mismatch, -3 if commit mismatch.
114  */
115 static int check_module_magic(CONF_SECTION *cs, module_t const *module)
116 {
117 #ifdef HAVE_DLADDR
118         Dl_info dl_info;
119         dladdr(module, &dl_info);
120 #endif
121
122         if (MAGIC_PREFIX(module->magic) != MAGIC_PREFIX(RADIUSD_MAGIC_NUMBER)) {
123 #ifdef HAVE_DLADDR
124                 cf_log_err_cs(cs, "Failed loading module rlm_%s from file %s", module->name, dl_info.dli_fname);
125 #endif
126                 cf_log_err_cs(cs, "Application and rlm_%s magic number (prefix) mismatch."
127                               "  application: %x module: %x", module->name,
128                               MAGIC_PREFIX(RADIUSD_MAGIC_NUMBER),
129                               MAGIC_PREFIX(module->magic));
130                 return -1;
131         }
132
133         if (MAGIC_VERSION(module->magic) != MAGIC_VERSION(RADIUSD_MAGIC_NUMBER)) {
134 #ifdef HAVE_DLADDR
135                 cf_log_err_cs(cs, "Failed loading module rlm_%s from file %s", module->name, dl_info.dli_fname);
136 #endif
137                 cf_log_err_cs(cs, "Application and rlm_%s magic number (version) mismatch."
138                               "  application: %lx module: %lx", module->name,
139                               (unsigned long) MAGIC_VERSION(RADIUSD_MAGIC_NUMBER),
140                               (unsigned long) MAGIC_VERSION(module->magic));
141                 return -2;
142         }
143
144         if (MAGIC_COMMIT(module->magic) != MAGIC_COMMIT(RADIUSD_MAGIC_NUMBER)) {
145 #ifdef HAVE_DLADDR
146                 cf_log_err_cs(cs, "Failed loading module rlm_%s from file %s", module->name, dl_info.dli_fname);
147 #endif
148                 cf_log_err_cs(cs, "Application and rlm_%s magic number (commit) mismatch."
149                               "  application: %lx module: %lx", module->name,
150                               (unsigned long) MAGIC_COMMIT(RADIUSD_MAGIC_NUMBER),
151                               (unsigned long) MAGIC_COMMIT(module->magic));
152                 return -3;
153         }
154
155         return 0;
156 }
157
158 fr_dlhandle fr_dlopenext(char const *name)
159 {
160         int             flags = RTLD_NOW;
161         void            *handle;
162         char            buffer[2048];
163         char            *env;
164         char const      *search_path;
165 #ifdef RTLD_GLOBAL
166         if (strcmp(name, "rlm_perl") == 0) {
167                 flags |= RTLD_GLOBAL;
168         } else
169 #endif
170                 flags |= RTLD_LOCAL;
171
172 #ifndef NDEBUG
173         /*
174          *      Bind all the symbols *NOW* so we don't hit errors later
175          */
176         flags |= RTLD_NOW;
177 #endif
178
179         /*
180          *      Apple removed support for DYLD_LIBRARY_PATH in rootless mode.
181          */
182         env = getenv("FR_LIBRARY_PATH");
183         if (env) {
184                 DEBUG3("Ignoring libdir as FR_LIBRARY_PATH set.  Module search path will be: %s", env);
185                 search_path = env;
186         } else {
187                 search_path = radlib_dir;
188         }
189
190         /*
191          *      Prefer loading our libraries by absolute path.
192          */
193         if (search_path) {
194                 char *error;
195                 char *ctx, *paths, *path;
196                 char *p;
197
198                 fr_strerror();
199
200                 ctx = paths = talloc_strdup(NULL, search_path);
201                 while ((path = strsep(&paths, ":")) != NULL) {
202                         /*
203                          *      Trim the trailing slash
204                          */
205                         p = strrchr(path, '/');
206                         if (p && ((p[1] == '\0') || (p[1] == ':'))) *p = '\0';
207
208                         path = talloc_asprintf(ctx, "%s/%s%s", path, name, LT_SHREXT);
209
210                         DEBUG4("Loading %s with path: %s", name, path);
211
212                         handle = dlopen(path, flags);
213                         if (handle) {
214                                 talloc_free(ctx);
215                                 return handle;
216                         }
217                         error = dlerror();
218
219                         fr_strerror_printf("%s%s\n", fr_strerror(), error);
220                         DEBUG4("Loading %s failed: %s - %s", name, error,
221                                (access(path, R_OK) < 0) ? fr_syserror(errno) : "No access errors");
222                         talloc_free(path);
223                 }
224                 talloc_free(ctx);
225         }
226
227         DEBUG4("Loading library using linker search path(s)");
228         if (DEBUG_ENABLED4) {
229 #ifdef __APPLE__
230                 env = getenv("LD_LIBRARY_PATH");
231                 if (env) {
232                         DEBUG4("LD_LIBRARY_PATH            : %s", env);
233                 }
234                 env = getenv("DYLD_LIBRARY_PATH");
235                 if (env) {
236                         DEBUG4("DYLB_LIBRARY_PATH          : %s", env);
237                 }
238                 env = getenv("DYLD_FALLBACK_LIBRARY_PATH");
239                 if (env) {
240                         DEBUG4("DYLD_FALLBACK_LIBRARY_PATH : %s", env);
241                 }
242                 env = getcwd(buffer, sizeof(buffer));
243                 if (env) {
244                         DEBUG4("Current directory          : %s", env);
245                 }
246 #else
247                 env = getenv("LD_LIBRARY_PATH");
248                 if (env) {
249                         DEBUG4("LD_LIBRARY_PATH  : %s", env);
250                 }
251                 DEBUG4("Defaults         : /lib:/usr/lib");
252 #endif
253         }
254
255         strlcpy(buffer, name, sizeof(buffer));
256         /*
257          *      FIXME: Make this configurable...
258          */
259         strlcat(buffer, LT_SHREXT, sizeof(buffer));
260
261         handle = dlopen(buffer, flags);
262         if (!handle) {
263                 char *error = dlerror();
264
265                 DEBUG4("Failed with error: %s", error);
266                 /*
267                  *      Don't overwrite the previous message
268                  *      It's likely to contain a better error.
269                  */
270                 if (!radlib_dir) fr_strerror_printf("%s", dlerror());
271                 return NULL;
272         }
273         return handle;
274 }
275
276 void *fr_dlsym(fr_dlhandle handle, char const *symbol)
277 {
278         return dlsym(handle, symbol);
279 }
280
281 int fr_dlclose(fr_dlhandle handle)
282 {
283         if (!handle) return 0;
284
285         return dlclose(handle);
286 }
287
288 char const *fr_dlerror(void)
289 {
290         return dlerror();
291 }
292
293 static int virtual_server_idx(char const *name)
294 {
295         uint32_t hash;
296
297         if (!name) return 0;
298
299         hash = fr_hash_string(name);
300
301         return hash & (VIRTUAL_SERVER_HASH_SIZE - 1);
302 }
303
304 static virtual_server_t *virtual_server_find(char const *name)
305 {
306         rlm_rcode_t rcode;
307         virtual_server_t *server;
308
309         rcode = virtual_server_idx(name);
310         for (server = virtual_servers[rcode];
311              server != NULL;
312              server = server->next) {
313                 if (!name && !server->name) break;
314
315                 if ((name && server->name) &&
316                     (strcmp(name, server->name) == 0)) break;
317         }
318
319         return server;
320 }
321
322 static int _virtual_server_free(virtual_server_t *server)
323 {
324         if (server->components) rbtree_free(server->components);
325         return 0;
326 }
327
328 void virtual_servers_free(time_t when)
329 {
330         int i;
331         virtual_server_t **last;
332
333         for (i = 0; i < VIRTUAL_SERVER_HASH_SIZE; i++) {
334                 virtual_server_t *server, *next;
335
336                 last = &virtual_servers[i];
337                 for (server = virtual_servers[i];
338                      server != NULL;
339                      server = next) {
340                         next = server->next;
341
342                         /*
343                          *      If we delete it, fix the links so that
344                          *      we don't orphan anything.  Also,
345                          *      delete it if it's old, AND a newer one
346                          *      was defined.
347                          *
348                          *      Otherwise, the last pointer gets set to
349                          *      the one we didn't delete.
350                          */
351                         if ((when == 0) ||
352                             ((server->created < when) && server->can_free)) {
353                                 *last = server->next;
354                                 talloc_free(server);
355                         } else {
356                                 last = &(server->next);
357                         }
358                 }
359         }
360 }
361
362 static int indexed_modcallable_cmp(void const *one, void const *two)
363 {
364         indexed_modcallable const *a = one;
365         indexed_modcallable const *b = two;
366
367         if (a->comp < b->comp) return -1;
368         if (a->comp >  b->comp) return +1;
369
370         return a->idx - b->idx;
371 }
372
373
374 /*
375  *      Compare two module entries
376  */
377 static int module_instance_cmp(void const *one, void const *two)
378 {
379         module_instance_t const *a = one;
380         module_instance_t const *b = two;
381
382         return strcmp(a->name, b->name);
383 }
384
385
386 static void module_instance_free_old(UNUSED CONF_SECTION *cs, module_instance_t *node, time_t when)
387 {
388         fr_module_hup_t *mh, **last;
389
390         /*
391          *      Walk the list, freeing up old instances.
392          */
393         last = &(node->mh);
394         while (*last) {
395                 mh = *last;
396
397                 /*
398                  *      Free only every 60 seconds.
399                  */
400                 if ((when - mh->when) < 60) {
401                         last = &(mh->next);
402                         continue;
403                 }
404
405                 talloc_free(mh->insthandle);
406
407                 *last = mh->next;
408                 talloc_free(mh);
409         }
410 }
411
412
413 /*
414  *      Free a module instance.
415  */
416 static void module_instance_free(void *data)
417 {
418         module_instance_t *module = talloc_get_type_abort(data, module_instance_t);
419
420         module_instance_free_old(module->cs, module, time(NULL) + 100);
421
422 #ifdef HAVE_PTHREAD_H
423         if (module->mutex) {
424                 /*
425                  *      FIXME
426                  *      The mutex MIGHT be locked...
427                  *      we'll check for that later, I guess.
428                  */
429                 pthread_mutex_destroy(module->mutex);
430                 talloc_free(module->mutex);
431         }
432 #endif
433
434         xlat_unregister(module->name, NULL, module->insthandle);
435
436         /*
437          *      Remove all xlat's registered to module instance.
438          */
439         if (module->insthandle) {
440                 /*
441                  *      Remove any registered paircompares.
442                  */
443                 paircompare_unregister_instance(module->insthandle);
444
445                 xlat_unregister_module(module->insthandle);
446         }
447         talloc_free(module);
448 }
449
450
451 /*
452  *      Compare two module entries
453  */
454 static int module_entry_cmp(void const *one, void const *two)
455 {
456         module_entry_t const *a = one;
457         module_entry_t const *b = two;
458
459         return strcmp(a->name, b->name);
460 }
461
462 /*
463  *      Free a module entry.
464  */
465 static int _module_entry_free(module_entry_t *this)
466 {
467 #ifndef NDEBUG
468         /*
469          *      Don't dlclose() modules if we're doing memory
470          *      debugging.  This removes the symbols needed by
471          *      valgrind.
472          */
473         if (!main_config.debug_memory)
474 #endif
475                 dlclose(this->handle);  /* ignore any errors */
476         return 0;
477 }
478
479
480 /*
481  *      Remove the module lists.
482  */
483 int modules_free(void)
484 {
485         rbtree_free(instance_tree);
486         rbtree_free(module_tree);
487
488         return 0;
489 }
490
491
492 /*
493  *      dlopen() a module.
494  */
495 static module_entry_t *module_dlopen(CONF_SECTION *cs, char const *module_name)
496 {
497         module_entry_t myentry;
498         module_entry_t *node;
499         void *handle = NULL;
500         module_t const *module;
501
502         strlcpy(myentry.name, module_name, sizeof(myentry.name));
503         node = rbtree_finddata(module_tree, &myentry);
504         if (node) return node;
505
506         /*
507          *      Link to the module's rlm_FOO{} structure, the same as
508          *      the module name.
509          */
510
511 #if !defined(WITH_LIBLTDL) && defined(HAVE_DLFCN_H) && defined(RTLD_SELF)
512         module = dlsym(RTLD_SELF, module_name);
513         if (module) goto open_self;
514 #endif
515
516         /*
517          *      Keep the handle around so we can dlclose() it.
518          */
519         handle = fr_dlopenext(module_name);
520         if (!handle) {
521                 cf_log_err_cs(cs, "Failed to link to module '%s': %s", module_name, fr_strerror());
522                 return NULL;
523         }
524
525         DEBUG3("Loaded %s, checking if it's valid", module_name);
526
527         module = dlsym(handle, module_name);
528         if (!module) {
529                 cf_log_err_cs(cs, "Failed linking to %s structure: %s", module_name, dlerror());
530                 dlclose(handle);
531                 return NULL;
532         }
533
534 #if !defined(WITH_LIBLTDL) && defined (HAVE_DLFCN_H) && defined(RTLD_SELF)
535  open_self:
536 #endif
537         /*
538          *      Before doing anything else, check if it's sane.
539          */
540         if (check_module_magic(cs, module) < 0) {
541                 dlclose(handle);
542                 return NULL;
543         }
544
545         /* make room for the module type */
546         node = talloc_zero(cs, module_entry_t);
547         talloc_set_destructor(node, _module_entry_free);
548         strlcpy(node->name, module_name, sizeof(node->name));
549         node->module = module;
550         node->handle = handle;
551
552         cf_log_module(cs, "Loaded module %s", module_name);
553
554         /*
555          *      Add the module as "rlm_foo-version" to the configuration
556          *      section.
557          */
558         if (!rbtree_insert(module_tree, node)) {
559                 ERROR("Failed to cache module %s", module_name);
560                 dlclose(handle);
561                 talloc_free(node);
562                 return NULL;
563         }
564
565         return node;
566 }
567
568 /** Parse module's configuration section and setup destructors
569  *
570  */
571 static int module_conf_parse(module_instance_t *node, void **handle)
572 {
573         *handle = NULL;
574
575         /*
576          *      If there is supposed to be instance data, allocate it now.
577          *      Also parse the configuration data, if required.
578          */
579         if (node->entry->module->inst_size) {
580                 *handle = talloc_zero_array(node, uint8_t, node->entry->module->inst_size);
581                 rad_assert(handle);
582
583                 talloc_set_name(*handle, "rlm_%s_t",
584                                 node->entry->module->name ? node->entry->module->name : "config");
585
586                 if (node->entry->module->config &&
587                     (cf_section_parse(node->cs, *handle, node->entry->module->config) < 0)) {
588                         cf_log_err_cs(node->cs,"Invalid configuration for module \"%s\"", node->name);
589                         talloc_free(*handle);
590
591                         return -1;
592                 }
593
594                 /*
595                  *      Set the destructor.
596                  */
597                 if (node->entry->module->detach) {
598                         talloc_set_destructor(*handle, node->entry->module->detach);
599                 }
600         }
601
602         return 0;
603 }
604
605 /** Bootstrap a module.
606  *
607  *  Load the module shared library, allocate instance memory for it,
608  *  parse the module configuration, and call the modules "bootstrap" method.
609  */
610 static module_instance_t *module_bootstrap(CONF_SECTION *cs)
611 {
612         char const *name1, *name2;
613         module_instance_t *node, myNode;
614         char module_name[256];
615
616         /*
617          *      Figure out which module we want to load.
618          */
619         name1 = cf_section_name1(cs);
620         name2 = cf_section_name2(cs);
621         if (!name2) name2 = name1;
622
623         strlcpy(myNode.name, name2, sizeof(myNode.name));
624
625         /*
626          *      See if the module already exists.
627          */
628         node = rbtree_finddata(instance_tree, &myNode);
629         if (node) {
630                 ERROR("Duplicate module \"%s %s\", in file %s:%d and file %s:%d",
631                       name1, name2,
632                       cf_section_filename(cs),
633                       cf_section_lineno(cs),
634                       cf_section_filename(node->cs),
635                       cf_section_lineno(node->cs));
636                 return NULL;
637         }
638
639         /*
640          *      Hang the node struct off of the configuration
641          *      section. If the CS is free'd the instance will be
642          *      free'd, too.
643          */
644         node = talloc_zero(instance_tree, module_instance_t);
645         node->cs = cs;
646         strlcpy(node->name, name2, sizeof(node->name));
647
648         /*
649          *      Names in the "modules" section aren't prefixed
650          *      with "rlm_", so we add it here.
651          */
652         snprintf(module_name, sizeof(module_name), "rlm_%s", name1);
653
654         /*
655          *      Load the module shared library.
656          */
657         node->entry = module_dlopen(cs, module_name);
658         if (!node->entry) {
659                 talloc_free(node);
660                 return NULL;
661         }
662
663         cf_log_module(cs, "Loading module \"%s\" from file %s", node->name,
664                       cf_section_filename(cs));
665
666         /*
667          *      Parse the modules configuration.
668          */
669         if (module_conf_parse(node, &node->insthandle) < 0) {
670                 talloc_free(node);
671                 return NULL;
672         }
673
674         /*
675          *      Bootstrap the module.
676          */
677         if (node->entry->module->bootstrap &&
678             ((node->entry->module->bootstrap)(cs, node->insthandle) < 0)) {
679                 cf_log_err_cs(cs, "Instantiation failed for module \"%s\"", node->name);
680                 talloc_free(node);
681                 return NULL;
682         }
683
684         /*
685          *      Remember the module for later.
686          */
687         rbtree_insert(instance_tree, node);
688
689         return node;
690 }
691
692
693 /** Find an existing module instance.
694  *
695  */
696 module_instance_t *module_find(CONF_SECTION *modules, char const *askedname)
697 {
698         char const *instname;
699         module_instance_t myNode;
700
701         if (!modules) return NULL;
702
703         /*
704          *      Look for the real name.  Ignore the first character,
705          *      which tells the server "it's OK for this module to not
706          *      exist."
707          */
708         instname = askedname;
709         if (instname[0] == '-') instname++;
710
711         strlcpy(myNode.name, instname, sizeof(myNode.name));
712
713         return rbtree_finddata(instance_tree, &myNode);
714 }
715
716
717 /** Load a module, and instantiate it.
718  *
719  */
720 module_instance_t *module_instantiate(CONF_SECTION *modules, char const *askedname)
721 {
722         module_instance_t *node;
723
724         /*
725          *      Find the module.  If it's not there, do nothing.
726          */
727         node = module_find(modules, askedname);
728         if (!node) {
729                 ERROR("Cannot find module \"%s\"", askedname);
730                 return NULL;
731         }
732
733         /*
734          *      The module is already instantiated.  Return it.
735          */
736         if (node->instantiated) return node;
737
738         /*
739          *      Now that ALL modules are instantiated, and ALL xlats
740          *      are defined, go compile the config items marked as XLAT.
741          */
742         if (node->entry->module->config &&
743             (cf_section_parse_pass2(node->cs, node->insthandle,
744                                     node->entry->module->config) < 0)) {
745                 return NULL;
746         }
747
748         /*
749          *      Call the instantiate method, if any.
750          */
751         if (node->entry->module->instantiate) {
752                 cf_log_module(node->cs, "Instantiating module \"%s\" from file %s", node->name,
753                               cf_section_filename(node->cs));
754
755                 /*
756                  *      Call the module's instantiation routine.
757                  */
758                 if ((node->entry->module->instantiate)(node->cs, node->insthandle) < 0) {
759                         cf_log_err_cs(node->cs, "Instantiation failed for module \"%s\"", node->name);
760
761                         return NULL;
762                 }
763         }
764
765 #ifdef HAVE_PTHREAD_H
766         /*
767          *      If we're threaded, check if the module is thread-safe.
768          *
769          *      If it isn't, we create a mutex.
770          */
771         if ((node->entry->module->type & RLM_TYPE_THREAD_UNSAFE) != 0) {
772                 node->mutex = talloc_zero(node, pthread_mutex_t);
773
774                 /*
775                  *      Initialize the mutex.
776                  */
777                 pthread_mutex_init(node->mutex, NULL);
778         }
779 #endif
780
781         node->instantiated = true;
782         node->last_hup = time(NULL); /* don't let us load it, then immediately hup it */
783
784         return node;
785 }
786
787
788 module_instance_t *module_instantiate_method(CONF_SECTION *modules, char const *name, rlm_components_t *method)
789 {
790         char *p;
791         rlm_components_t i;
792         module_instance_t *mi;
793
794         /*
795          *      If the module exists, ensure it's instantiated.
796          *
797          *      Doing it this way avoids complaints from
798          *      module_instantiate()
799          */
800         mi = module_find(modules, name);
801         if (mi) return module_instantiate(modules, name);
802
803         /*
804          *      Find out which method is being used.
805          */
806         p = strrchr(name, '.');
807         if (!p) return NULL;
808
809         p++;
810
811         /*
812          *      Find the component.
813          */
814         for (i = MOD_AUTHENTICATE; i < MOD_COUNT; i++) {
815                 if (strcmp(p, section_type_value[i].section) == 0) {
816                         char buffer[256];
817
818                         strlcpy(buffer, name, sizeof(buffer));
819                         buffer[p - name - 1] = '\0';
820
821                         mi = module_find(modules, buffer);
822                         if (mi) {
823                                 if (method) *method = i;
824                                 return module_instantiate(modules, buffer);
825                         }
826                 }
827         }
828
829         /*
830          *      Not found.
831          */
832         return NULL;
833 }
834
835
836 /** Resolve polymorphic item's from a module's CONF_SECTION to a subsection in another module
837  *
838  * This allows certain module sections to reference module sections in other instances
839  * of the same module and share CONF_DATA associated with them.
840  *
841  * @verbatim
842 example {
843         data {
844                 ...
845         }
846 }
847
848 example inst {
849         data = example
850 }
851  * @endverbatim
852  *
853  * @param out where to write the pointer to a module's config section.  May be NULL on success, indicating the config
854  *        item was not found within the module CONF_SECTION, or the chain of module references was followed and the
855  *        module at the end of the chain did not a subsection.
856  * @param module CONF_SECTION.
857  * @param name of the polymorphic sub-section.
858  * @return 0 on success with referenced section, 1 on success with local section, or -1 on failure.
859  */
860 int find_module_sibling_section(CONF_SECTION **out, CONF_SECTION *module, char const *name)
861 {
862         static bool loop = true;        /* not used, we just need a valid pointer to quiet static analysis */
863
864         CONF_PAIR *cp;
865         CONF_SECTION *cs;
866
867         module_instance_t *inst;
868         char const *inst_name;
869
870 #define FIND_SIBLING_CF_KEY "find_sibling"
871
872         *out = NULL;
873
874         /*
875          *      Is a real section (not referencing sibling module).
876          */
877         cs = cf_section_sub_find(module, name);
878         if (cs) {
879                 *out = cs;
880
881                 return 0;
882         }
883
884         /*
885          *      Item omitted completely from module config.
886          */
887         cp = cf_pair_find(module, name);
888         if (!cp) return 0;
889
890         if (cf_data_find(module, FIND_SIBLING_CF_KEY)) {
891                 cf_log_err_cp(cp, "Module reference loop found");
892
893                 return -1;
894         }
895         cf_data_add(module, FIND_SIBLING_CF_KEY, &loop, NULL);
896
897         /*
898          *      Item found, resolve it to a module instance.
899          *      This triggers module loading, so we don't have
900          *      instantiation order issues.
901          */
902         inst_name = cf_pair_value(cp);
903         inst = module_instantiate(cf_item_parent(cf_section_to_item(module)), inst_name);
904
905         /*
906          *      Remove the config data we added for loop
907          *      detection.
908          */
909         cf_data_remove(module, FIND_SIBLING_CF_KEY);
910         if (!inst) {
911                 cf_log_err_cp(cp, "Unknown module instance \"%s\"", inst_name);
912
913                 return -1;
914         }
915
916         /*
917          *      Check the module instances are of the same type.
918          */
919         if (strcmp(cf_section_name1(inst->cs), cf_section_name1(module)) != 0) {
920                 cf_log_err_cp(cp, "Referenced module is a rlm_%s instance, must be a rlm_%s instance",
921                               cf_section_name1(inst->cs), cf_section_name1(module));
922
923                 return -1;
924         }
925
926         *out = cf_section_sub_find(inst->cs, name);
927
928         return 1;
929 }
930
931 static indexed_modcallable *lookup_by_index(rbtree_t *components,
932                                             rlm_components_t comp, int idx)
933 {
934         indexed_modcallable myc;
935
936         myc.comp = comp;
937         myc.idx = idx;
938
939         return rbtree_finddata(components, &myc);
940 }
941
942 /*
943  *      Create a new sublist.
944  */
945 static indexed_modcallable *new_sublist(CONF_SECTION *cs,
946                                         rbtree_t *components, rlm_components_t comp, int idx)
947 {
948         indexed_modcallable *c;
949
950         c = lookup_by_index(components, comp, idx);
951
952         /* It is an error to try to create a sublist that already
953          * exists. It would almost certainly be caused by accidental
954          * duplication in the config file.
955          *
956          * index 0 is the exception, because it is used when we want
957          * to collect _all_ listed modules under a single index by
958          * default, which is currently the case in all components
959          * except authenticate. */
960         if (c) {
961                 if (idx == 0) {
962                         return c;
963                 }
964                 return NULL;
965         }
966
967         c = talloc_zero(cs, indexed_modcallable);
968         c->modulelist = NULL;
969         c->comp = comp;
970         c->idx = idx;
971
972         if (!rbtree_insert(components, c)) {
973                 talloc_free(c);
974                 return NULL;
975         }
976
977         return c;
978 }
979
980 rlm_rcode_t indexed_modcall(rlm_components_t comp, int idx, REQUEST *request)
981 {
982         rlm_rcode_t rcode;
983         modcallable *list = NULL;
984         virtual_server_t *server;
985
986         /*
987          *      Hack to find the correct virtual server.
988          */
989         server = virtual_server_find(request->server);
990         if (!server) {
991                 RDEBUG("No such virtual server \"%s\"", request->server);
992                 return RLM_MODULE_FAIL;
993         }
994
995         if (idx == 0) {
996                 list = server->mc[comp];
997                 if (!list) {
998                         if (server->name) {
999                                 RDEBUG3("Empty %s section in virtual server \"%s\".  Using default return values.",
1000                                         section_type_value[comp].section, server->name);
1001                         } else {
1002                                 RDEBUG3("Empty %s section.  Using default return values.", section_type_value[comp].section);
1003                         }
1004                 }
1005         } else {
1006                 indexed_modcallable *this;
1007
1008                 this = lookup_by_index(server->components, comp, idx);
1009                 if (this) {
1010                         list = this->modulelist;
1011                 } else {
1012                         RDEBUG2("%s sub-section not found.  Ignoring.", section_type_value[comp].typename);
1013                 }
1014         }
1015
1016         if (server->subcs[comp]) {
1017                 if (idx == 0) {
1018                         RDEBUG("# Executing section %s from file %s",
1019                                section_type_value[comp].section,
1020                                cf_section_filename(server->subcs[comp]));
1021                 } else {
1022                         RDEBUG("# Executing group from file %s",
1023                                cf_section_filename(server->subcs[comp]));
1024                 }
1025         }
1026         request->component = section_type_value[comp].section;
1027
1028         rcode = modcall(comp, list, request);
1029
1030         request->module = "";
1031         request->component = "<core>";
1032         return rcode;
1033 }
1034
1035 /*
1036  *      Load a sub-module list, as found inside an Auth-Type foo {}
1037  *      block
1038  */
1039 static int load_subcomponent_section(CONF_SECTION *cs,
1040                                      rbtree_t *components,
1041                                      DICT_ATTR const *da, rlm_components_t comp)
1042 {
1043         indexed_modcallable *subcomp;
1044         modcallable *ml;
1045         DICT_VALUE *dval;
1046         char const *name2 = cf_section_name2(cs);
1047
1048         /*
1049          *      Sanity check.
1050          */
1051         if (!name2) {
1052                 return 1;
1053         }
1054
1055         /*
1056          *      Compile the group.
1057          */
1058         ml = compile_modgroup(NULL, comp, cs);
1059         if (!ml) {
1060                 return 0;
1061         }
1062
1063         /*
1064          *      We must assign a numeric index to this subcomponent.
1065          *      It is generated and placed in the dictionary
1066          *      automatically.  If it isn't found, it's a serious
1067          *      error.
1068          */
1069         dval = dict_valbyname(da->attr, da->vendor, name2);
1070         if (!dval) {
1071                 talloc_free(ml);
1072                 cf_log_err_cs(cs,
1073                            "The %s attribute has no VALUE defined for %s",
1074                               section_type_value[comp].typename, name2);
1075                 return 0;
1076         }
1077
1078         subcomp = new_sublist(cs, components, comp, dval->value);
1079         if (!subcomp) {
1080                 talloc_free(ml);
1081                 return 1;
1082         }
1083
1084         /*
1085          *      Link it into the talloc hierarchy.
1086          */
1087         subcomp->modulelist = talloc_steal(subcomp, ml);
1088         return 1;               /* OK */
1089 }
1090
1091 /*
1092  *      Don't complain too often.
1093  */
1094 #define MAX_IGNORED (32)
1095 static int last_ignored = -1;
1096 static char const *ignored[MAX_IGNORED];
1097
1098 static int load_component_section(CONF_SECTION *cs,
1099                                   rbtree_t *components, rlm_components_t comp)
1100 {
1101         modcallable *this;
1102         CONF_ITEM *modref;
1103         int idx;
1104         indexed_modcallable *subcomp;
1105         char const *modname;
1106         DICT_ATTR const *da;
1107
1108         /*
1109          *      Find the attribute used to store VALUEs for this section.
1110          */
1111         da = dict_attrbyvalue(section_type_value[comp].attr, 0);
1112         if (!da) {
1113                 cf_log_err_cs(cs,
1114                            "No such attribute %s",
1115                            section_type_value[comp].typename);
1116                 return -1;
1117         }
1118
1119         /*
1120          *      Loop over the entries in the named section, loading
1121          *      the sections this time.
1122          */
1123         for (modref = cf_item_find_next(cs, NULL);
1124              modref != NULL;
1125              modref = cf_item_find_next(cs, modref)) {
1126                 char const *name1;
1127                 CONF_PAIR *cp = NULL;
1128                 CONF_SECTION *scs = NULL;
1129
1130                 if (cf_item_is_section(modref)) {
1131                         scs = cf_item_to_section(modref);
1132
1133                         name1 = cf_section_name1(scs);
1134
1135                         if (strcmp(name1,
1136                                    section_type_value[comp].typename) == 0) {
1137                                 if (!load_subcomponent_section(scs,
1138                                                                components,
1139                                                                da,
1140                                                                comp)) {
1141
1142                                         return -1; /* FIXME: memleak? */
1143                                 }
1144                                 continue;
1145                         }
1146
1147                         cp = NULL;
1148
1149                 } else if (cf_item_is_pair(modref)) {
1150                         cp = cf_item_to_pair(modref);
1151
1152                 } else {
1153                         continue; /* ignore it */
1154                 }
1155
1156                 /*
1157                  *      Look for Auth-Type foo {}, which are special
1158                  *      cases of named sections, and allowable ONLY
1159                  *      at the top-level.
1160                  *
1161                  *      i.e. They're not allowed in a "group" or "redundant"
1162                  *      subsection.
1163                  */
1164                 if (comp == MOD_AUTHENTICATE) {
1165                         DICT_VALUE *dval;
1166                         char const *modrefname = NULL;
1167                         if (cp) {
1168                                 modrefname = cf_pair_attr(cp);
1169                         } else {
1170                                 modrefname = cf_section_name2(scs);
1171                                 if (!modrefname) {
1172                                         cf_log_err_cs(cs,
1173                                                    "Errors parsing %s sub-section.\n",
1174                                                    cf_section_name1(scs));
1175                                         return -1;
1176                                 }
1177                         }
1178
1179                         dval = dict_valbyname(PW_AUTH_TYPE, 0, modrefname);
1180                         if (!dval) {
1181                                 /*
1182                                  *      It's a section, but nothing we
1183                                  *      recognize.  Die!
1184                                  */
1185                                 cf_log_err_cs(cs,
1186                                            "Unknown Auth-Type \"%s\" in %s sub-section.",
1187                                            modrefname, section_type_value[comp].section);
1188                                 return -1;
1189                         }
1190                         idx = dval->value;
1191                 } else {
1192                         /* See the comment in new_sublist() for explanation
1193                          * of the special index 0 */
1194                         idx = 0;
1195                 }
1196
1197                 subcomp = new_sublist(cs, components, comp, idx);
1198                 if (!subcomp) continue;
1199
1200                 /*
1201                  *      Try to compile one entry.
1202                  */
1203                 this = compile_modsingle(subcomp, &subcomp->modulelist, comp, modref, &modname);
1204
1205                 /*
1206                  *      It's OK for the module to not exist.
1207                  */
1208                 if (!this && modname && (modname[0] == '-')) {
1209                         int i;
1210
1211                         if (last_ignored < 0) {
1212                         save_complain:
1213                                 last_ignored++;
1214                                 ignored[last_ignored] = modname;
1215
1216                         complain:
1217                                 WARN("Ignoring \"%s\" (see raddb/mods-available/README.rst)", modname + 1);
1218                                 continue;
1219                         }
1220
1221                         if (last_ignored >= MAX_IGNORED) goto complain;
1222
1223                         for (i = 0; i <= last_ignored; i++) {
1224                                 if (strcmp(ignored[i], modname) == 0) {
1225                                         break;
1226                                 }
1227                         }
1228
1229                         if (i > last_ignored) goto save_complain;
1230                         continue;
1231                 }
1232
1233                 if (!this) {
1234                         cf_log_err_cs(cs,
1235                                    "Errors parsing %s section.\n",
1236                                    cf_section_name1(cs));
1237                         return -1;
1238                 }
1239
1240                 if (rad_debug_lvl > 2) modcall_debug(this, 2);
1241
1242                 add_to_modcallable(subcomp->modulelist, this);
1243         }
1244
1245
1246         return 0;
1247 }
1248
1249 static int load_byserver(CONF_SECTION *cs)
1250 {
1251         rlm_components_t comp, found;
1252         char const *name = cf_section_name2(cs);
1253         rbtree_t *components;
1254         virtual_server_t *server = NULL;
1255         indexed_modcallable *c;
1256         bool is_bare;
1257
1258         if (name) {
1259                 cf_log_info(cs, "server %s { # from file %s",
1260                             name, cf_section_filename(cs));
1261         } else {
1262                 cf_log_info(cs, "server { # from file %s",
1263                             cf_section_filename(cs));
1264         }
1265
1266         is_bare = (cf_item_parent(cf_section_to_item(cs)) == NULL);
1267
1268         server = talloc_zero(cs, virtual_server_t);
1269         server->name = name;
1270         server->created = time(NULL);
1271         server->cs = cs;
1272         server->components = components = rbtree_create(server, indexed_modcallable_cmp, NULL, 0);
1273         if (!components) {
1274                 ERROR("Failed to initialize components");
1275
1276         error:
1277                 if (rad_debug_lvl == 0) {
1278                         ERROR("Failed to load virtual server %s",
1279                               (name != NULL) ? name : "<default>");
1280                 }
1281                 return -1;
1282         }
1283         talloc_set_destructor(server, _virtual_server_free);
1284
1285         /*
1286          *      Loop over all of the known components, finding their
1287          *      configuration section, and loading it.
1288          */
1289         found = 0;
1290         for (comp = 0; comp < MOD_COUNT; ++comp) {
1291                 CONF_SECTION *subcs;
1292
1293                 subcs = cf_section_sub_find(cs,
1294                                             section_type_value[comp].section);
1295                 if (!subcs) continue;
1296
1297                 if (is_bare) {
1298                         cf_log_err_cs(subcs, "The %s section should be inside of a 'server { ... }' block!",
1299                                       section_type_value[comp].section);
1300                 }
1301
1302                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
1303
1304                 /*
1305                  *      Skip pre/post-proxy sections if we're not
1306                  *      proxying.
1307                  */
1308                 if (
1309 #ifdef WITH_PROXY
1310                     !main_config.proxy_requests &&
1311 #endif
1312                     ((comp == MOD_PRE_PROXY) ||
1313                      (comp == MOD_POST_PROXY))) {
1314                         continue;
1315                 }
1316
1317 #ifndef WITH_ACCOUNTING
1318                 if (comp == MOD_ACCOUNTING) continue;
1319 #endif
1320
1321 #ifndef WITH_SESSION_MGMT
1322                 if (comp == MOD_SESSION) continue;
1323 #endif
1324
1325                 if (rad_debug_lvl <= 3) {
1326                         cf_log_module(cs, "Loading %s {...}",
1327                                       section_type_value[comp].section);
1328                 } else {
1329                         DEBUG(" %s {", section_type_value[comp].section);
1330                 }
1331
1332                 if (load_component_section(subcs, components, comp) < 0) {
1333                         goto error;
1334                 }
1335
1336                 if (rad_debug_lvl > 3) {
1337                         DEBUG(" } # %s", section_type_value[comp].section);
1338                 }
1339
1340                 /*
1341                  *      Cache a default, if it exists.  Some people
1342                  *      put empty sections for some reason...
1343                  */
1344                 c = lookup_by_index(components, comp, 0);
1345                 if (c) server->mc[comp] = c->modulelist;
1346
1347                 server->subcs[comp] = subcs;
1348
1349                 found = 1;
1350         } /* loop over components */
1351
1352         /*
1353          *      We haven't loaded any of the normal sections.  Maybe we're
1354          *      supposed to load the vmps section.
1355          *
1356          *      This is a bit of a hack...
1357          */
1358         if (!found) do {
1359 #if defined(WITH_VMPS) || defined(WITH_DHCP)
1360                 CONF_SECTION *subcs;
1361 #endif
1362 #ifdef WITH_DHCP
1363                 DICT_ATTR const *da;
1364 #endif
1365
1366 #ifdef WITH_VMPS
1367                 subcs = cf_section_sub_find(cs, "vmps");
1368                 if (subcs) {
1369                         cf_log_module(cs, "Loading vmps {...}");
1370                         if (load_component_section(subcs, components,
1371                                                    MOD_POST_AUTH) < 0) {
1372                                 goto error;
1373                         }
1374                         c = lookup_by_index(components,
1375                                             MOD_POST_AUTH, 0);
1376                         if (c) server->mc[MOD_POST_AUTH] = c->modulelist;
1377                         break;
1378                 }
1379 #endif
1380
1381 #ifdef WITH_DHCP
1382                 /*
1383                  *      It's OK to not have DHCP.
1384                  */
1385                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1386                 if (!subcs) break;
1387
1388                 da = dict_attrbyname("DHCP-Message-Type");
1389
1390                 /*
1391                  *      Handle each DHCP Message type separately.
1392                  */
1393                 while (subcs) {
1394                         char const *name2 = cf_section_name2(subcs);
1395
1396                         if (name2) {
1397                                 cf_log_module(cs, "Loading dhcp %s {...}", name2);
1398                         } else {
1399                                 cf_log_module(cs, "Loading dhcp {...}");
1400                         }
1401                         if (!load_subcomponent_section(subcs,
1402                                                        components,
1403                                                        da,
1404                                                        MOD_POST_AUTH)) {
1405                                 goto error; /* FIXME: memleak? */
1406                         }
1407                         c = lookup_by_index(components,
1408                                             MOD_POST_AUTH, 0);
1409                         if (c) server->mc[MOD_POST_AUTH] = c->modulelist;
1410
1411                         subcs = cf_subsection_find_next(cs, subcs, "dhcp");
1412                 }
1413 #endif
1414         } while (0);
1415
1416         if (name) {
1417                 cf_log_info(cs, "} # server %s", name);
1418         } else {
1419                 cf_log_info(cs, "} # server");
1420         }
1421
1422         if (rad_debug_lvl == 0) {
1423                 INFO("Loaded virtual server %s",
1424                        (name != NULL) ? name : "<default>");
1425         }
1426
1427         /*
1428          *      Now that it is OK, insert it into the list.
1429          *
1430          *      This is thread-safe...
1431          */
1432         comp = virtual_server_idx(name);
1433         server->next = virtual_servers[comp];
1434         virtual_servers[comp] = server;
1435
1436         /*
1437          *      Mark OLDER ones of the same name as being unused.
1438          */
1439         server = server->next;
1440         while (server) {
1441                 if ((!name && !server->name) ||
1442                     (name && server->name &&
1443                      (strcmp(server->name, name) == 0))) {
1444                         server->can_free = true;
1445                         break;
1446                 }
1447                 server = server->next;
1448         }
1449
1450         return 0;
1451 }
1452
1453
1454 static int pass2_cb(UNUSED void *ctx, void *data)
1455 {
1456         indexed_modcallable *this = data;
1457
1458         if (!modcall_pass2(this->modulelist)) return -1;
1459
1460         return 0;
1461 }
1462
1463
1464 /*
1465  *      Load all of the virtual servers.
1466  */
1467 int virtual_servers_load(CONF_SECTION *config)
1468 {
1469         CONF_SECTION *cs;
1470         virtual_server_t *server;
1471         static bool first_time = true;
1472
1473         DEBUG2("%s: #### Loading Virtual Servers ####", main_config.name);
1474
1475         /*
1476          *      If we have "server { ...}", then there SHOULD NOT be
1477          *      bare "authorize", etc. sections.  if there is no such
1478          *      server, then try to load the old-style sections first.
1479          *
1480          *      In either case, load the "default" virtual server first.
1481          *      this matches better with users expectations.
1482          */
1483         cs = cf_section_find_name2(cf_subsection_find_next(config, NULL,
1484                                                            "server"),
1485                                    "server", NULL);
1486         if (cs) {
1487                 if (load_byserver(cs) < 0) {
1488                         return -1;
1489                 }
1490         } else {
1491                 if (load_byserver(config) < 0) {
1492                         return -1;
1493                 }
1494         }
1495
1496         /*
1497          *      Load all of the virtual servers.
1498          */
1499         for (cs = cf_subsection_find_next(config, NULL, "server");
1500              cs != NULL;
1501              cs = cf_subsection_find_next(config, cs, "server")) {
1502                 char const *name2;
1503
1504                 name2 = cf_section_name2(cs);
1505                 if (!name2) continue; /* handled above */
1506
1507                 server = virtual_server_find(name2);
1508                 if (server &&
1509                     (cf_top_section(server->cs) == config)) {
1510                         ERROR("Duplicate virtual server \"%s\" in file %s:%d and file %s:%d",
1511                                server->name,
1512                                cf_section_filename(server->cs),
1513                                cf_section_lineno(server->cs),
1514                                cf_section_filename(cs),
1515                                cf_section_lineno(cs));
1516                         return -1;
1517                 }
1518
1519                 if (load_byserver(cs) < 0) {
1520                         /*
1521                          *      Once we successfully started once,
1522                          *      continue loading the OTHER servers,
1523                          *      even if one fails.
1524                          */
1525                         if (!first_time) continue;
1526                         return -1;
1527                 }
1528         }
1529
1530         /*
1531          *      Try to compile the "authorize", etc. sections which
1532          *      aren't in a virtual server.
1533          */
1534         server = virtual_server_find(NULL);
1535         if (server) {
1536                 int i;
1537
1538                 for (i = MOD_AUTHENTICATE; i < MOD_COUNT; i++) {
1539                         if (!modcall_pass2(server->mc[i])) return -1;
1540                 }
1541
1542                 if (server->components &&
1543                     (rbtree_walk(server->components, RBTREE_IN_ORDER,
1544                                  pass2_cb, NULL) != 0)) {
1545                         return -1;
1546                 }
1547         }
1548
1549         /*
1550          *      Now that we've loaded everything, run pass 2 over the
1551          *      conditions and xlats.
1552          */
1553         for (cs = cf_subsection_find_next(config, NULL, "server");
1554              cs != NULL;
1555              cs = cf_subsection_find_next(config, cs, "server")) {
1556                 int i;
1557                 char const *name2;
1558
1559                 name2 = cf_section_name2(cs);
1560
1561                 server = virtual_server_find(name2);
1562                 if (!server) continue;
1563
1564                 for (i = MOD_AUTHENTICATE; i < MOD_COUNT; i++) {
1565                         if (!modcall_pass2(server->mc[i])) return -1;
1566                 }
1567
1568                 if (server->components &&
1569                     (rbtree_walk(server->components, RBTREE_IN_ORDER,
1570                                  pass2_cb, NULL) != 0)) {
1571                         return -1;
1572                 }
1573         }
1574
1575         /*
1576          *      If we succeed the first time around, remember that.
1577          */
1578         first_time = false;
1579
1580         return 0;
1581 }
1582
1583 int module_hup_module(CONF_SECTION *cs, module_instance_t *node, time_t when)
1584 {
1585         void *insthandle;
1586         fr_module_hup_t *mh;
1587
1588         if (!node ||
1589             node->entry->module->bootstrap ||
1590             !node->entry->module->instantiate ||
1591             ((node->entry->module->type & RLM_TYPE_HUP_SAFE) == 0)) {
1592                 return 1;
1593         }
1594
1595         /*
1596          *      Silently ignore multiple HUPs within a short time period.
1597          */
1598         if ((node->last_hup + 2) >= when) return 1;
1599         node->last_hup = when;
1600
1601         cf_log_module(cs, "Trying to reload module \"%s\"", node->name);
1602
1603         /*
1604          *      Parse the module configuration, and setup destructors so the
1605          *      module's detach method is called when it's instance data is
1606          *      about to be freed.
1607          */
1608         if (module_conf_parse(node, &insthandle) < 0) {
1609                 cf_log_err_cs(cs, "HUP failed for module \"%s\" (parsing config failed). "
1610                               "Using old configuration", node->name);
1611
1612                 return 0;
1613         }
1614
1615         if ((node->entry->module->instantiate)(cs, insthandle) < 0) {
1616                 cf_log_err_cs(cs, "HUP failed for module \"%s\".  Using old configuration.", node->name);
1617                 talloc_free(insthandle);
1618
1619                 return 0;
1620         }
1621
1622         INFO(" Module: Reloaded module \"%s\"", node->name);
1623
1624         module_instance_free_old(cs, node, when);
1625
1626         /*
1627          *      Save the old instance handle for later deletion.
1628          */
1629         mh = talloc_zero(cs, fr_module_hup_t);
1630         mh->mi = node;
1631         mh->when = when;
1632         mh->insthandle = node->insthandle;
1633         mh->next = node->mh;
1634         node->mh = mh;
1635
1636         /*
1637          *      Replace the instance handle while the module is running.
1638          */
1639         node->insthandle = insthandle;
1640
1641         /*
1642          *      FIXME: Set a timeout to come back in 60s, so that
1643          *      we can pro-actively clean up the old instances.
1644          */
1645
1646         return 1;
1647 }
1648
1649
1650 int modules_hup(CONF_SECTION *modules)
1651 {
1652         time_t when;
1653         CONF_ITEM *ci;
1654         CONF_SECTION *cs;
1655         module_instance_t *node;
1656
1657         if (!modules) return 0;
1658
1659         when = time(NULL);
1660
1661         /*
1662          *      Loop over the modules
1663          */
1664         for (ci=cf_item_find_next(modules, NULL);
1665              ci != NULL;
1666              ci=cf_item_find_next(modules, ci)) {
1667                 char const *instname;
1668                 module_instance_t myNode;
1669
1670                 /*
1671                  *      If it's not a section, ignore it.
1672                  */
1673                 if (!cf_item_is_section(ci)) continue;
1674
1675                 cs = cf_item_to_section(ci);
1676                 instname = cf_section_name2(cs);
1677                 if (!instname) instname = cf_section_name1(cs);
1678
1679                 strlcpy(myNode.name, instname, sizeof(myNode.name));
1680                 node = rbtree_finddata(instance_tree, &myNode);
1681
1682                 module_hup_module(cs, node, when);
1683         }
1684
1685         return 1;
1686 }
1687
1688
1689 static int define_type(CONF_SECTION *cs, DICT_ATTR const *da, char const *name)
1690 {
1691         uint32_t value;
1692         DICT_VALUE *dval;
1693
1694         /*
1695          *      If the value already exists, don't
1696          *      create it again.
1697          */
1698         dval = dict_valbyname(da->attr, da->vendor, name);
1699         if (dval) {
1700                 if (dval->value == 0) {
1701                         ERROR("The dictionaries must not define VALUE %s %s 0",
1702                               da->name, name);
1703                         return 0;
1704                 }
1705                 return 1;
1706         }
1707
1708         /*
1709          *      Create a new unique value with a
1710          *      meaningless number.  You can't look at
1711          *      it from outside of this code, so it
1712          *      doesn't matter.  The only requirement
1713          *      is that it's unique.
1714          */
1715         do {
1716                 value = (fr_rand() & 0x00ffffff) + 1;
1717         } while (dict_valbyattr(da->attr, da->vendor, value));
1718
1719         cf_log_module(cs, "Creating %s = %s", da->name, name);
1720         if (dict_addvalue(name, da->name, value) < 0) {
1721                 ERROR("%s", fr_strerror());
1722                 return 0;
1723         }
1724
1725         return 1;
1726 }
1727
1728 /*
1729  *      Define Auth-Type, etc. in a server.
1730  */
1731 static bool server_define_types(CONF_SECTION *cs)
1732 {
1733         rlm_components_t        comp;
1734
1735         /*
1736          *      Loop over all of the components
1737          */
1738         for (comp = 0; comp < MOD_COUNT; ++comp) {
1739                 CONF_SECTION *subcs, *type_cs;
1740                 DICT_ATTR const *da;
1741
1742                 subcs = cf_section_sub_find(cs,
1743                                             section_type_value[comp].section);
1744                 if (!subcs) continue;
1745
1746                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
1747
1748                 /*
1749                  *      Find the attribute used to store VALUEs for this section.
1750                  */
1751                 da = dict_attrbyvalue(section_type_value[comp].attr, 0);
1752                 if (!da) {
1753                         cf_log_err_cs(subcs,
1754                                    "No such attribute %s",
1755                                    section_type_value[comp].typename);
1756                         return false;
1757                 }
1758
1759                 /*
1760                  *      Define dynamic types, so that others can reference
1761                  *      them.
1762                  *
1763                  *      First, bare modules for 'authenticate'.
1764                  *      Second, Auth-Type, etc.
1765                  */
1766                 if (section_type_value[comp].attr == PW_AUTH_TYPE) {
1767                         CONF_ITEM *modref;
1768
1769                         for (modref = cf_item_find_next(subcs, NULL);
1770                              modref != NULL;
1771                              modref = cf_item_find_next(subcs, modref)) {
1772                                 CONF_PAIR *cp;
1773
1774                                 if (!cf_item_is_pair(modref)) continue;
1775
1776                                 cp = cf_item_to_pair(modref);
1777                                 if (!define_type(cs, da, cf_pair_attr(cp))) {
1778                                         return false;
1779                                 }
1780
1781                                 /*
1782                                  *      Check for duplicates
1783                                  */
1784                                 if (rad_debug_lvl) {
1785                                         CONF_PAIR *cp2;
1786                                         CONF_SECTION *cs2;
1787
1788                                         cp2 = cf_pair_find(subcs, cf_pair_attr(cp));
1789                                         rad_assert(cp2 != NULL);
1790                                         if (cp2 != cp) {
1791                                                 WARN("%s[%d]: Duplicate module '%s'",
1792                                                      cf_pair_filename(cp2),
1793                                                      cf_pair_lineno(cp2),
1794                                                      cf_pair_attr(cp));
1795                                         }
1796
1797                                         cs2 = cf_section_sub_find_name2(subcs, section_type_value[comp].typename, cf_pair_attr(cp));
1798                                         if (cs2) {
1799                                                 WARN("%s[%d]: Duplicate Auth-Type '%s'",
1800                                                      cf_section_filename(cs2),
1801                                                      cf_section_lineno(cs2),
1802                                                      cf_pair_attr(cp));
1803                                         }
1804                                 }
1805
1806                         }
1807                 }
1808
1809                 /*
1810                  *      And loop over the type names
1811                  */
1812                 for (type_cs = cf_subsection_find_next(subcs, NULL, section_type_value[comp].typename);
1813                      type_cs != NULL;
1814                      type_cs = cf_subsection_find_next(subcs, type_cs, section_type_value[comp].typename)) {
1815                         if (!define_type(cs, da, cf_section_name2(type_cs))) {
1816                                 return false;
1817                         }
1818
1819                         if (rad_debug_lvl) {
1820                                 CONF_SECTION *cs2;
1821
1822                                 cs2 = cf_section_sub_find_name2(subcs, section_type_value[comp].typename, cf_section_name2(type_cs));
1823                                 rad_assert(cs2 != NULL);
1824                                 if (cs2 != type_cs) {
1825                                         WARN("%s[%d]: Duplicate Auth-Type '%s'",
1826                                              cf_section_filename(cs2),
1827                                              cf_section_lineno(cs2),
1828                                              cf_section_name2(cs2));
1829                                 }
1830                         }
1831                 }
1832         } /* loop over components */
1833
1834         return true;
1835 }
1836
1837 extern char const *unlang_keyword[];
1838
1839 static bool is_reserved_word(const char *name)
1840 {
1841         int i;
1842
1843         if (!name || !*name) return false;
1844
1845         for (i = 1; unlang_keyword[i] != NULL; i++) {
1846                 if (strcmp(name, unlang_keyword[i]) == 0) return true;
1847         }
1848
1849         return false;
1850 }
1851
1852
1853 /*
1854  *      Parse the module config sections, and load
1855  *      and call each module's init() function.
1856  */
1857 int modules_init(CONF_SECTION *config)
1858 {
1859         CONF_ITEM       *ci, *next;
1860         CONF_SECTION    *cs, *modules;
1861
1862         /*
1863          *      Set up the internal module struct.
1864          */
1865         module_tree = rbtree_create(NULL, module_entry_cmp, NULL, 0);
1866         if (!module_tree) {
1867                 ERROR("Failed to initialize modules\n");
1868                 return -1;
1869         }
1870
1871         instance_tree = rbtree_create(NULL, module_instance_cmp,
1872                                       module_instance_free, 0);
1873         if (!instance_tree) {
1874                 ERROR("Failed to initialize modules\n");
1875                 return -1;
1876         }
1877
1878         memset(virtual_servers, 0, sizeof(virtual_servers));
1879
1880         /*
1881          *      Remember where the modules were stored.
1882          */
1883         modules = cf_section_sub_find(config, "modules");
1884         if (!modules) {
1885                 WARN("Cannot find a \"modules\" section in the configuration file!");
1886         }
1887
1888         /*
1889          *      Load dictionaries.
1890          */
1891         for (cs = cf_subsection_find_next(config, NULL, "server");
1892              cs != NULL;
1893              cs = cf_subsection_find_next(config, cs, "server")) {
1894 #if defined(WITH_DHCP) || defined(WITH_VMPS)
1895                 CONF_SECTION *subcs;
1896                 DICT_ATTR const *da;
1897 #endif
1898
1899 #ifdef WITH_VMPS
1900                 /*
1901                  *      Auto-load the VMPS/VQP dictionary.
1902                  */
1903                 subcs = cf_section_sub_find(cs, "vmps");
1904                 if (subcs) {
1905                         da = dict_attrbyname("VQP-Packet-Type");
1906                         if (!da) {
1907                                 if (dict_read(main_config.dictionary_dir, "dictionary.vqp") < 0) {
1908                                         ERROR("Failed reading dictionary.vqp: %s",
1909                                               fr_strerror());
1910                                         return -1;
1911                                 }
1912                                 cf_log_module(cs, "Loading dictionary.vqp");
1913
1914                                 da = dict_attrbyname("VQP-Packet-Type");
1915                                 if (!da) {
1916                                         ERROR("No VQP-Packet-Type in dictionary.vqp");
1917                                         return -1;
1918                                 }
1919                         }
1920                 }
1921 #endif
1922
1923 #ifdef WITH_DHCP
1924                 /*
1925                  *      Auto-load the DHCP dictionary.
1926                  */
1927                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1928                 if (subcs) {
1929                         da = dict_attrbyname("DHCP-Message-Type");
1930                         if (!da) {
1931                                 cf_log_module(cs, "Loading dictionary.dhcp");
1932                                 if (dict_read(main_config.dictionary_dir, "dictionary.dhcp") < 0) {
1933                                         ERROR("Failed reading dictionary.dhcp: %s",
1934                                               fr_strerror());
1935                                         return -1;
1936                                 }
1937
1938                                 da = dict_attrbyname("DHCP-Message-Type");
1939                                 if (!da) {
1940                                         ERROR("No DHCP-Message-Type in dictionary.dhcp");
1941                                         return -1;
1942                                 }
1943                         }
1944                 }
1945 #endif
1946                 /*
1947                  *      Else it's a RADIUS virtual server, and the
1948                  *      dictionaries are already loaded.
1949                  */
1950
1951                 /*
1952                  *      Root through each virtual server, defining
1953                  *      Autz-Type and Auth-Type.  This is so that the
1954                  *      modules can reference a particular type.
1955                  */
1956                 if (!server_define_types(cs)) return -1;
1957         }
1958
1959         DEBUG2("%s: #### Instantiating modules ####", main_config.name);
1960
1961         cf_log_info(config, " modules {");
1962
1963         /*
1964          *      Loop over module definitions, looking for duplicates.
1965          *
1966          *      This is O(N^2) in the number of modules, but most
1967          *      systems should have less than 100 modules.
1968          */
1969         for (ci = cf_item_find_next(modules, NULL);
1970              ci != NULL;
1971              ci = next) {
1972                 char const *name1;
1973                 CONF_SECTION *subcs;
1974                 module_instance_t *node;
1975
1976                 next = cf_item_find_next(modules, ci);
1977
1978                 if (!cf_item_is_section(ci)) continue;
1979
1980                 subcs = cf_item_to_section(ci);
1981
1982                 node = module_bootstrap(subcs);
1983                 if (!node) return -1;
1984
1985                 if (!next || !cf_item_is_section(next)) continue;
1986
1987                 name1 = cf_section_name1(subcs);
1988
1989                 if (is_reserved_word(name1)) {
1990                         cf_log_err_cs(subcs, "Module cannot be named for an 'unlang' keyword");
1991                         return -1;
1992                 }
1993         }
1994
1995         /*
1996          *  Look for the 'instantiate' section, which tells us
1997          *  the instantiation order of the modules, and also allows
1998          *  us to load modules with no authorize/authenticate/etc.
1999          *  sections.
2000          */
2001         cs = cf_section_sub_find(config, "instantiate");
2002         if (cs) {
2003                 CONF_PAIR *cp;
2004                 module_instance_t *module;
2005                 char const *name;
2006
2007                 cf_log_info(cs, "  instantiate {");
2008
2009                 /*
2010                  *  Loop over the items in the 'instantiate' section.
2011                  */
2012                 for (ci=cf_item_find_next(cs, NULL);
2013                      ci != NULL;
2014                      ci=cf_item_find_next(cs, ci)) {
2015                         /*
2016                          *      Skip sections and "other" stuff.
2017                          *      Sections will be handled later, if
2018                          *      they're referenced at all...
2019                          */
2020                         if (cf_item_is_pair(ci)) {
2021                                 cp = cf_item_to_pair(ci);
2022                                 name = cf_pair_attr(cp);
2023
2024                                 module = module_instantiate(modules, name);
2025                                 if (!module && (name[0] != '-')) {
2026                                         return -1;
2027                                 }
2028                         }
2029
2030                         /*
2031                          *      Can only be "redundant" or
2032                          *      "load-balance" or
2033                          *      "redundant-load-balance"
2034                          */
2035                         if (cf_item_is_section(ci)) {
2036                                 bool all_same = true;
2037                                 module_t const *last = NULL;
2038                                 CONF_SECTION *subcs;
2039                                 CONF_ITEM *subci;
2040
2041                                 subcs = cf_item_to_section(ci);
2042                                 name = cf_section_name1(subcs);
2043
2044                                 /*
2045                                  *      Groups, etc. must have a name.
2046                                  */
2047                                 if (((strcmp(name, "group") == 0) ||
2048                                      (strcmp(name, "redundant") == 0) ||
2049                                      (strcmp(name, "redundant-load-balance") == 0) ||
2050                                      strcmp(name, "load-balance") == 0)) {
2051                                         name = cf_section_name2(subcs);
2052                                         if (!name) {
2053                                                 cf_log_err_cs(subcs, "Subsection must have a name");
2054                                                 return -1;
2055                                         }
2056
2057                                         if (is_reserved_word(name)) {
2058                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
2059                                                 return -1;
2060                                         }
2061                                 } else {
2062                                         if (is_reserved_word(name)) {
2063                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
2064                                                 return -1;
2065                                         }
2066                                 }
2067
2068                                 /*
2069                                  *      Ensure that the modules we reference here exist.
2070                                  */
2071                                 for (subci=cf_item_find_next(subcs, NULL);
2072                                      subci != NULL;
2073                                      subci=cf_item_find_next(subcs, subci)) {
2074                                         if (cf_item_is_pair(subci)) {
2075                                                 cp = cf_item_to_pair(subci);
2076                                                 if (cf_pair_value(cp)) {
2077                                                         cf_log_err(subci, "Cannot set return codes in a %s block",
2078                                                                    cf_section_name1(subcs));
2079                                                         return -1;
2080                                                 }
2081
2082                                                 /*
2083                                                  *      Allow "foo.authorize" in subsections.
2084                                                  */
2085                                                 module = module_instantiate_method(modules, cf_pair_attr(cp), NULL);
2086                                                 if (!module) {
2087                                                         return -1;
2088                                                 }
2089
2090                                                 if (all_same) {
2091                                                         if (!last) {
2092                                                                 last = module->entry->module;
2093                                                         } else if (last != module->entry->module) {
2094                                                                 last = NULL;
2095                                                                 all_same = false;
2096                                                         }
2097                                                 }
2098                                         } else {
2099                                                 all_same = false;
2100                                         }
2101
2102                                         /*
2103                                          *      Don't check subsections for now.
2104                                          */
2105                                 } /* loop over modules in a "redundant foo" section */
2106
2107                                 /*
2108                                  *      Register a redundant xlat
2109                                  */
2110                                 if (all_same) {
2111                                         if (!xlat_register_redundant(cf_item_to_section(ci))) {
2112                                                 WARN("%s[%d] Not registering expansions for %s",
2113                                                      cf_section_filename(subcs), cf_section_lineno(subcs),
2114                                                      cf_section_name2(subcs));
2115                                         }
2116                                 }
2117                         }  /* handle subsections */
2118                 } /* loop over the "instantiate" section */
2119
2120                 cf_log_info(cs, "  }");
2121         } /* if there's an 'instantiate' section. */
2122
2123         /*
2124          *      Now that we've loaded the explicitly ordered modules,
2125          *      load everything in the "modules" section.  This is
2126          *      because we've now split up the modules into
2127          *      mods-enabled.
2128          */
2129         for (ci=cf_item_find_next(modules, NULL);
2130              ci != NULL;
2131              ci=next) {
2132                 char const *name;
2133                 module_instance_t *module;
2134                 CONF_SECTION *subcs;
2135
2136                 next = cf_item_find_next(modules, ci);
2137
2138                 if (!cf_item_is_section(ci)) continue;
2139
2140                 subcs = cf_item_to_section(ci);
2141                 name = cf_section_name2(subcs);
2142                 if (!name) name = cf_section_name1(subcs);
2143
2144                 module = module_instantiate(modules, name);
2145                 if (!module) return -1;
2146         }
2147         cf_log_info(config, " } # modules");
2148
2149         if (virtual_servers_load(config) < 0) return -1;
2150
2151         return 0;
2152 }
2153
2154 /*
2155  *      Call all authorization modules until one returns
2156  *      somethings else than RLM_MODULE_OK
2157  */
2158 rlm_rcode_t process_authorize(int autz_type, REQUEST *request)
2159 {
2160         return indexed_modcall(MOD_AUTHORIZE, autz_type, request);
2161 }
2162
2163 /*
2164  *      Authenticate a user/password with various methods.
2165  */
2166 rlm_rcode_t process_authenticate(int auth_type, REQUEST *request)
2167 {
2168         return indexed_modcall(MOD_AUTHENTICATE, auth_type, request);
2169 }
2170
2171 #ifdef WITH_ACCOUNTING
2172 /*
2173  *      Do pre-accounting for ALL configured sessions
2174  */
2175 rlm_rcode_t module_preacct(REQUEST *request)
2176 {
2177         return indexed_modcall(MOD_PREACCT, 0, request);
2178 }
2179
2180 /*
2181  *      Do accounting for ALL configured sessions
2182  */
2183 rlm_rcode_t process_accounting(int acct_type, REQUEST *request)
2184 {
2185         return indexed_modcall(MOD_ACCOUNTING, acct_type, request);
2186 }
2187 #endif
2188
2189 #ifdef WITH_SESSION_MGMT
2190 /*
2191  *      See if a user is already logged in.
2192  *
2193  *      Returns: 0 == OK, 1 == double logins, 2 == multilink attempt
2194  */
2195 int process_checksimul(int sess_type, REQUEST *request, int maxsimul)
2196 {
2197         rlm_rcode_t rcode;
2198
2199         if(!request->username)
2200                 return 0;
2201
2202         request->simul_count = 0;
2203         request->simul_max = maxsimul;
2204         request->simul_mpp = 1;
2205
2206         rcode = indexed_modcall(MOD_SESSION, sess_type, request);
2207
2208         if (rcode != RLM_MODULE_OK) {
2209                 /* FIXME: Good spot for a *rate-limited* warning to the log */
2210                 return 0;
2211         }
2212
2213         return (request->simul_count < maxsimul) ? 0 : request->simul_mpp;
2214 }
2215 #endif
2216
2217 #ifdef WITH_PROXY
2218 /*
2219  *      Do pre-proxying for ALL configured sessions
2220  */
2221 rlm_rcode_t process_pre_proxy(int type, REQUEST *request)
2222 {
2223         return indexed_modcall(MOD_PRE_PROXY, type, request);
2224 }
2225
2226 /*
2227  *      Do post-proxying for ALL configured sessions
2228  */
2229 rlm_rcode_t process_post_proxy(int type, REQUEST *request)
2230 {
2231         return indexed_modcall(MOD_POST_PROXY, type, request);
2232 }
2233 #endif
2234
2235 /*
2236  *      Do post-authentication for ALL configured sessions
2237  */
2238 rlm_rcode_t process_post_auth(int postauth_type, REQUEST *request)
2239 {
2240         return indexed_modcall(MOD_POST_AUTH, postauth_type, request);
2241 }
2242
2243 #ifdef WITH_COA
2244 rlm_rcode_t process_recv_coa(int recv_coa_type, REQUEST *request)
2245 {
2246         return indexed_modcall(MOD_RECV_COA, recv_coa_type, request);
2247 }
2248
2249 rlm_rcode_t process_send_coa(int send_coa_type, REQUEST *request)
2250 {
2251         return indexed_modcall(MOD_SEND_COA, send_coa_type, request);
2252 }
2253 #endif