remove unnecessary assert
[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;
1252         bool found;
1253         char const *name = cf_section_name2(cs);
1254         rbtree_t *components;
1255         virtual_server_t *server = NULL;
1256         indexed_modcallable *c;
1257         bool is_bare;
1258
1259         if (name) {
1260                 cf_log_info(cs, "server %s { # from file %s",
1261                             name, cf_section_filename(cs));
1262         } else {
1263                 cf_log_info(cs, "server { # from file %s",
1264                             cf_section_filename(cs));
1265         }
1266
1267         is_bare = (cf_item_parent(cf_section_to_item(cs)) == NULL);
1268
1269         server = talloc_zero(cs, virtual_server_t);
1270         server->name = name;
1271         server->created = time(NULL);
1272         server->cs = cs;
1273         server->components = components = rbtree_create(server, indexed_modcallable_cmp, NULL, 0);
1274         if (!components) {
1275                 ERROR("Failed to initialize components");
1276
1277         error:
1278                 if (rad_debug_lvl == 0) {
1279                         ERROR("Failed to load virtual server %s",
1280                               (name != NULL) ? name : "<default>");
1281                 }
1282                 return -1;
1283         }
1284         talloc_set_destructor(server, _virtual_server_free);
1285
1286         /*
1287          *      Loop over all of the known components, finding their
1288          *      configuration section, and loading it.
1289          */
1290         found = false;
1291         for (comp = 0; comp < MOD_COUNT; ++comp) {
1292                 CONF_SECTION *subcs;
1293
1294                 subcs = cf_section_sub_find(cs,
1295                                             section_type_value[comp].section);
1296                 if (!subcs) continue;
1297
1298                 if (is_bare) {
1299                         cf_log_err_cs(subcs, "The %s section should be inside of a 'server { ... }' block!",
1300                                       section_type_value[comp].section);
1301                 }
1302
1303                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
1304
1305                 /*
1306                  *      Skip pre/post-proxy sections if we're not
1307                  *      proxying.
1308                  */
1309                 if (
1310 #ifdef WITH_PROXY
1311                     !main_config.proxy_requests &&
1312 #endif
1313                     ((comp == MOD_PRE_PROXY) ||
1314                      (comp == MOD_POST_PROXY))) {
1315                         continue;
1316                 }
1317
1318 #ifndef WITH_ACCOUNTING
1319                 if (comp == MOD_ACCOUNTING) continue;
1320 #endif
1321
1322 #ifndef WITH_SESSION_MGMT
1323                 if (comp == MOD_SESSION) continue;
1324 #endif
1325
1326                 if (rad_debug_lvl <= 3) {
1327                         cf_log_module(cs, "Loading %s {...}",
1328                                       section_type_value[comp].section);
1329                 } else {
1330                         DEBUG(" %s {", section_type_value[comp].section);
1331                 }
1332
1333                 if (load_component_section(subcs, components, comp) < 0) {
1334                         goto error;
1335                 }
1336
1337                 if (rad_debug_lvl > 3) {
1338                         DEBUG(" } # %s", section_type_value[comp].section);
1339                 }
1340
1341                 /*
1342                  *      Cache a default, if it exists.  Some people
1343                  *      put empty sections for some reason...
1344                  */
1345                 c = lookup_by_index(components, comp, 0);
1346                 if (c) server->mc[comp] = c->modulelist;
1347
1348                 server->subcs[comp] = subcs;
1349
1350                 found = true;
1351         } /* loop over components */
1352
1353         /*
1354          *      We haven't loaded any of the normal sections.  Maybe we're
1355          *      supposed to load the vmps section.
1356          *
1357          *      This is a bit of a hack...
1358          */
1359         if (!found) do {
1360 #if defined(WITH_VMPS) || defined(WITH_DHCP)
1361                 CONF_SECTION *subcs;
1362 #endif
1363 #ifdef WITH_DHCP
1364                 DICT_ATTR const *da;
1365 #endif
1366
1367 #ifdef WITH_VMPS
1368                 subcs = cf_section_sub_find(cs, "vmps");
1369                 if (subcs) {
1370                         cf_log_module(cs, "Loading vmps {...}");
1371                         if (load_component_section(subcs, components,
1372                                                    MOD_POST_AUTH) < 0) {
1373                                 goto error;
1374                         }
1375                         c = lookup_by_index(components,
1376                                             MOD_POST_AUTH, 0);
1377                         if (c) server->mc[MOD_POST_AUTH] = c->modulelist;
1378                         break;
1379                 }
1380 #endif
1381
1382 #ifdef WITH_DHCP
1383                 /*
1384                  *      It's OK to not have DHCP.
1385                  */
1386                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1387                 if (!subcs) break;
1388
1389                 da = dict_attrbyname("DHCP-Message-Type");
1390
1391                 /*
1392                  *      Handle each DHCP Message type separately.
1393                  */
1394                 while (subcs) {
1395                         char const *name2 = cf_section_name2(subcs);
1396
1397                         if (name2) {
1398                                 cf_log_module(cs, "Loading dhcp %s {...}", name2);
1399                         } else {
1400                                 cf_log_module(cs, "Loading dhcp {...}");
1401                         }
1402                         if (!load_subcomponent_section(subcs,
1403                                                        components,
1404                                                        da,
1405                                                        MOD_POST_AUTH)) {
1406                                 goto error; /* FIXME: memleak? */
1407                         }
1408                         c = lookup_by_index(components,
1409                                             MOD_POST_AUTH, 0);
1410                         if (c) server->mc[MOD_POST_AUTH] = c->modulelist;
1411
1412                         subcs = cf_subsection_find_next(cs, subcs, "dhcp");
1413                 }
1414 #endif
1415         } while (0);
1416
1417         if (name) {
1418                 cf_log_info(cs, "} # server %s", name);
1419         } else {
1420                 cf_log_info(cs, "} # server");
1421         }
1422
1423         if (rad_debug_lvl == 0) {
1424                 INFO("Loaded virtual server %s",
1425                        (name != NULL) ? name : "<default>");
1426         }
1427
1428         /*
1429          *      Now that it is OK, insert it into the list.
1430          *
1431          *      This is thread-safe...
1432          */
1433         comp = virtual_server_idx(name);
1434         server->next = virtual_servers[comp];
1435         virtual_servers[comp] = server;
1436
1437         /*
1438          *      Mark OLDER ones of the same name as being unused.
1439          */
1440         server = server->next;
1441         while (server) {
1442                 if ((!name && !server->name) ||
1443                     (name && server->name &&
1444                      (strcmp(server->name, name) == 0))) {
1445                         server->can_free = true;
1446                         break;
1447                 }
1448                 server = server->next;
1449         }
1450
1451         return 0;
1452 }
1453
1454
1455 static int pass2_cb(UNUSED void *ctx, void *data)
1456 {
1457         indexed_modcallable *this = data;
1458
1459         if (!modcall_pass2(this->modulelist)) return -1;
1460
1461         return 0;
1462 }
1463
1464
1465 /*
1466  *      Load all of the virtual servers.
1467  */
1468 int virtual_servers_load(CONF_SECTION *config)
1469 {
1470         CONF_SECTION *cs;
1471         virtual_server_t *server;
1472         static bool first_time = true;
1473
1474         DEBUG2("%s: #### Loading Virtual Servers ####", main_config.name);
1475
1476         /*
1477          *      If we have "server { ...}", then there SHOULD NOT be
1478          *      bare "authorize", etc. sections.  if there is no such
1479          *      server, then try to load the old-style sections first.
1480          *
1481          *      In either case, load the "default" virtual server first.
1482          *      this matches better with users expectations.
1483          */
1484         cs = cf_section_find_name2(cf_subsection_find_next(config, NULL,
1485                                                            "server"),
1486                                    "server", NULL);
1487         if (cs) {
1488                 if (load_byserver(cs) < 0) {
1489                         return -1;
1490                 }
1491         } else {
1492                 if (load_byserver(config) < 0) {
1493                         return -1;
1494                 }
1495         }
1496
1497         /*
1498          *      Load all of the virtual servers.
1499          */
1500         for (cs = cf_subsection_find_next(config, NULL, "server");
1501              cs != NULL;
1502              cs = cf_subsection_find_next(config, cs, "server")) {
1503                 char const *name2;
1504
1505                 name2 = cf_section_name2(cs);
1506                 if (!name2) continue; /* handled above */
1507
1508                 server = virtual_server_find(name2);
1509                 if (server &&
1510                     (cf_top_section(server->cs) == config)) {
1511                         ERROR("Duplicate virtual server \"%s\" in file %s:%d and file %s:%d",
1512                                server->name,
1513                                cf_section_filename(server->cs),
1514                                cf_section_lineno(server->cs),
1515                                cf_section_filename(cs),
1516                                cf_section_lineno(cs));
1517                         return -1;
1518                 }
1519
1520                 if (load_byserver(cs) < 0) {
1521                         /*
1522                          *      Once we successfully started once,
1523                          *      continue loading the OTHER servers,
1524                          *      even if one fails.
1525                          */
1526                         if (!first_time) continue;
1527                         return -1;
1528                 }
1529         }
1530
1531         /*
1532          *      Try to compile the "authorize", etc. sections which
1533          *      aren't in a virtual server.
1534          */
1535         server = virtual_server_find(NULL);
1536         if (server) {
1537                 int i;
1538
1539                 for (i = MOD_AUTHENTICATE; i < MOD_COUNT; i++) {
1540                         if (!modcall_pass2(server->mc[i])) return -1;
1541                 }
1542
1543                 if (server->components &&
1544                     (rbtree_walk(server->components, RBTREE_IN_ORDER,
1545                                  pass2_cb, NULL) != 0)) {
1546                         return -1;
1547                 }
1548         }
1549
1550         /*
1551          *      Now that we've loaded everything, run pass 2 over the
1552          *      conditions and xlats.
1553          */
1554         for (cs = cf_subsection_find_next(config, NULL, "server");
1555              cs != NULL;
1556              cs = cf_subsection_find_next(config, cs, "server")) {
1557                 int i;
1558                 char const *name2;
1559
1560                 name2 = cf_section_name2(cs);
1561
1562                 server = virtual_server_find(name2);
1563                 if (!server) continue;
1564
1565                 for (i = MOD_AUTHENTICATE; i < MOD_COUNT; i++) {
1566                         if (!modcall_pass2(server->mc[i])) return -1;
1567                 }
1568
1569                 if (server->components &&
1570                     (rbtree_walk(server->components, RBTREE_IN_ORDER,
1571                                  pass2_cb, NULL) != 0)) {
1572                         return -1;
1573                 }
1574         }
1575
1576         /*
1577          *      If we succeed the first time around, remember that.
1578          */
1579         first_time = false;
1580
1581         return 0;
1582 }
1583
1584 int module_hup_module(CONF_SECTION *cs, module_instance_t *node, time_t when)
1585 {
1586         void *insthandle;
1587         fr_module_hup_t *mh;
1588
1589         if (!node ||
1590             node->entry->module->bootstrap ||
1591             !node->entry->module->instantiate ||
1592             ((node->entry->module->type & RLM_TYPE_HUP_SAFE) == 0)) {
1593                 return 1;
1594         }
1595
1596         /*
1597          *      Silently ignore multiple HUPs within a short time period.
1598          */
1599         if ((node->last_hup + 2) >= when) return 1;
1600         node->last_hup = when;
1601
1602         cf_log_module(cs, "Trying to reload module \"%s\"", node->name);
1603
1604         /*
1605          *      Parse the module configuration, and setup destructors so the
1606          *      module's detach method is called when it's instance data is
1607          *      about to be freed.
1608          */
1609         if (module_conf_parse(node, &insthandle) < 0) {
1610                 cf_log_err_cs(cs, "HUP failed for module \"%s\" (parsing config failed). "
1611                               "Using old configuration", node->name);
1612
1613                 return 0;
1614         }
1615
1616         if ((node->entry->module->instantiate)(cs, insthandle) < 0) {
1617                 cf_log_err_cs(cs, "HUP failed for module \"%s\".  Using old configuration.", node->name);
1618                 talloc_free(insthandle);
1619
1620                 return 0;
1621         }
1622
1623         INFO(" Module: Reloaded module \"%s\"", node->name);
1624
1625         module_instance_free_old(cs, node, when);
1626
1627         /*
1628          *      Save the old instance handle for later deletion.
1629          */
1630         mh = talloc_zero(cs, fr_module_hup_t);
1631         mh->mi = node;
1632         mh->when = when;
1633         mh->insthandle = node->insthandle;
1634         mh->next = node->mh;
1635         node->mh = mh;
1636
1637         /*
1638          *      Replace the instance handle while the module is running.
1639          */
1640         node->insthandle = insthandle;
1641
1642         /*
1643          *      FIXME: Set a timeout to come back in 60s, so that
1644          *      we can pro-actively clean up the old instances.
1645          */
1646
1647         return 1;
1648 }
1649
1650
1651 int modules_hup(CONF_SECTION *modules)
1652 {
1653         time_t when;
1654         CONF_ITEM *ci;
1655         CONF_SECTION *cs;
1656         module_instance_t *node;
1657
1658         if (!modules) return 0;
1659
1660         when = time(NULL);
1661
1662         /*
1663          *      Loop over the modules
1664          */
1665         for (ci=cf_item_find_next(modules, NULL);
1666              ci != NULL;
1667              ci=cf_item_find_next(modules, ci)) {
1668                 char const *instname;
1669                 module_instance_t myNode;
1670
1671                 /*
1672                  *      If it's not a section, ignore it.
1673                  */
1674                 if (!cf_item_is_section(ci)) continue;
1675
1676                 cs = cf_item_to_section(ci);
1677                 instname = cf_section_name2(cs);
1678                 if (!instname) instname = cf_section_name1(cs);
1679
1680                 strlcpy(myNode.name, instname, sizeof(myNode.name));
1681                 node = rbtree_finddata(instance_tree, &myNode);
1682
1683                 module_hup_module(cs, node, when);
1684         }
1685
1686         return 1;
1687 }
1688
1689
1690 static int define_type(CONF_SECTION *cs, DICT_ATTR const *da, char const *name)
1691 {
1692         uint32_t value;
1693         DICT_VALUE *dval;
1694
1695         /*
1696          *      If the value already exists, don't
1697          *      create it again.
1698          */
1699         dval = dict_valbyname(da->attr, da->vendor, name);
1700         if (dval) {
1701                 if (dval->value == 0) {
1702                         ERROR("The dictionaries must not define VALUE %s %s 0",
1703                               da->name, name);
1704                         return 0;
1705                 }
1706                 return 1;
1707         }
1708
1709         /*
1710          *      Create a new unique value with a
1711          *      meaningless number.  You can't look at
1712          *      it from outside of this code, so it
1713          *      doesn't matter.  The only requirement
1714          *      is that it's unique.
1715          */
1716         do {
1717                 value = (fr_rand() & 0x00ffffff) + 1;
1718         } while (dict_valbyattr(da->attr, da->vendor, value));
1719
1720         cf_log_module(cs, "Creating %s = %s", da->name, name);
1721         if (dict_addvalue(name, da->name, value) < 0) {
1722                 ERROR("%s", fr_strerror());
1723                 return 0;
1724         }
1725
1726         return 1;
1727 }
1728
1729 /*
1730  *      Define Auth-Type, etc. in a server.
1731  */
1732 static bool server_define_types(CONF_SECTION *cs)
1733 {
1734         rlm_components_t        comp;
1735
1736         /*
1737          *      Loop over all of the components
1738          */
1739         for (comp = 0; comp < MOD_COUNT; ++comp) {
1740                 CONF_SECTION *subcs, *type_cs;
1741                 DICT_ATTR const *da;
1742
1743                 subcs = cf_section_sub_find(cs,
1744                                             section_type_value[comp].section);
1745                 if (!subcs) continue;
1746
1747                 if (cf_item_find_next(subcs, NULL) == NULL) continue;
1748
1749                 /*
1750                  *      Find the attribute used to store VALUEs for this section.
1751                  */
1752                 da = dict_attrbyvalue(section_type_value[comp].attr, 0);
1753                 if (!da) {
1754                         cf_log_err_cs(subcs,
1755                                    "No such attribute %s",
1756                                    section_type_value[comp].typename);
1757                         return false;
1758                 }
1759
1760                 /*
1761                  *      Define dynamic types, so that others can reference
1762                  *      them.
1763                  *
1764                  *      First, bare modules for 'authenticate'.
1765                  *      Second, Auth-Type, etc.
1766                  */
1767                 if (section_type_value[comp].attr == PW_AUTH_TYPE) {
1768                         CONF_ITEM *modref;
1769
1770                         for (modref = cf_item_find_next(subcs, NULL);
1771                              modref != NULL;
1772                              modref = cf_item_find_next(subcs, modref)) {
1773                                 CONF_PAIR *cp;
1774
1775                                 if (!cf_item_is_pair(modref)) continue;
1776
1777                                 cp = cf_item_to_pair(modref);
1778                                 if (!define_type(cs, da, cf_pair_attr(cp))) {
1779                                         return false;
1780                                 }
1781
1782                                 /*
1783                                  *      Check for duplicates
1784                                  */
1785                                 if (rad_debug_lvl) {
1786                                         CONF_PAIR *cp2;
1787                                         CONF_SECTION *cs2;
1788
1789                                         cp2 = cf_pair_find(subcs, cf_pair_attr(cp));
1790                                         rad_assert(cp2 != NULL);
1791                                         if (cp2 != cp) {
1792                                                 WARN("%s[%d]: Duplicate module '%s'",
1793                                                      cf_pair_filename(cp2),
1794                                                      cf_pair_lineno(cp2),
1795                                                      cf_pair_attr(cp));
1796                                         }
1797
1798                                         cs2 = cf_section_sub_find_name2(subcs, section_type_value[comp].typename, cf_pair_attr(cp));
1799                                         if (cs2) {
1800                                                 WARN("%s[%d]: Duplicate Auth-Type '%s'",
1801                                                      cf_section_filename(cs2),
1802                                                      cf_section_lineno(cs2),
1803                                                      cf_pair_attr(cp));
1804                                         }
1805                                 }
1806
1807                         }
1808                 }
1809
1810                 /*
1811                  *      And loop over the type names
1812                  */
1813                 for (type_cs = cf_subsection_find_next(subcs, NULL, section_type_value[comp].typename);
1814                      type_cs != NULL;
1815                      type_cs = cf_subsection_find_next(subcs, type_cs, section_type_value[comp].typename)) {
1816                         if (!define_type(cs, da, cf_section_name2(type_cs))) {
1817                                 return false;
1818                         }
1819
1820                         if (rad_debug_lvl) {
1821                                 CONF_SECTION *cs2;
1822
1823                                 cs2 = cf_section_sub_find_name2(subcs, section_type_value[comp].typename, cf_section_name2(type_cs));
1824                                 rad_assert(cs2 != NULL);
1825                                 if (cs2 != type_cs) {
1826                                         WARN("%s[%d]: Duplicate Auth-Type '%s'",
1827                                              cf_section_filename(cs2),
1828                                              cf_section_lineno(cs2),
1829                                              cf_section_name2(cs2));
1830                                 }
1831                         }
1832                 }
1833         } /* loop over components */
1834
1835         return true;
1836 }
1837
1838 extern char const *unlang_keyword[];
1839
1840 static bool is_reserved_word(const char *name)
1841 {
1842         int i;
1843
1844         if (!name || !*name) return false;
1845
1846         for (i = 1; unlang_keyword[i] != NULL; i++) {
1847                 if (strcmp(name, unlang_keyword[i]) == 0) return true;
1848         }
1849
1850         return false;
1851 }
1852
1853
1854 /*
1855  *      Parse the module config sections, and load
1856  *      and call each module's init() function.
1857  */
1858 int modules_init(CONF_SECTION *config)
1859 {
1860         CONF_ITEM       *ci, *next;
1861         CONF_SECTION    *cs, *modules;
1862
1863         /*
1864          *      Set up the internal module struct.
1865          */
1866         module_tree = rbtree_create(NULL, module_entry_cmp, NULL, 0);
1867         if (!module_tree) {
1868                 ERROR("Failed to initialize modules\n");
1869                 return -1;
1870         }
1871
1872         instance_tree = rbtree_create(NULL, module_instance_cmp,
1873                                       module_instance_free, 0);
1874         if (!instance_tree) {
1875                 ERROR("Failed to initialize modules\n");
1876                 return -1;
1877         }
1878
1879         memset(virtual_servers, 0, sizeof(virtual_servers));
1880
1881         /*
1882          *      Remember where the modules were stored.
1883          */
1884         modules = cf_section_sub_find(config, "modules");
1885         if (!modules) {
1886                 WARN("Cannot find a \"modules\" section in the configuration file!");
1887         }
1888
1889         /*
1890          *      Load dictionaries.
1891          */
1892         for (cs = cf_subsection_find_next(config, NULL, "server");
1893              cs != NULL;
1894              cs = cf_subsection_find_next(config, cs, "server")) {
1895 #if defined(WITH_DHCP) || defined(WITH_VMPS)
1896                 CONF_SECTION *subcs;
1897                 DICT_ATTR const *da;
1898 #endif
1899
1900 #ifdef WITH_VMPS
1901                 /*
1902                  *      Auto-load the VMPS/VQP dictionary.
1903                  */
1904                 subcs = cf_section_sub_find(cs, "vmps");
1905                 if (subcs) {
1906                         da = dict_attrbyname("VQP-Packet-Type");
1907                         if (!da) {
1908                                 if (dict_read(main_config.dictionary_dir, "dictionary.vqp") < 0) {
1909                                         ERROR("Failed reading dictionary.vqp: %s",
1910                                               fr_strerror());
1911                                         return -1;
1912                                 }
1913                                 cf_log_module(cs, "Loading dictionary.vqp");
1914
1915                                 da = dict_attrbyname("VQP-Packet-Type");
1916                                 if (!da) {
1917                                         ERROR("No VQP-Packet-Type in dictionary.vqp");
1918                                         return -1;
1919                                 }
1920                         }
1921                 }
1922 #endif
1923
1924 #ifdef WITH_DHCP
1925                 /*
1926                  *      Auto-load the DHCP dictionary.
1927                  */
1928                 subcs = cf_subsection_find_next(cs, NULL, "dhcp");
1929                 if (subcs) {
1930                         da = dict_attrbyname("DHCP-Message-Type");
1931                         if (!da) {
1932                                 cf_log_module(cs, "Loading dictionary.dhcp");
1933                                 if (dict_read(main_config.dictionary_dir, "dictionary.dhcp") < 0) {
1934                                         ERROR("Failed reading dictionary.dhcp: %s",
1935                                               fr_strerror());
1936                                         return -1;
1937                                 }
1938
1939                                 da = dict_attrbyname("DHCP-Message-Type");
1940                                 if (!da) {
1941                                         ERROR("No DHCP-Message-Type in dictionary.dhcp");
1942                                         return -1;
1943                                 }
1944                         }
1945                 }
1946 #endif
1947                 /*
1948                  *      Else it's a RADIUS virtual server, and the
1949                  *      dictionaries are already loaded.
1950                  */
1951
1952                 /*
1953                  *      Root through each virtual server, defining
1954                  *      Autz-Type and Auth-Type.  This is so that the
1955                  *      modules can reference a particular type.
1956                  */
1957                 if (!server_define_types(cs)) return -1;
1958         }
1959
1960         DEBUG2("%s: #### Instantiating modules ####", main_config.name);
1961
1962         cf_log_info(config, " modules {");
1963
1964         /*
1965          *      Loop over module definitions, looking for duplicates.
1966          *
1967          *      This is O(N^2) in the number of modules, but most
1968          *      systems should have less than 100 modules.
1969          */
1970         for (ci = cf_item_find_next(modules, NULL);
1971              ci != NULL;
1972              ci = next) {
1973                 char const *name1;
1974                 CONF_SECTION *subcs;
1975                 module_instance_t *node;
1976
1977                 next = cf_item_find_next(modules, ci);
1978
1979                 if (!cf_item_is_section(ci)) continue;
1980
1981                 subcs = cf_item_to_section(ci);
1982
1983                 node = module_bootstrap(subcs);
1984                 if (!node) return -1;
1985
1986                 if (!next || !cf_item_is_section(next)) continue;
1987
1988                 name1 = cf_section_name1(subcs);
1989
1990                 if (is_reserved_word(name1)) {
1991                         cf_log_err_cs(subcs, "Module cannot be named for an 'unlang' keyword");
1992                         return -1;
1993                 }
1994         }
1995
1996         /*
1997          *  Look for the 'instantiate' section, which tells us
1998          *  the instantiation order of the modules, and also allows
1999          *  us to load modules with no authorize/authenticate/etc.
2000          *  sections.
2001          */
2002         cs = cf_section_sub_find(config, "instantiate");
2003         if (cs) {
2004                 CONF_PAIR *cp;
2005                 module_instance_t *module;
2006                 char const *name;
2007
2008                 cf_log_info(cs, "  instantiate {");
2009
2010                 /*
2011                  *  Loop over the items in the 'instantiate' section.
2012                  */
2013                 for (ci=cf_item_find_next(cs, NULL);
2014                      ci != NULL;
2015                      ci=cf_item_find_next(cs, ci)) {
2016                         /*
2017                          *      Skip sections and "other" stuff.
2018                          *      Sections will be handled later, if
2019                          *      they're referenced at all...
2020                          */
2021                         if (cf_item_is_pair(ci)) {
2022                                 cp = cf_item_to_pair(ci);
2023                                 name = cf_pair_attr(cp);
2024
2025                                 module = module_instantiate(modules, name);
2026                                 if (!module && (name[0] != '-')) {
2027                                         return -1;
2028                                 }
2029                         }
2030
2031                         /*
2032                          *      Can only be "redundant" or
2033                          *      "load-balance" or
2034                          *      "redundant-load-balance"
2035                          */
2036                         if (cf_item_is_section(ci)) {
2037                                 bool all_same = true;
2038                                 module_t const *last = NULL;
2039                                 CONF_SECTION *subcs;
2040                                 CONF_ITEM *subci;
2041
2042                                 subcs = cf_item_to_section(ci);
2043                                 name = cf_section_name1(subcs);
2044
2045                                 /*
2046                                  *      Groups, etc. must have a name.
2047                                  */
2048                                 if (((strcmp(name, "group") == 0) ||
2049                                      (strcmp(name, "redundant") == 0) ||
2050                                      (strcmp(name, "redundant-load-balance") == 0) ||
2051                                      strcmp(name, "load-balance") == 0)) {
2052                                         name = cf_section_name2(subcs);
2053                                         if (!name) {
2054                                                 cf_log_err_cs(subcs, "Subsection must have a name");
2055                                                 return -1;
2056                                         }
2057
2058                                         if (is_reserved_word(name)) {
2059                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
2060                                                 return -1;
2061                                         }
2062                                 } else {
2063                                         if (is_reserved_word(name)) {
2064                                                 cf_log_err_cs(subcs, "Instantiate sections cannot be named for an 'unlang' keyword");
2065                                                 return -1;
2066                                         }
2067                                 }
2068
2069                                 /*
2070                                  *      Ensure that the modules we reference here exist.
2071                                  */
2072                                 for (subci=cf_item_find_next(subcs, NULL);
2073                                      subci != NULL;
2074                                      subci=cf_item_find_next(subcs, subci)) {
2075                                         if (cf_item_is_pair(subci)) {
2076                                                 cp = cf_item_to_pair(subci);
2077                                                 if (cf_pair_value(cp)) {
2078                                                         cf_log_err(subci, "Cannot set return codes in a %s block",
2079                                                                    cf_section_name1(subcs));
2080                                                         return -1;
2081                                                 }
2082
2083                                                 /*
2084                                                  *      Allow "foo.authorize" in subsections.
2085                                                  */
2086                                                 module = module_instantiate_method(modules, cf_pair_attr(cp), NULL);
2087                                                 if (!module) {
2088                                                         return -1;
2089                                                 }
2090
2091                                                 if (all_same) {
2092                                                         if (!last) {
2093                                                                 last = module->entry->module;
2094                                                         } else if (last != module->entry->module) {
2095                                                                 last = NULL;
2096                                                                 all_same = false;
2097                                                         }
2098                                                 }
2099                                         } else {
2100                                                 all_same = false;
2101                                         }
2102
2103                                         /*
2104                                          *      Don't check subsections for now.
2105                                          */
2106                                 } /* loop over modules in a "redundant foo" section */
2107
2108                                 /*
2109                                  *      Register a redundant xlat
2110                                  */
2111                                 if (all_same) {
2112                                         if (!xlat_register_redundant(cf_item_to_section(ci))) {
2113                                                 WARN("%s[%d] Not registering expansions for %s",
2114                                                      cf_section_filename(subcs), cf_section_lineno(subcs),
2115                                                      cf_section_name2(subcs));
2116                                         }
2117                                 }
2118                         }  /* handle subsections */
2119                 } /* loop over the "instantiate" section */
2120
2121                 cf_log_info(cs, "  }");
2122         } /* if there's an 'instantiate' section. */
2123
2124         /*
2125          *      Now that we've loaded the explicitly ordered modules,
2126          *      load everything in the "modules" section.  This is
2127          *      because we've now split up the modules into
2128          *      mods-enabled.
2129          */
2130         for (ci=cf_item_find_next(modules, NULL);
2131              ci != NULL;
2132              ci=next) {
2133                 char const *name;
2134                 module_instance_t *module;
2135                 CONF_SECTION *subcs;
2136
2137                 next = cf_item_find_next(modules, ci);
2138
2139                 if (!cf_item_is_section(ci)) continue;
2140
2141                 subcs = cf_item_to_section(ci);
2142                 name = cf_section_name2(subcs);
2143                 if (!name) name = cf_section_name1(subcs);
2144
2145                 module = module_instantiate(modules, name);
2146                 if (!module) return -1;
2147         }
2148         cf_log_info(config, " } # modules");
2149
2150         if (virtual_servers_load(config) < 0) return -1;
2151
2152         return 0;
2153 }
2154
2155 /*
2156  *      Call all authorization modules until one returns
2157  *      somethings else than RLM_MODULE_OK
2158  */
2159 rlm_rcode_t process_authorize(int autz_type, REQUEST *request)
2160 {
2161         return indexed_modcall(MOD_AUTHORIZE, autz_type, request);
2162 }
2163
2164 /*
2165  *      Authenticate a user/password with various methods.
2166  */
2167 rlm_rcode_t process_authenticate(int auth_type, REQUEST *request)
2168 {
2169         return indexed_modcall(MOD_AUTHENTICATE, auth_type, request);
2170 }
2171
2172 #ifdef WITH_ACCOUNTING
2173 /*
2174  *      Do pre-accounting for ALL configured sessions
2175  */
2176 rlm_rcode_t module_preacct(REQUEST *request)
2177 {
2178         return indexed_modcall(MOD_PREACCT, 0, request);
2179 }
2180
2181 /*
2182  *      Do accounting for ALL configured sessions
2183  */
2184 rlm_rcode_t process_accounting(int acct_type, REQUEST *request)
2185 {
2186         return indexed_modcall(MOD_ACCOUNTING, acct_type, request);
2187 }
2188 #endif
2189
2190 #ifdef WITH_SESSION_MGMT
2191 /*
2192  *      See if a user is already logged in.
2193  *
2194  *      Returns: 0 == OK, 1 == double logins, 2 == multilink attempt
2195  */
2196 int process_checksimul(int sess_type, REQUEST *request, int maxsimul)
2197 {
2198         rlm_rcode_t rcode;
2199
2200         if(!request->username)
2201                 return 0;
2202
2203         request->simul_count = 0;
2204         request->simul_max = maxsimul;
2205         request->simul_mpp = 1;
2206
2207         rcode = indexed_modcall(MOD_SESSION, sess_type, request);
2208
2209         if (rcode != RLM_MODULE_OK) {
2210                 /* FIXME: Good spot for a *rate-limited* warning to the log */
2211                 return 0;
2212         }
2213
2214         return (request->simul_count < maxsimul) ? 0 : request->simul_mpp;
2215 }
2216 #endif
2217
2218 #ifdef WITH_PROXY
2219 /*
2220  *      Do pre-proxying for ALL configured sessions
2221  */
2222 rlm_rcode_t process_pre_proxy(int type, REQUEST *request)
2223 {
2224         return indexed_modcall(MOD_PRE_PROXY, type, request);
2225 }
2226
2227 /*
2228  *      Do post-proxying for ALL configured sessions
2229  */
2230 rlm_rcode_t process_post_proxy(int type, REQUEST *request)
2231 {
2232         return indexed_modcall(MOD_POST_PROXY, type, request);
2233 }
2234 #endif
2235
2236 /*
2237  *      Do post-authentication for ALL configured sessions
2238  */
2239 rlm_rcode_t process_post_auth(int postauth_type, REQUEST *request)
2240 {
2241         return indexed_modcall(MOD_POST_AUTH, postauth_type, request);
2242 }
2243
2244 #ifdef WITH_COA
2245 rlm_rcode_t process_recv_coa(int recv_coa_type, REQUEST *request)
2246 {
2247         return indexed_modcall(MOD_RECV_COA, recv_coa_type, request);
2248 }
2249
2250 rlm_rcode_t process_send_coa(int send_coa_type, REQUEST *request)
2251 {
2252         return indexed_modcall(MOD_SEND_COA, send_coa_type, request);
2253 }
2254 #endif