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