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