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