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