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