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