Massive change to the server core to remove horrid code in
[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/autoconf.h>
28
29 #include <stdlib.h>
30 #include <string.h>
31
32 #ifdef HAVE_NETINET_IN_H
33 #include <netinet/in.h>
34 #endif
35
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
38 #endif
39
40 #include <freeradius-devel/radiusd.h>
41 #include <freeradius-devel/rad_assert.h>
42 #include <freeradius-devel/modules.h>
43
44 #include <sys/resource.h>
45 #include <netdb.h>
46 #include <sys/stat.h>
47 #include <grp.h>
48 #include <pwd.h>
49
50 #ifdef HAVE_SYS_PRTCL_H
51 #include <sys/prctl.h>
52 #endif
53
54 #ifdef HAVE_SYSLOG_H
55 #       include <syslog.h>
56 #endif
57
58 struct main_config_t mainconfig;
59
60 /*
61  *      Temporary local variables for parsing the configuration
62  *      file.
63  */
64 static uid_t server_uid;
65 static gid_t server_gid;
66
67 /*
68  *      These are not used anywhere else..
69  */
70 static const char *localstatedir = NULL;
71 static const char *prefix = NULL;
72 static char *syslog_facility = NULL;
73 static const LRAD_NAME_NUMBER str2fac[] = {
74 #ifdef LOG_KERN
75         { "kern", LOG_KERN },
76 #endif  
77 #ifdef LOG_USER
78         { "user", LOG_USER },
79 #endif
80 #ifdef LOG_MAIL
81         { "mail", LOG_MAIL },
82 #endif
83 #ifdef LOG_DAEMON
84         { "daemon", LOG_DAEMON },
85 #endif
86 #ifdef LOG_AUTH
87         { "auth", LOG_AUTH },
88 #endif
89 #ifdef LOG_LPR
90         { "lpr", LOG_LPR },
91 #endif
92 #ifdef LOG_NEWS
93         { "news", LOG_NEWS },
94 #endif
95 #ifdef LOG_UUCP
96         { "uucp", LOG_UUCP },
97 #endif
98 #ifdef LOG_CRON
99         { "cron", LOG_CRON },
100 #endif
101 #ifdef LOG_AUTHPRIV
102         { "authpriv", LOG_AUTHPRIV },
103 #endif
104 #ifdef LOG_FTP
105         { "ftp", LOG_FTP },
106 #endif
107 #ifdef LOG_LOCAL0
108         { "local0", LOG_LOCAL0 },
109 #endif
110 #ifdef LOG_LOCAL1
111         { "local1", LOG_LOCAL1 },
112 #endif
113 #ifdef LOG_LOCAL2
114         { "local2", LOG_LOCAL2 },
115 #endif
116 #ifdef LOG_LOCAL3
117         { "local3", LOG_LOCAL3 },
118 #endif
119 #ifdef LOG_LOCAL4
120         { "local4", LOG_LOCAL4 },
121 #endif
122 #ifdef LOG_LOCAL5
123         { "local5", LOG_LOCAL5 },
124 #endif
125 #ifdef LOG_LOCAL6
126         { "local6", LOG_LOCAL6 },
127 #endif
128 #ifdef LOG_LOCAL7
129         { "local7", LOG_LOCAL7 },
130 #endif
131         { NULL, -1 }
132 };
133
134 /*
135  *  Map the proxy server configuration parameters to variables.
136  */
137 static const CONF_PARSER proxy_config[] = {
138         { "retry_delay",  PW_TYPE_INTEGER, 0, &mainconfig.proxy_retry_delay, Stringify(RETRY_DELAY) },
139         { "retry_count",  PW_TYPE_INTEGER, 0, &mainconfig.proxy_retry_count, Stringify(RETRY_COUNT) },
140         { "default_fallback", PW_TYPE_BOOLEAN, 0, &mainconfig.proxy_fallback, "no" },
141         { "dead_time",    PW_TYPE_INTEGER, 0, &mainconfig.proxy_dead_time, Stringify(DEAD_TIME) },
142         { "wake_all_if_all_dead", PW_TYPE_BOOLEAN, 0, &mainconfig.wake_all_if_all_dead, "no" },
143         { "proxy_fail_type", PW_TYPE_STRING_PTR, 0, &mainconfig.proxy_fail_type, NULL},
144         { NULL, -1, 0, NULL, NULL }
145 };
146
147
148 /*
149  *  Security configuration for the server.
150  */
151 static const CONF_PARSER security_config[] = {
152         { "max_attributes",  PW_TYPE_INTEGER, 0, &librad_max_attributes, Stringify(0) },
153         { "reject_delay",  PW_TYPE_INTEGER, 0, &mainconfig.reject_delay, Stringify(0) },
154         { "status_server", PW_TYPE_BOOLEAN, 0, &mainconfig.status_server, "no"},
155         { NULL, -1, 0, NULL, NULL }
156 };
157
158
159 /*
160  *  syslog configuration for the server.
161  */
162 static const CONF_PARSER log_config[] = {
163         { "syslog_facility",  PW_TYPE_STRING_PTR, 0, &syslog_facility, Stringify(0) },
164         { NULL, -1, 0, NULL, NULL }
165 };
166
167
168 /*
169  *  A mapping of configuration file names to internal variables
170  */
171 static const CONF_PARSER server_config[] = {
172         /*
173          *      FIXME: 'prefix' is the ONLY one which should be
174          *      configured at compile time.  Hard-coding it here is
175          *      bad.  It will be cleaned up once we clean up the
176          *      hard-coded defines for the locations of the various
177          *      files.
178          */
179         { "prefix",             PW_TYPE_STRING_PTR, 0, &prefix,            "/usr/local"},
180         { "localstatedir",      PW_TYPE_STRING_PTR, 0, &localstatedir,     "${prefix}/var"},
181         { "logdir",             PW_TYPE_STRING_PTR, 0, &radlog_dir,        "${localstatedir}/log"},
182         { "libdir",             PW_TYPE_STRING_PTR, 0, &radlib_dir,        "${prefix}/lib"},
183         { "radacctdir",         PW_TYPE_STRING_PTR, 0, &radacct_dir,       "${logdir}/radacct" },
184         { "hostname_lookups",   PW_TYPE_BOOLEAN,    0, &librad_dodns,      "no" },
185 #ifdef WITH_SNMP
186         { "snmp",               PW_TYPE_BOOLEAN,    0, &mainconfig.do_snmp,      "no" },
187 #endif
188         { "max_request_time", PW_TYPE_INTEGER, 0, &mainconfig.max_request_time, Stringify(MAX_REQUEST_TIME) },
189         { "cleanup_delay", PW_TYPE_INTEGER, 0, &mainconfig.cleanup_delay, Stringify(CLEANUP_DELAY) },
190         { "max_requests", PW_TYPE_INTEGER, 0, &mainconfig.max_requests, Stringify(MAX_REQUESTS) },
191 #ifdef DELETE_BLOCKED_REQUESTS
192         { "delete_blocked_requests", PW_TYPE_INTEGER, 0, &mainconfig.kill_unresponsive_children, Stringify(FALSE) },
193 #endif
194         { "allow_core_dumps", PW_TYPE_BOOLEAN, 0, &mainconfig.allow_core_dumps, "no" },
195         { "log_stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names,"no" },
196
197         { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
198         { "log_auth", PW_TYPE_BOOLEAN, -1, &mainconfig.log_auth, "no" },
199         { "log_auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, "no" },
200         { "log_auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, "no" },
201         { "pidfile", PW_TYPE_STRING_PTR, 0, &mainconfig.pid_file, "${run_dir}/radiusd.pid"},
202         { "user", PW_TYPE_STRING_PTR, 0, &mainconfig.uid_name, NULL},
203         { "group", PW_TYPE_STRING_PTR, 0, &mainconfig.gid_name, NULL},
204         { "checkrad", PW_TYPE_STRING_PTR, 0, &mainconfig.checkrad, "${sbindir}/checkrad" },
205
206         { "debug_level", PW_TYPE_INTEGER, 0, &mainconfig.debug_level, "0"},
207
208         { "proxy_requests", PW_TYPE_BOOLEAN, 0, &mainconfig.proxy_requests, "yes" },
209         { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
210         { "proxy", PW_TYPE_SUBSECTION, 0, NULL, (const void *) proxy_config },
211         { "security", PW_TYPE_SUBSECTION, 0, NULL, (const void *) security_config },
212         { NULL, -1, 0, NULL, NULL }
213 };
214
215
216 #define MAX_ARGV (256)
217 /*
218  *      Xlat for %{config:section.subsection.attribute}
219  */
220 static int xlat_config(void *instance, REQUEST *request,
221                        char *fmt, char *out,
222                        size_t outlen,
223                        RADIUS_ESCAPE_STRING func)
224 {
225         CONF_SECTION *cs;
226         CONF_PAIR *cp;
227         int i, argc, left;
228         const char *from, *value;
229         char *to;
230         char myfmt[1024];
231         char argv_buf[1024];
232         char *argv[MAX_ARGV];
233
234         request = request;      /* -Wunused */
235         instance = instance;    /* -Wunused */
236
237         cp = NULL;
238         cs = NULL;
239
240         /*
241          *      Split the string into argv's BEFORE doing radius_xlat...
242          *      Copied from exec.c
243          */
244         from = fmt;
245         to = myfmt; 
246         argc = 0;
247         while (*from) {
248                 int flag, length;
249                 
250                 flag = 0;
251                 argv[argc] = to;
252                 argc++;
253                 
254                 if (argc >= (MAX_ARGV - 1)) break;
255                 
256                 /*
257                  *      Copy the argv over to our buffer.
258                  */
259                 while (*from) {
260                         if (to >= myfmt + sizeof(myfmt) - 1) {
261                                 return 0; /* no error msg */
262                         }
263
264                         switch (*from) {
265                         case '%':
266                                 if (from[1] == '{') {
267                                         *(to++) = *(from++);
268                                         
269                                         length = rad_copy_variable(to, from);
270                                         if (length < 0) {
271                                                 return -1;
272                                         }
273                                         from += length;
274                                         to += length;
275                                 } else { /* FIXME: catch %%{ ? */
276                                         *(to++) = *(from++);
277                                 }
278                                 break;
279
280                         case '[':
281                                 if (flag != 0) {
282                                         radlog(L_ERR, "config: Unexpected nested '[' in \"%s\"", fmt);
283                                         return 0;
284                                 }
285                                 flag++;
286                                 *(to++) = *(from++);
287                                 break;
288
289                         case ']':
290                                 if (flag == 0) {
291                                         radlog(L_ERR, "config: Unbalanced ']' in \"%s\"", fmt);
292                                         return 0;
293                                 }
294                                 if (from[1] != '.') {
295                                         radlog(L_ERR, "config: Unexpected text after ']' in \"%s\"", fmt);
296                                         return 0;
297                                 }
298
299                                 flag--;
300                                 *(to++) = *(from++);
301                                 break;
302
303                         case '.':
304                                 if (flag == 0) break;
305                                 /* FALL-THROUGH */
306
307                         default:
308                                 *(to++) = *(from++);
309                                 break;
310                         }
311
312                         if ((*from == '.') && (flag == 0)) {
313                                 from++;
314                                 break;
315                         }
316                 } /* end of string, or found a period */
317
318                 if (flag != 0) {
319                         radlog(L_ERR, "config: Unbalanced '[' in \"%s\"", fmt);
320                         return 0;
321                 }
322
323                 *(to++) = '\0'; /* terminate the string. */
324         }
325
326         /*
327          *      Expand each string, as appropriate
328          */
329         to = argv_buf;
330         left = sizeof(argv_buf);
331         for (i = 0; i < argc; i++) {
332                 int sublen;
333
334                 /*
335                  *      Don't touch argv's which won't be translated.
336                  */
337                 if (strchr(argv[i], '%') == NULL) continue;
338
339                 sublen = radius_xlat(to, left - 1, argv[i], request, NULL);
340                 if (sublen <= 0) {
341                         /*
342                          *      Fail to be backwards compatible.
343                          *
344                          *      It's yucky, but it won't break anything,
345                          *      and it won't cause security problems.
346                          */
347                         sublen = 0;
348                 }
349                 
350                 argv[i] = to;
351                 to += sublen;
352                 *(to++) = '\0';
353                 left -= sublen;
354                 left--;
355
356                 if (left <= 0) {
357                         return 0;
358                 }
359         }
360         argv[argc] = NULL;
361
362         cs = cf_section_find(NULL); /* get top-level section */
363
364         /*
365          *      Root through section & subsection references.
366          *      The last entry of argv MUST be the CONF_PAIR.
367          */
368         for (i = 0; i < argc - 1; i++) {
369                 char *name2 = NULL;
370                 CONF_SECTION *subcs;
371
372                 /*
373                  *      FIXME: What about RADIUS attributes containing '['?
374                  */
375                 name2 = strchr(argv[i], '[');
376                 if (name2) {
377                         char *p = strchr(name2, ']');
378                         rad_assert(p != NULL);
379                         rad_assert(p[1] =='\0');
380                         *p = '\0';
381                         *name2 = '\0';
382                         name2++;
383                 }
384
385                 if (name2) {
386                         subcs = cf_section_sub_find_name2(cs, argv[i],
387                                                           name2);
388                         if (!subcs) {
389                           radlog(L_ERR, "config: section \"%s %s {}\" not found while dereferencing \"%s\"", argv[i], name2, fmt);
390                           return 0;
391                         }
392                 } else {
393                         subcs = cf_section_sub_find(cs, argv[i]);
394                         if (!subcs) {
395                           radlog(L_ERR, "config: section \"%s {}\" not found while dereferencing \"%s\"", argv[i], fmt);
396                           return 0;
397                         }
398                 }
399                 cs = subcs;
400         } /* until argc - 1 */
401
402         /*
403          *      This can now have embedded periods in it.
404          */
405         cp = cf_pair_find(cs, argv[argc - 1]);
406         if (!cp) {
407                 radlog(L_ERR, "config: item \"%s\" not found while dereferencing \"%s\"", argv[argc], fmt);
408                 return 0;
409         }
410
411         /*
412          *  Ensure that we only copy what's necessary.
413          *
414          *  If 'outlen' is too small, then the output is chopped to fit.
415          */
416         value = cf_pair_value(cp);
417         if (value) {
418                 if (outlen > strlen(value)) {
419                         outlen = strlen(value) + 1;
420                 }
421         }
422
423         return func(out, outlen, value);
424 }
425
426
427 /*
428  *      Recursively make directories.
429  */
430 static int r_mkdir(const char *part)
431 {
432         char *ptr, parentdir[500];
433         struct stat st;
434
435         if (stat(part, &st) == 0)
436                 return(0);
437
438         ptr = strrchr(part, '/');
439
440         if (ptr == part)
441                 return(0);
442
443         snprintf(parentdir, (ptr - part)+1, "%s", part);
444
445         if (r_mkdir(parentdir) != 0)
446                 return(1);
447
448         if (mkdir(part, 0770) != 0) {
449                 radlog(L_ERR, "mkdir(%s) error: %s\n", part, strerror(errno));
450                 return(1);
451         }
452
453         return(0);
454 }
455
456 /*
457  *      Checks if the log directory is writeable by a particular user.
458  */
459 static int radlogdir_iswritable(const char *effectiveuser)
460 {
461         struct passwd *pwent;
462
463         if (!radlog_dir || radlog_dir[0] != '/')
464                 return(0);
465
466         if (r_mkdir(radlog_dir) != 0)
467                 return(1);
468
469         /* FIXME: do we have this function? */
470         if (strstr(radlog_dir, "radius") == NULL)
471                 return(0);
472
473         /* we have a logdir that mentions 'radius', so it's probably
474          * safe to chown the immediate directory to be owned by the normal
475          * process owner. we gotta do it before we give up root.  -chad
476          */
477
478         if (!effectiveuser) {
479                 return 1;
480         }
481
482         pwent = getpwnam(effectiveuser);
483
484         if (pwent == NULL) /* uh oh! */
485                 return(1);
486
487         if (chown(radlog_dir, pwent->pw_uid, -1) != 0)
488                 return(1);
489
490         return(0);
491 }
492
493
494 /*
495  *  Switch UID and GID to what is specified in the config file
496  */
497 static int switch_users(void)
498 {
499         struct rlimit core_limits;
500
501         /*  Set GID.  */
502         if (mainconfig.gid_name != NULL) {
503                 struct group *gr;
504
505                 gr = getgrnam(mainconfig.gid_name);
506                 if (gr == NULL) {
507                         if (errno == ENOMEM) {
508                                 radlog(L_ERR|L_CONS, "Cannot switch to Group %s: out of memory", mainconfig.gid_name);
509                         } else {
510                                 radlog(L_ERR|L_CONS, "Cannot switch group; %s doesn't exist", mainconfig.gid_name);
511                         }
512                         exit(1);
513                 }
514                 server_gid = gr->gr_gid;
515                 if (setgid(server_gid) < 0) {
516                         radlog(L_ERR|L_CONS, "Failed setting Group to %s: %s",
517                                mainconfig.gid_name, strerror(errno));
518                         exit(1);
519                 }
520         } else {
521                 server_gid = getgid();
522         }
523
524         /*  Set UID.  */
525         if (mainconfig.uid_name != NULL) {
526                 struct passwd *pw;
527
528                 pw = getpwnam(mainconfig.uid_name);
529                 if (pw == NULL) {
530                         if (errno == ENOMEM) {
531                                 radlog(L_ERR|L_CONS, "Cannot switch to User %s: out of memory", mainconfig.uid_name);
532                         } else {
533                                 radlog(L_ERR|L_CONS, "Cannot switch user; %s doesn't exist", mainconfig.uid_name);
534                         }
535                         exit(1);
536                 }
537                 server_uid = pw->pw_uid;
538 #ifdef HAVE_INITGROUPS
539                 if (initgroups(mainconfig.uid_name, server_gid) < 0) {
540                         if (errno != EPERM) {
541                                 radlog(L_ERR|L_CONS, "Failed setting supplementary groups for User %s: %s", mainconfig.uid_name, strerror(errno));
542                                 exit(1);
543                         }
544                 }
545 #endif
546                 if (setuid(server_uid) < 0) {
547                         radlog(L_ERR|L_CONS, "Failed setting User to %s: %s", mainconfig.uid_name, strerror(errno));
548                         exit(1);
549                 }
550         }
551
552         /*  Get the current maximum for core files.  */
553         if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
554                 radlog(L_ERR|L_CONS, "Failed to get current core limit:  %s", strerror(errno));
555                 exit(1);
556         }
557
558         if (mainconfig.allow_core_dumps) {
559 #ifdef HAVE_SYS_PRTCL_H
560 #ifdef PR_SET_DUMPABLE
561                 if (prctl(PR_SET_DUMPABLE, 1) < 0) {
562                         radlog(L_ERR|L_CONS,"Cannot enable core dumps: prctl(PR_SET_DUMPABLE) failed: '%s'",
563                                strerror(errno));
564                 }
565 #endif
566 #endif
567
568                 if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
569                         radlog(L_ERR|L_CONS, "Cannot update core dump limit: %s",
570                                         strerror(errno));
571                         exit(1);
572
573                         /*
574                          *  If we're running as a daemon, and core
575                          *  dumps are enabled, log that information.
576                          */
577                 } else if ((core_limits.rlim_cur != 0) && !debug_flag)
578                         radlog(L_INFO|L_CONS, "Core dumps are enabled.");
579
580         } else if (!debug_flag) {
581                 /*
582                  *  Not debugging.  Set the core size to zero, to
583                  *  prevent security breaches.  i.e. People
584                  *  reading passwords from the 'core' file.
585                  */
586                 struct rlimit limits;
587
588                 limits.rlim_cur = 0;
589                 limits.rlim_max = core_limits.rlim_max;
590
591                 if (setrlimit(RLIMIT_CORE, &limits) < 0) {
592                         radlog(L_ERR|L_CONS, "Cannot disable core dumps: %s",
593                                         strerror(errno));
594                         exit(1);
595                 }
596         }
597
598         /*
599          *      We've probably written to the log file already as
600          *      root.root, so if we have switched users, we've got to
601          *      update the ownership of the file.
602          */
603         if ((debug_flag == 0) &&
604             (mainconfig.radlog_dest == RADLOG_FILES) &&
605             (mainconfig.log_file != NULL)) {
606                 chown(mainconfig.log_file, server_uid, server_gid);
607         }
608
609         return(0);
610 }
611
612
613 static const LRAD_NAME_NUMBER str2dest[] = {
614         { "null", RADLOG_NULL },
615         { "files", RADLOG_FILES },
616         { "syslog", RADLOG_SYSLOG },
617         { "stdout", RADLOG_STDOUT },
618         { "stderr", RADLOG_STDERR },
619         { NULL, RADLOG_NUM_DEST }
620 };
621
622
623 /*
624  *      Read config files.
625  *
626  *      This function can ONLY be called from the main server process.
627  */
628 int read_mainconfig(int reload)
629 {
630         static int old_debug_level = -1;
631         char buffer[1024];
632         CONF_SECTION *cs, *oldcs;
633         rad_listen_t *listener;
634         struct stat statbuf;
635
636         if (stat(radius_dir, &statbuf) < 0) {
637                 radlog(L_ERR|L_CONS, "Errors reading %s: %s",
638                        radius_dir, strerror(errno));
639                 return -1;
640         }
641
642         if ((statbuf.st_mode & S_IWOTH) != 0) {
643                 radlog(L_ERR|L_CONS, "Configuration directory %s is globally writable.  Refusing to start due to insecure configuration.",
644                        radius_dir);
645           return -1;
646         }
647
648
649         if (0 && (statbuf.st_mode & S_IROTH) != 0) {
650                 radlog(L_ERR|L_CONS, "Configuration directory %s is globally readable.  Refusing to start due to insecure configuration.",
651                        radius_dir);
652                 return -1;
653         }
654
655         /* Read the configuration file */
656         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
657                  radius_dir, mainconfig.radiusd_conf);
658         if ((cs = cf_file_read(buffer)) == NULL) {
659                 radlog(L_ERR|L_CONS, "Errors reading %s", buffer);
660                 return -1;
661         }
662
663         /*
664          *      Debug flag 1 MAY go to files.
665          *      Debug flag 2 ALWAYS goes to stdout
666          *
667          *      Parse the log_destination before printing anything else.
668          *      All messages before this MUST be errors, which log.c
669          *      will print to stderr, since log_file is NULL, too.
670          */
671         if (debug_flag < 2) {
672                 int rcode;
673                 char *radlog_dest = NULL;
674
675                 rcode = cf_item_parse(cs, "log_destination",
676                                       PW_TYPE_STRING_PTR, &radlog_dest,
677                                       "files");
678                 if (rcode < 0) return -1;
679         
680                 mainconfig.radlog_dest = lrad_str2int(str2dest, radlog_dest, RADLOG_NUM_DEST);
681                 if (mainconfig.radlog_dest == RADLOG_NUM_DEST) {
682                         fprintf(stderr, "radiusd: Error: Unknown log_destination %s\n",
683                                 radlog_dest);
684                         free(radlog_dest);
685                         cf_section_free(&cs);
686                         return -1;
687                 }
688                 
689                 if (mainconfig.radlog_dest == RADLOG_SYSLOG) {
690                         static const CONF_PARSER syslog_config[] = {
691                                 { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
692                                 { NULL, -1, 0, NULL, NULL }
693                         };
694                         cf_section_parse(cs, NULL, syslog_config);
695
696                         /*
697                          *      Make sure syslog_facility isn't NULL before using it
698                          */
699                         if (!syslog_facility) {
700                                 fprintf(stderr, "radiusd: Error: Unknown syslog chosen but no facility spedified\n");
701                                 free(radlog_dest);
702                                 cf_section_free(&cs);
703                                 return -1;
704                         }
705                         mainconfig.syslog_facility = lrad_str2int(str2fac, syslog_facility, -1);
706                         if (mainconfig.syslog_facility < 0) {
707                                 fprintf(stderr, "radiusd: Error: Unknown syslog_facility %s\n",
708                                         syslog_facility);
709                                 free(radlog_dest);
710                                 free(syslog_facility);
711                                 cf_section_free(&cs);
712                                 return -1;
713                         }
714                 }
715
716                 if (mainconfig.radlog_dest == RADLOG_FILES) {
717                         static const CONF_PARSER file_config[] = {
718                                 { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
719                                 { NULL, -1, 0, NULL, NULL }
720                         };
721
722                         cf_section_parse(cs, NULL, file_config);
723                 }
724
725                 free(radlog_dest);
726         } else {
727                 mainconfig.radlog_dest = RADLOG_STDOUT;
728                 mainconfig.radlog_fd = STDOUT_FILENO;
729         }
730
731         radlog(L_INFO, "%s", radiusd_version);
732         if (!reload) {
733                 radlog(L_INFO, "Starting - reading configuration files ...");
734         } else {
735                 radlog(L_INFO, "Reloading - reading configuration files...");
736         }
737
738         /* Initialize the dictionary */
739         DEBUG2("read_config_files:  reading dictionary");
740         if (dict_init(radius_dir, RADIUS_DICTIONARY) != 0) {
741                 radlog(L_ERR|L_CONS, "Errors reading dictionary: %s",
742                                 librad_errstr);
743                 return -1;
744         }
745
746         /*
747          *      This allows us to figure out where, relative to
748          *      radiusd.conf, the other configuration files exist.
749          */
750         cf_section_parse(cs, NULL, server_config);
751
752 #if 0
753         /*
754          *      Merge the old with the new.
755          */
756         if (reload) {
757                 CONF_SECTION *newcs;
758
759                 newcs = cf_section_sub_find(cs, "modules");
760                 oldcs = cf_section_sub_find(mainconfig.config, "modules");
761                 if (newcs && oldcs) {
762                         if (!cf_section_migrate(newcs, oldcs)) {
763                                 radlog(L_ERR|L_CONS, "Fatal error migrating configuration data");
764                                 return -1;
765                         }
766                 }
767         }
768 #endif
769
770         /*
771          *      Free the old configuration items, and replace them
772          *      with the new ones.
773          *
774          *      Note that where possible, we do atomic switch-overs,
775          *      to ensure that the pointers are always valid.
776          */
777         oldcs = mainconfig.config;
778         mainconfig.config = cs;
779         cf_section_free(&oldcs);
780
781         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
782                  radius_dir, mainconfig.radiusd_conf);
783         if (!realms_init(buffer)) {
784                 return -1;
785         }
786
787         /*
788          *  Register the %{config:section.subsection} xlat function.
789          */
790         xlat_register("config", xlat_config, NULL);
791
792         /*
793          *      Set the libraries debugging flag to whatever the main
794          *      flag is.  Note that on a SIGHUP, to turn the debugging
795          *      off, we do other magic.
796          *
797          *      Increase the debug level, if the configuration file
798          *      says to, OR, if we're decreasing the debug from what it
799          *      was before, allow that, too.
800          */
801         if ((mainconfig.debug_level > debug_flag) ||
802             (mainconfig.debug_level <= old_debug_level)) {
803                 debug_flag = mainconfig.debug_level;
804         }
805         librad_debug = debug_flag;
806         old_debug_level = mainconfig.debug_level;
807
808         /*
809          *  Go update our behaviour, based on the configuration
810          *  changes.
811          */
812
813         /*
814          *      The first time around, ensure that we can write to the
815          *      log directory.
816          */
817         if (!reload) {
818                 /*
819                  *      We need root to do mkdir() and chown(), so we
820                  *      do this before giving up root.
821                  */
822                 radlogdir_iswritable(mainconfig.uid_name);
823         }
824
825         /*
826          *      We should really switch users earlier in the process.
827          */
828         switch_users();
829
830         /*
831          *      Sanity check the configuration for internal
832          *      consistency.
833          */
834         if (mainconfig.reject_delay > mainconfig.cleanup_delay) {
835                 mainconfig.reject_delay = mainconfig.cleanup_delay;
836         }
837
838         /*
839          *      Initialize the old "bind_address" and "port", first.
840          */
841         listener = NULL;
842
843         /*
844          *      Read the list of listeners.
845          */
846         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
847                  radius_dir, mainconfig.radiusd_conf);
848         if (listen_init(buffer, &listener) < 0) {
849                 exit(1);
850         }
851
852         if (!listener) {
853                 radlog(L_ERR|L_CONS, "Server is not configured to listen on any ports.  Exiting.");
854                 exit(1);
855         }
856
857         listen_free(&mainconfig.listen);
858         mainconfig.listen = listener;
859
860         /*
861          *      Walk through the listeners.  If we're listening on acct
862          *      or auth, read in the clients files, else ignore them.
863          */
864         for (listener = mainconfig.listen;
865              listener != NULL;
866              listener = listener->next) {
867                 if ((listener->type == RAD_LISTEN_AUTH) ||
868                     (listener->type == RAD_LISTEN_ACCT)) {
869                         break;
870                 }
871         }
872
873         if (listener != NULL) {
874                 RADCLIENT_LIST *clients, *old_clients;
875
876                 /*
877                  *      Create the new clients first, and add them
878                  *      to the CONF_SECTION, where they're automagically
879                  *      freed if anything goes wrong.
880                  */
881                 snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
882                          radius_dir, mainconfig.radiusd_conf);
883                 clients = clients_parse_section(buffer, mainconfig.config);
884                 if (!clients) {
885                         return -1;
886                 }
887
888                 /*
889                  *      Free the old trees AFTER replacing them with
890                  *      the new ones...
891                  */
892                 old_clients = mainconfig.clients;
893                 mainconfig.clients = clients;
894                 clients_free(old_clients);
895         }
896
897         /*  Reload the modules.  */
898         DEBUG2("radiusd:  entering modules setup");
899         if (setup_modules(reload) < 0) {
900                 radlog(L_ERR|L_CONS, "Errors setting up modules");
901                 return -1;
902         }
903         return 0;
904 }
905
906 /*
907  *      Free the configuration.  Called only when the server is exiting.
908  */
909 int free_mainconfig(void)
910 {
911         /*
912          *      Clean up the configuration data
913          *      structures.
914          */
915         cf_section_free(&mainconfig.config);
916         free(mainconfig.radiusd_conf);
917         realms_free();
918         listen_free(&mainconfig.listen);
919         xlat_free();
920         dict_free();
921         lt_dlexit();
922
923         return 0;
924 }