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