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