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