Call lt_dlexit() AFTER detach modules.
[freeradius.git] / src / main / mainconfig.c
1 /*
2  * mainconf.c   Handle the server's configuration.
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 2002,2006-2007  The FreeRADIUS server project
21  * Copyright 2002  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 #include <sys/stat.h>
32
33 #ifdef HAVE_SYS_RESOURCE_H
34 #include <sys/resource.h>
35 #endif
36
37 #ifdef HAVE_PWD_H
38 #include <pwd.h>
39 #endif
40
41 #ifdef HAVE_GRP_H
42 #include <grp.h>
43 #endif
44
45 #ifdef HAVE_SYS_PRCTL_H
46 #include <sys/prctl.h>
47 #endif
48
49 #ifdef HAVE_SYSLOG_H
50 #       include <syslog.h>
51 #endif
52
53 struct main_config_t mainconfig;
54
55 /*
56  *      Temporary local variables for parsing the configuration
57  *      file.
58  */
59 static uid_t server_uid;
60 static gid_t server_gid;
61 static const char *uid_name = NULL;
62 static const char *gid_name = NULL;
63 static int allow_core_dumps = 0;
64
65 /*
66  *      These are not used anywhere else..
67  */
68 static const char *localstatedir = NULL;
69 static const char *prefix = NULL;
70 static char *syslog_facility = NULL;
71 static const FR_NAME_NUMBER str2fac[] = {
72 #ifdef LOG_KERN
73         { "kern", LOG_KERN },
74 #endif
75 #ifdef LOG_USER
76         { "user", LOG_USER },
77 #endif
78 #ifdef LOG_MAIL
79         { "mail", LOG_MAIL },
80 #endif
81 #ifdef LOG_DAEMON
82         { "daemon", LOG_DAEMON },
83 #endif
84 #ifdef LOG_AUTH
85         { "auth", LOG_AUTH },
86 #endif
87 #ifdef LOG_LPR
88         { "lpr", LOG_LPR },
89 #endif
90 #ifdef LOG_NEWS
91         { "news", LOG_NEWS },
92 #endif
93 #ifdef LOG_UUCP
94         { "uucp", LOG_UUCP },
95 #endif
96 #ifdef LOG_CRON
97         { "cron", LOG_CRON },
98 #endif
99 #ifdef LOG_AUTHPRIV
100         { "authpriv", LOG_AUTHPRIV },
101 #endif
102 #ifdef LOG_FTP
103         { "ftp", LOG_FTP },
104 #endif
105 #ifdef LOG_LOCAL0
106         { "local0", LOG_LOCAL0 },
107 #endif
108 #ifdef LOG_LOCAL1
109         { "local1", LOG_LOCAL1 },
110 #endif
111 #ifdef LOG_LOCAL2
112         { "local2", LOG_LOCAL2 },
113 #endif
114 #ifdef LOG_LOCAL3
115         { "local3", LOG_LOCAL3 },
116 #endif
117 #ifdef LOG_LOCAL4
118         { "local4", LOG_LOCAL4 },
119 #endif
120 #ifdef LOG_LOCAL5
121         { "local5", LOG_LOCAL5 },
122 #endif
123 #ifdef LOG_LOCAL6
124         { "local6", LOG_LOCAL6 },
125 #endif
126 #ifdef LOG_LOCAL7
127         { "local7", LOG_LOCAL7 },
128 #endif
129         { NULL, -1 }
130 };
131
132 /*
133  *  Security configuration for the server.
134  */
135 static const CONF_PARSER security_config[] = {
136         { "max_attributes",  PW_TYPE_INTEGER, 0, &librad_max_attributes, Stringify(0) },
137         { "reject_delay",  PW_TYPE_INTEGER, 0, &mainconfig.reject_delay, Stringify(0) },
138         { "status_server", PW_TYPE_BOOLEAN, 0, &mainconfig.status_server, "no"},
139         { NULL, -1, 0, NULL, NULL }
140 };
141
142
143 /*
144  *  syslog configuration for the server.
145  */
146 static const CONF_PARSER log_config[] = {
147         { "syslog_facility",  PW_TYPE_STRING_PTR, 0, &syslog_facility, Stringify(0) },
148         { NULL, -1, 0, NULL, NULL }
149 };
150
151
152 /*
153  *  A mapping of configuration file names to internal variables
154  */
155 static const CONF_PARSER server_config[] = {
156         /*
157          *      FIXME: 'prefix' is the ONLY one which should be
158          *      configured at compile time.  Hard-coding it here is
159          *      bad.  It will be cleaned up once we clean up the
160          *      hard-coded defines for the locations of the various
161          *      files.
162          */
163         { "prefix",             PW_TYPE_STRING_PTR, 0, &prefix,            "/usr/local"},
164         { "localstatedir",      PW_TYPE_STRING_PTR, 0, &localstatedir,     "${prefix}/var"},
165         { "logdir",             PW_TYPE_STRING_PTR, 0, &radlog_dir,        "${localstatedir}/log"},
166         { "libdir",             PW_TYPE_STRING_PTR, 0, &radlib_dir,        "${prefix}/lib"},
167         { "radacctdir",         PW_TYPE_STRING_PTR, 0, &radacct_dir,       "${logdir}/radacct" },
168         { "hostname_lookups",   PW_TYPE_BOOLEAN,    0, &librad_dodns,      "no" },
169         { "max_request_time", PW_TYPE_INTEGER, 0, &mainconfig.max_request_time, Stringify(MAX_REQUEST_TIME) },
170         { "cleanup_delay", PW_TYPE_INTEGER, 0, &mainconfig.cleanup_delay, Stringify(CLEANUP_DELAY) },
171         { "max_requests", PW_TYPE_INTEGER, 0, &mainconfig.max_requests, Stringify(MAX_REQUESTS) },
172 #ifdef DELETE_BLOCKED_REQUESTS
173         { "delete_blocked_requests", PW_TYPE_INTEGER, 0, &mainconfig.kill_unresponsive_children, Stringify(FALSE) },
174 #endif
175         { "allow_core_dumps", PW_TYPE_BOOLEAN, 0, &allow_core_dumps, "no" },
176         { "log_stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names,"no" },
177
178         { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
179         { "log_auth", PW_TYPE_BOOLEAN, -1, &mainconfig.log_auth, "no" },
180         { "log_auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, "no" },
181         { "log_auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, "no" },
182         { "pidfile", PW_TYPE_STRING_PTR, 0, &mainconfig.pid_file, "${run_dir}/radiusd.pid"},
183         { "user", PW_TYPE_STRING_PTR, 0, &uid_name, NULL},
184         { "group", PW_TYPE_STRING_PTR, 0, &gid_name, NULL},
185         { "checkrad", PW_TYPE_STRING_PTR, 0, &mainconfig.checkrad, "${sbindir}/checkrad" },
186
187         { "debug_level", PW_TYPE_INTEGER, 0, &mainconfig.debug_level, "0"},
188
189         { "proxy_requests", PW_TYPE_BOOLEAN, 0, &mainconfig.proxy_requests, "yes" },
190         { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
191         { "security", PW_TYPE_SUBSECTION, 0, NULL, (const void *) security_config },
192         { NULL, -1, 0, NULL, NULL }
193 };
194
195
196 #define MAX_ARGV (256)
197 /*
198  *      Xlat for %{config:section.subsection.attribute}
199  */
200 static size_t xlat_config(void *instance, REQUEST *request,
201                        char *fmt, char *out,
202                        size_t outlen,
203                        RADIUS_ESCAPE_STRING func)
204 {
205         const char *value;
206         CONF_PAIR *cp;
207         CONF_ITEM *ci;
208
209         request = request;      /* -Wunused */
210         instance = instance;    /* -Wunused */
211
212         /*
213          *      FIXME: radius_xlat, with a function that escapes
214          *      "%{[].\\\'"\`".
215          */
216
217         ci = cf_reference_item(request->root->config,
218                                request->root->config, fmt);
219         if (!ci || !cf_item_is_pair(ci)) {
220                 *out = '\0';
221                 return 0;
222         }
223
224         cp = cf_itemtopair(ci);
225
226         /*
227          *  Ensure that we only copy what's necessary.
228          *
229          *  If 'outlen' is too small, then the output is chopped to fit.
230          */
231         value = cf_pair_value(cp);
232         if (value) {
233                 if (outlen > strlen(value)) {
234                         outlen = strlen(value) + 1;
235                 }
236         }
237
238         return func(out, outlen, value);
239 }
240
241
242 /*
243  *      Xlat for %{client:foo}
244  */
245 static size_t xlat_client(UNUSED void *instance, REQUEST *request,
246                        char *fmt, char *out,
247                        size_t outlen,
248                        UNUSED RADIUS_ESCAPE_STRING func)
249 {
250         const char *value = NULL;
251         CONF_PAIR *cp;
252
253         if (!fmt || !out || (outlen < 1)) return 0;
254
255         if (!request || !request->client) {
256                 *out = '\0';
257                 return 0;
258         }
259
260         cp = cf_pair_find(request->client->cs, fmt);
261         if (!cp || !(value = cf_pair_value(cp))) {
262                 *out = '\0';
263                 return 0;
264         }
265         
266         strlcpy(out, value, outlen);
267
268         return strlen(out);
269 }
270
271 /*
272  *      Recursively make directories.
273  */
274 static int r_mkdir(const char *part)
275 {
276         char *ptr, parentdir[500];
277         struct stat st;
278
279         if (stat(part, &st) == 0)
280                 return(0);
281
282         ptr = strrchr(part, FR_DIR_SEP);
283
284         if (ptr == part)
285                 return(0);
286
287         snprintf(parentdir, (ptr - part)+1, "%s", part);
288
289         if (r_mkdir(parentdir) != 0)
290                 return(1);
291
292         if (mkdir(part, 0770) != 0) {
293                 radlog(L_ERR, "mkdir(%s) error: %s\n", part, strerror(errno));
294                 return(1);
295         }
296
297         return(0);
298 }
299
300 /*
301  *      Checks if the log directory is writeable by a particular user.
302  */
303 static int radlogdir_iswritable(const char *effectiveuser)
304 {
305 #ifdef HAVE_GETPWNAM
306         struct passwd *pwent;
307 #endif
308
309         if (!radlog_dir || FR_DIR_IS_RELATIVE(radlog_dir))
310                 return(0);
311
312         if (r_mkdir(radlog_dir) != 0)
313                 return(1);
314
315         /* FIXME: do we have this function? */
316         if (strstr(radlog_dir, "radius") == NULL)
317                 return(0);
318
319         /* we have a logdir that mentions 'radius', so it's probably
320          * safe to chown the immediate directory to be owned by the normal
321          * process owner. we gotta do it before we give up root.  -chad
322          */
323
324         if (!effectiveuser) {
325                 return 1;
326         }
327
328 #ifdef HAVE_GETPWNAM
329         pwent = getpwnam(effectiveuser);
330
331         if (pwent == NULL) /* uh oh! */
332                 return(1);
333
334         if (chown(radlog_dir, pwent->pw_uid, -1) != 0)
335                 return(1);
336 #endif
337
338         return(0);
339 }
340
341
342 /*
343  *  Switch UID and GID to what is specified in the config file
344  */
345 static int switch_users(void)
346 {
347         int did_setuid = FALSE;
348
349 #ifdef HAVE_SYS_RESOURCE_H
350         struct rlimit core_limits;
351 #endif
352
353 #ifdef HAVE_GRP_H
354         /*  Set GID.  */
355         if (gid_name != NULL) {
356                 struct group *gr;
357
358                 gr = getgrnam(gid_name);
359                 if (gr == NULL) {
360                         if (errno == ENOMEM) {
361                                 radlog(L_ERR, "Cannot switch to Group %s: out of memory", gid_name);
362                         } else {
363                                 radlog(L_ERR, "Cannot switch group; %s doesn't exist", gid_name);
364                         }
365                         return 0;
366                 }
367                 server_gid = gr->gr_gid;
368                 if (setgid(server_gid) < 0) {
369                         radlog(L_ERR, "Failed setting Group to %s: %s",
370                                gid_name, strerror(errno));
371                         return 0;
372                 }
373         } else {
374                 server_gid = getgid();
375         }
376 #endif
377
378 #ifdef HAVE_PWD_H
379         /*  Set UID.  */
380         if (uid_name != NULL) {
381                 struct passwd *pw;
382
383                 pw = getpwnam(uid_name);
384                 if (pw == NULL) {
385                         if (errno == ENOMEM) {
386                                 radlog(L_ERR, "Cannot switch to User %s: out of memory", uid_name);
387                         } else {
388                                 radlog(L_ERR, "Cannot switch user; %s doesn't exist", uid_name);
389                         }
390                         return 0;
391                 }
392                 server_uid = pw->pw_uid;
393 #ifdef HAVE_INITGROUPS
394                 if (initgroups(uid_name, server_gid) < 0) {
395                         if (errno != EPERM) {
396                                 radlog(L_ERR, "Failed setting supplementary groups for User %s: %s", uid_name, strerror(errno));
397                                 return 0;
398                         }
399                 }
400 #endif
401                 if (setuid(server_uid) < 0) {
402                         radlog(L_ERR, "Failed setting User to %s: %s", uid_name, strerror(errno));
403                         return 0;
404                 }
405
406                 /*
407                  *      Now core dumps are disabled on most secure systems.
408                  */
409                 did_setuid = TRUE;
410         }
411 #endif
412
413 #ifdef HAVE_SYS_RESOURCE_H
414         /*  Get the current maximum for core files.  */
415         if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
416                 radlog(L_ERR, "Failed to get current core limit:  %s", strerror(errno));
417                 return 0;
418         }
419 #endif
420
421         /*
422          *      Core dumps are allowed if we're in debug mode, OR
423          *      we've allowed them, OR we did a setuid (which turns
424          *      core dumps off).
425          *
426          *      Otherwise, disable core dumps for security.
427          *      
428          */
429         if (!(debug_flag || allow_core_dumps || did_setuid)) {
430 #ifdef HAVE_SYS_RESOURCE_H
431                 struct rlimit no_core;
432
433                 no_core.rlim_cur = 0;
434                 no_core.rlim_max = 0;
435
436                 if (setrlimit(RLIMIT_CORE, &no_core) < 0) {
437                         radlog(L_ERR, "Failed disabling core dumps: %s",
438                                strerror(errno));
439                         return 0;
440                 }
441 #endif
442
443                 /*
444                  *      Otherwise, re-enable core dumps if we're
445                  *      running as a daemon, AND core dumps are
446                  *      allowed, AND we changed UID's.
447                  */
448         } else if ((debug_flag == 0) && allow_core_dumps && did_setuid) {
449                 /*
450                  *      Set the dumpable flag.
451                  */
452 #ifdef HAVE_SYS_PRCTL_H
453 #ifdef PR_SET_DUMPABLE
454                 if (prctl(PR_SET_DUMPABLE, 1) < 0) {
455                         radlog(L_ERR,"Cannot enable core dumps: prctl(PR_SET_DUMPABLE) failed: '%s'",
456                                strerror(errno));
457                 }
458 #endif
459 #endif
460
461                 /*
462                  *      Reset the core dump limits again, just to
463                  *      double check that they haven't changed.
464                  */
465 #ifdef HAVE_SYS_RESOURCE_H
466                 if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
467                         radlog(L_ERR, "Cannot update core dump limit: %s",
468                                         strerror(errno));
469                         return 0;
470                 }
471 #endif
472
473                 radlog(L_INFO, "Core dumps are enabled.");
474         }
475         /*
476          *      Else we're debugging (so core dumps are enabled)
477          *      OR we're not debugging, AND "allow_core_dumps == FALSE",
478          *      OR we're not debugging, AND core dumps are allowed,
479          *         BUT we didn't call setuid, so we haven't changed the
480          *         core dump capabilities inherited from the parent shell.
481          */
482
483 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
484         /*
485          *      We've probably written to the log file already as
486          *      root.root, so if we have switched users, we've got to
487          *      update the ownership of the file.
488          */
489         if ((debug_flag == 0) &&
490             (mainconfig.radlog_dest == RADLOG_FILES) &&
491             (mainconfig.log_file != NULL)) {
492                 chown(mainconfig.log_file, server_uid, server_gid);
493         }
494 #endif
495         return 1;
496 }
497
498
499 static const FR_NAME_NUMBER str2dest[] = {
500         { "null", RADLOG_NULL },
501         { "files", RADLOG_FILES },
502         { "syslog", RADLOG_SYSLOG },
503         { "stdout", RADLOG_STDOUT },
504         { "stderr", RADLOG_STDERR },
505         { NULL, RADLOG_NUM_DEST }
506 };
507
508
509 /*
510  *      Read config files.
511  *
512  *      This function can ONLY be called from the main server process.
513  */
514 int read_mainconfig(int reload)
515 {
516         static int old_debug_level = -1;
517         char buffer[1024];
518         CONF_SECTION *cs, *templates;
519         struct stat statbuf;
520
521         if (stat(radius_dir, &statbuf) < 0) {
522                 radlog(L_ERR, "Errors reading %s: %s",
523                        radius_dir, strerror(errno));
524                 return -1;
525         }
526
527 #ifdef S_IWOTH
528         if ((statbuf.st_mode & S_IWOTH) != 0) {
529                 radlog(L_ERR, "Configuration directory %s is globally writable.  Refusing to start due to insecure configuration.",
530                        radius_dir);
531           return -1;
532         }
533 #endif
534
535 #ifdef S_IROTH
536         if (0 && (statbuf.st_mode & S_IROTH) != 0) {
537                 radlog(L_ERR, "Configuration directory %s is globally readable.  Refusing to start due to insecure configuration.",
538                        radius_dir);
539                 return -1;
540         }
541 #endif
542
543         if (!reload) {
544                 radlog(L_INFO, "Starting - reading configuration files ...");
545         } else {
546                 radlog(L_INFO, "Reloading - reading configuration files...");
547         }
548
549         /* Read the configuration file */
550         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
551                  radius_dir, mainconfig.radiusd_conf);
552         if ((cs = cf_file_read(buffer)) == NULL) {
553                 radlog(L_ERR, "Errors reading %s", buffer);
554                 return -1;
555         }
556
557         /*
558          *      Add templates to each kind of subsection.
559          */
560         templates = cf_section_sub_find(cs, "templates");
561         if (templates) {
562                 CONF_SECTION *ts, *mycs;
563
564                 /*
565                  *      Loop over the templates, adding them to the
566                  *      sections in the main configuration file.
567                  */
568                 for (ts = cf_subsection_find_next(templates, NULL, NULL);
569                      ts != NULL;
570                      ts = cf_subsection_find_next(templates, ts, NULL)) {
571                         const char *name1 = cf_section_name1(ts);
572
573                         /*
574                          *      Loop over sections in the main config
575                          *      file, adding templats.
576                          */
577                         for (mycs = cf_subsection_find_next(cs, NULL, name1);
578                              mycs != NULL;
579                              mycs = cf_subsection_find_next(cs, mycs, name1)) {
580                                 const char *value;
581
582                                 value = cf_section_value_find(mycs, "template");
583                                 if (value) {
584                                         CONF_SECTION *tts;
585
586                                         tts = cf_section_sub_find_name2(templates,
587                                                                         name1,
588                                                                         value);
589                                         if (!tts) {
590                                                 radlog(L_ERR, "%s[%d]: Section refers to non-existent template \"%s\"",
591                                                        cf_section_filename(mycs), cf_section_lineno(mycs), value);
592                                                 return -1;
593                                         }
594                                         cf_section_template(mycs, tts);
595                                 } else {
596                                         cf_section_template(mycs, ts);
597                                 }
598                         }
599                 }
600         }
601
602         /*
603          *      Debug flag 1 MAY go to files.
604          *      Debug flag 2 ALWAYS goes to stdout
605          *
606          *      Parse the log_destination before printing anything else.
607          *      All messages before this MUST be errors, which log.c
608          *      will print to stderr, since log_file is NULL, too.
609          */
610         if (debug_flag < 2) {
611                 int rcode;
612                 char *radlog_dest = NULL;
613
614                 rcode = cf_item_parse(cs, "log_destination",
615                                       PW_TYPE_STRING_PTR, &radlog_dest,
616                                       "files");
617                 if (rcode < 0) return -1;
618
619                 mainconfig.radlog_dest = fr_str2int(str2dest, radlog_dest, RADLOG_NUM_DEST);
620                 if (mainconfig.radlog_dest == RADLOG_NUM_DEST) {
621                         fprintf(stderr, "radiusd: Error: Unknown log_destination %s\n",
622                                 radlog_dest);
623                         free(radlog_dest);
624                         cf_section_free(&cs);
625                         return -1;
626                 }
627
628                 if (mainconfig.radlog_dest == RADLOG_SYSLOG) {
629                         static const CONF_PARSER syslog_config[] = {
630                                 { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
631                                 { NULL, -1, 0, NULL, NULL }
632                         };
633                         cf_section_parse(cs, NULL, syslog_config);
634
635                         /*
636                          *      Make sure syslog_facility isn't NULL before using it
637                          */
638                         if (!syslog_facility) {
639                                 fprintf(stderr, "radiusd: Error: Unknown syslog chosen but no facility spedified\n");
640                                 free(radlog_dest);
641                                 cf_section_free(&cs);
642                                 return -1;
643                         }
644                         mainconfig.syslog_facility = fr_str2int(str2fac, syslog_facility, -1);
645                         if (mainconfig.syslog_facility < 0) {
646                                 fprintf(stderr, "radiusd: Error: Unknown syslog_facility %s\n",
647                                         syslog_facility);
648                                 free(radlog_dest);
649                                 free(syslog_facility);
650                                 cf_section_free(&cs);
651                                 return -1;
652                         }
653                 }
654
655                 if (mainconfig.radlog_dest == RADLOG_FILES) {
656                         static const CONF_PARSER file_config[] = {
657                                 { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
658                                 { NULL, -1, 0, NULL, NULL }
659                         };
660
661                         cf_section_parse(cs, NULL, file_config);
662                 }
663
664                 free(radlog_dest);
665         } else {
666                 mainconfig.radlog_dest = RADLOG_STDOUT;
667                 mainconfig.radlog_fd = STDOUT_FILENO;
668         }
669
670         /* Initialize the dictionary */
671         DEBUG2("including dictionary file %s/%s", radius_dir, RADIUS_DICTIONARY);
672         if (dict_init(radius_dir, RADIUS_DICTIONARY) != 0) {
673                 radlog(L_ERR, "Errors reading dictionary: %s",
674                                 librad_errstr);
675                 return -1;
676         }
677
678         /*
679          *      This allows us to figure out where, relative to
680          *      radiusd.conf, the other configuration files exist.
681          */
682         cf_section_parse(cs, NULL, server_config);
683
684 #if 0
685         /*
686          *      Merge the old with the new.
687          */
688         if (reload) {
689                 CONF_SECTION *newcs;
690
691                 newcs = cf_section_sub_find(cs, "modules");
692                 oldcs = cf_section_sub_find(mainconfig.config, "modules");
693                 if (newcs && oldcs) {
694                         if (!cf_section_migrate(newcs, oldcs)) {
695                                 radlog(L_ERR, "Fatal error migrating configuration data");
696                                 return -1;
697                         }
698                 }
699         }
700 #endif
701
702         /*
703          *      Free the old configuration items, and replace them
704          *      with the new ones.
705          *
706          *      Note that where possible, we do atomic switch-overs,
707          *      to ensure that the pointers are always valid.
708          */
709         cf_section_free(&mainconfig.config);
710         mainconfig.config = cs;
711
712         clients_parse_section(cs);
713
714         DEBUG2("radiusd: #### Loading Realms and Home Servers ####");
715
716         if (!realms_init(cs)) {
717                 return -1;
718         }
719
720         /*
721          *  Register the %{config:section.subsection} xlat function.
722          */
723         xlat_register("config", xlat_config, NULL);
724         xlat_register("client", xlat_client, NULL);
725
726         /*
727          *      Reload: change debug flag if it's changed in the
728          *      configuration file.
729          */
730         if (reload) {
731                 if (mainconfig.debug_level != old_debug_level) {
732                         debug_flag = mainconfig.debug_level;
733                 }
734
735         } else if (debug_flag == 0) {
736
737                 /*
738                  *      Starting the server, WITHOUT "-x" on the
739                  *      command-line: use whatever's in the config
740                  *      file.
741                  */
742                 debug_flag = mainconfig.debug_level;
743         }
744         librad_debug = debug_flag;
745         old_debug_level = mainconfig.debug_level;
746
747         /*
748          *  Go update our behaviour, based on the configuration
749          *  changes.
750          */
751
752         /*
753          *      The first time around, ensure that we can write to the
754          *      log directory.
755          */
756         if (!reload) {
757                 /*
758                  *      We need root to do mkdir() and chown(), so we
759                  *      do this before giving up root.
760                  */
761                 radlogdir_iswritable(uid_name);
762         }
763
764         /*
765          *      We should really switch users earlier in the process.
766          */
767         if (!switch_users()) exit(1);
768
769         /*
770          *      Sanity check the configuration for internal
771          *      consistency.
772          */
773         if (mainconfig.reject_delay > mainconfig.cleanup_delay) {
774                 mainconfig.reject_delay = mainconfig.cleanup_delay;
775         }
776         if (mainconfig.reject_delay < 0) mainconfig.reject_delay = 0;
777
778         /*  Reload the modules.  */
779         if (setup_modules(reload, mainconfig.config) < 0) {
780                 radlog(L_ERR, "Errors initializing modules");
781                 return -1;
782         }
783
784         return 0;
785 }
786
787 /*
788  *      Free the configuration.  Called only when the server is exiting.
789  */
790 int free_mainconfig(void)
791 {
792         /*
793          *      Clean up the configuration data
794          *      structures.
795          */
796         cf_section_free(&mainconfig.config);
797         free(mainconfig.radiusd_conf);
798         realms_free();
799         listen_free(&mainconfig.listen);
800         dict_free();
801
802         return 0;
803 }