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