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