Parse clients from the main config section, which initializes
[freeradius.git] / src / main / mainconfig.c
1 /*
2  * mainconf.c   Handle the server's configuration.
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2002,2006-2007  The FreeRADIUS server project
21  * Copyright 2002  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 #include <sys/stat.h>
32
33 #ifdef HAVE_SYS_RESOURCE_H
34 #include <sys/resource.h>
35 #endif
36
37 #ifdef HAVE_PWD_H
38 #include <pwd.h>
39 #endif
40
41 #ifdef HAVE_GRP_H
42 #include <grp.h>
43 #endif
44
45 #ifdef HAVE_SYS_PRCTL_H
46 #include <sys/prctl.h>
47 #endif
48
49 #ifdef HAVE_SYSLOG_H
50 #       include <syslog.h>
51 #endif
52
53 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, &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         int did_setuid = FALSE;
513
514 #ifdef HAVE_SYS_RESOURCE_H
515         struct rlimit core_limits;
516 #endif
517
518 #ifdef HAVE_GRP_H
519         /*  Set GID.  */
520         if (gid_name != NULL) {
521                 struct group *gr;
522
523                 gr = getgrnam(gid_name);
524                 if (gr == NULL) {
525                         if (errno == ENOMEM) {
526                                 radlog(L_ERR, "Cannot switch to Group %s: out of memory", gid_name);
527                         } else {
528                                 radlog(L_ERR, "Cannot switch group; %s doesn't exist", gid_name);
529                         }
530                         return 0;
531                 }
532                 server_gid = gr->gr_gid;
533                 if (setgid(server_gid) < 0) {
534                         radlog(L_ERR, "Failed setting Group to %s: %s",
535                                gid_name, strerror(errno));
536                         return 0;
537                 }
538         } else {
539                 server_gid = getgid();
540         }
541 #endif
542
543 #ifdef HAVE_PWD_H
544         /*  Set UID.  */
545         if (uid_name != NULL) {
546                 struct passwd *pw;
547
548                 pw = getpwnam(uid_name);
549                 if (pw == NULL) {
550                         if (errno == ENOMEM) {
551                                 radlog(L_ERR, "Cannot switch to User %s: out of memory", uid_name);
552                         } else {
553                                 radlog(L_ERR, "Cannot switch user; %s doesn't exist", uid_name);
554                         }
555                         return 0;
556                 }
557                 server_uid = pw->pw_uid;
558 #ifdef HAVE_INITGROUPS
559                 if (initgroups(uid_name, server_gid) < 0) {
560                         if (errno != EPERM) {
561                                 radlog(L_ERR, "Failed setting supplementary groups for User %s: %s", uid_name, strerror(errno));
562                                 return 0;
563                         }
564                 }
565 #endif
566                 if (setuid(server_uid) < 0) {
567                         radlog(L_ERR, "Failed setting User to %s: %s", uid_name, strerror(errno));
568                         return 0;
569                 }
570
571                 /*
572                  *      Now core dumps are disabled on most secure systems.
573                  */
574                 did_setuid = TRUE;
575         }
576 #endif
577
578 #ifdef HAVE_SYS_RESOURCE_H
579         /*  Get the current maximum for core files.  */
580         if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
581                 radlog(L_ERR, "Failed to get current core limit:  %s", strerror(errno));
582                 return 0;
583         }
584 #endif
585
586         /*
587          *      Core dumps are allowed if we're in debug mode, OR
588          *      we've allowed them, OR we did a setuid (which turns
589          *      core dumps off).
590          *
591          *      Otherwise, disable core dumps for security.
592          *      
593          */
594         if (!(debug_flag || allow_core_dumps || did_setuid)) {
595 #ifdef HAVE_SYS_RESOURCE_H
596                 struct rlimit no_core;
597
598                 no_core.rlim_cur = 0;
599                 no_core.rlim_max = 0;
600
601                 if (setrlimit(RLIMIT_CORE, &no_core) < 0) {
602                         radlog(L_ERR, "Failed disabling core dumps: %s",
603                                strerror(errno));
604                         return 0;
605                 }
606 #endif
607
608                 /*
609                  *      Otherwise, re-enable core dumps if we're
610                  *      running as a daemon, AND core dumps are
611                  *      allowed, AND we changed UID's.
612                  */
613         } else if ((debug_flag == 0) && allow_core_dumps && did_setuid) {
614                 /*
615                  *      Set the dumpable flag.
616                  */
617 #ifdef HAVE_SYS_PRCTL_H
618 #ifdef PR_SET_DUMPABLE
619                 if (prctl(PR_SET_DUMPABLE, 1) < 0) {
620                         radlog(L_ERR,"Cannot enable core dumps: prctl(PR_SET_DUMPABLE) failed: '%s'",
621                                strerror(errno));
622                 }
623 #endif
624 #endif
625
626                 /*
627                  *      Reset the core dump limits again, just to
628                  *      double check that they haven't changed.
629                  */
630 #ifdef HAVE_SYS_RESOURCE_H
631                 if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
632                         radlog(L_ERR, "Cannot update core dump limit: %s",
633                                         strerror(errno));
634                         return 0;
635                 }
636 #endif
637
638                 radlog(L_INFO, "Core dumps are enabled.");
639         }
640         /*
641          *      Else we're debugging (so core dumps are enabled)
642          *      OR we're not debugging, AND "allow_core_dumps == FALSE",
643          *      OR we're not debugging, AND core dumps are allowed,
644          *         BUT we didn't call setuid, so we haven't changed the
645          *         core dump capabilities inherited from the parent shell.
646          */
647
648 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
649         /*
650          *      We've probably written to the log file already as
651          *      root.root, so if we have switched users, we've got to
652          *      update the ownership of the file.
653          */
654         if ((debug_flag == 0) &&
655             (mainconfig.radlog_dest == RADLOG_FILES) &&
656             (mainconfig.log_file != NULL)) {
657                 chown(mainconfig.log_file, server_uid, server_gid);
658         }
659 #endif
660         return 1;
661 }
662
663
664 static const LRAD_NAME_NUMBER str2dest[] = {
665         { "null", RADLOG_NULL },
666         { "files", RADLOG_FILES },
667         { "syslog", RADLOG_SYSLOG },
668         { "stdout", RADLOG_STDOUT },
669         { "stderr", RADLOG_STDERR },
670         { NULL, RADLOG_NUM_DEST }
671 };
672
673
674 /*
675  *      Read config files.
676  *
677  *      This function can ONLY be called from the main server process.
678  */
679 int read_mainconfig(int reload)
680 {
681         static int old_debug_level = -1;
682         char buffer[1024];
683         CONF_SECTION *cs, *templates;
684         struct stat statbuf;
685
686         if (stat(radius_dir, &statbuf) < 0) {
687                 radlog(L_ERR, "Errors reading %s: %s",
688                        radius_dir, strerror(errno));
689                 return -1;
690         }
691
692 #ifdef S_IWOTH
693         if ((statbuf.st_mode & S_IWOTH) != 0) {
694                 radlog(L_ERR, "Configuration directory %s is globally writable.  Refusing to start due to insecure configuration.",
695                        radius_dir);
696           return -1;
697         }
698 #endif
699
700 #ifdef S_IROTH
701         if (0 && (statbuf.st_mode & S_IROTH) != 0) {
702                 radlog(L_ERR, "Configuration directory %s is globally readable.  Refusing to start due to insecure configuration.",
703                        radius_dir);
704                 return -1;
705         }
706 #endif
707
708         if (!reload) {
709                 radlog(L_INFO, "Starting - reading configuration files ...");
710         } else {
711                 radlog(L_INFO, "Reloading - reading configuration files...");
712         }
713
714         /* Read the configuration file */
715         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
716                  radius_dir, mainconfig.radiusd_conf);
717         if ((cs = cf_file_read(buffer)) == NULL) {
718                 radlog(L_ERR, "Errors reading %s", buffer);
719                 return -1;
720         }
721
722         /*
723          *      Add templates to each kind of subsection.
724          */
725         templates = cf_section_sub_find(cs, "templates");
726         if (templates) {
727                 CONF_SECTION *ts, *mycs;
728
729                 /*
730                  *      Loop over the templates, adding them to the
731                  *      sections in the main configuration file.
732                  */
733                 for (ts = cf_subsection_find_next(templates, NULL, NULL);
734                      ts != NULL;
735                      ts = cf_subsection_find_next(templates, ts, NULL)) {
736                         const char *name1 = cf_section_name1(ts);
737
738                         /*
739                          *      Loop over sections in the main config
740                          *      file, adding templats.
741                          */
742                         for (mycs = cf_subsection_find_next(cs, NULL, name1);
743                              mycs != NULL;
744                              mycs = cf_subsection_find_next(cs, mycs, name1)) {
745                                 const char *value;
746
747                                 value = cf_section_value_find(mycs, "template");
748                                 if (value) {
749                                         CONF_SECTION *tts;
750
751                                         tts = cf_section_sub_find_name2(templates,
752                                                                         name1,
753                                                                         value);
754                                         if (!tts) {
755                                                 radlog(L_ERR, "%s[%d]: Section refers to non-existent template \"%s\"",
756                                                        cf_section_filename(mycs), cf_section_lineno(mycs), value);
757                                                 return -1;
758                                         }
759                                         cf_section_template(mycs, tts);
760                                 } else {
761                                         cf_section_template(mycs, ts);
762                                 }
763                         }
764                 }
765         }
766
767         /*
768          *      Debug flag 1 MAY go to files.
769          *      Debug flag 2 ALWAYS goes to stdout
770          *
771          *      Parse the log_destination before printing anything else.
772          *      All messages before this MUST be errors, which log.c
773          *      will print to stderr, since log_file is NULL, too.
774          */
775         if (debug_flag < 2) {
776                 int rcode;
777                 char *radlog_dest = NULL;
778
779                 rcode = cf_item_parse(cs, "log_destination",
780                                       PW_TYPE_STRING_PTR, &radlog_dest,
781                                       "files");
782                 if (rcode < 0) return -1;
783
784                 mainconfig.radlog_dest = lrad_str2int(str2dest, radlog_dest, RADLOG_NUM_DEST);
785                 if (mainconfig.radlog_dest == RADLOG_NUM_DEST) {
786                         fprintf(stderr, "radiusd: Error: Unknown log_destination %s\n",
787                                 radlog_dest);
788                         free(radlog_dest);
789                         cf_section_free(&cs);
790                         return -1;
791                 }
792
793                 if (mainconfig.radlog_dest == RADLOG_SYSLOG) {
794                         static const CONF_PARSER syslog_config[] = {
795                                 { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
796                                 { NULL, -1, 0, NULL, NULL }
797                         };
798                         cf_section_parse(cs, NULL, syslog_config);
799
800                         /*
801                          *      Make sure syslog_facility isn't NULL before using it
802                          */
803                         if (!syslog_facility) {
804                                 fprintf(stderr, "radiusd: Error: Unknown syslog chosen but no facility spedified\n");
805                                 free(radlog_dest);
806                                 cf_section_free(&cs);
807                                 return -1;
808                         }
809                         mainconfig.syslog_facility = lrad_str2int(str2fac, syslog_facility, -1);
810                         if (mainconfig.syslog_facility < 0) {
811                                 fprintf(stderr, "radiusd: Error: Unknown syslog_facility %s\n",
812                                         syslog_facility);
813                                 free(radlog_dest);
814                                 free(syslog_facility);
815                                 cf_section_free(&cs);
816                                 return -1;
817                         }
818                 }
819
820                 if (mainconfig.radlog_dest == RADLOG_FILES) {
821                         static const CONF_PARSER file_config[] = {
822                                 { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
823                                 { NULL, -1, 0, NULL, NULL }
824                         };
825
826                         cf_section_parse(cs, NULL, file_config);
827                 }
828
829                 free(radlog_dest);
830         } else {
831                 mainconfig.radlog_dest = RADLOG_STDOUT;
832                 mainconfig.radlog_fd = STDOUT_FILENO;
833         }
834
835         /* Initialize the dictionary */
836         DEBUG2("including dictionary file %s/%s", radius_dir, RADIUS_DICTIONARY);
837         if (dict_init(radius_dir, RADIUS_DICTIONARY) != 0) {
838                 radlog(L_ERR, "Errors reading dictionary: %s",
839                                 librad_errstr);
840                 return -1;
841         }
842
843         /*
844          *      This allows us to figure out where, relative to
845          *      radiusd.conf, the other configuration files exist.
846          */
847         cf_section_parse(cs, NULL, server_config);
848
849 #if 0
850         /*
851          *      Merge the old with the new.
852          */
853         if (reload) {
854                 CONF_SECTION *newcs;
855
856                 newcs = cf_section_sub_find(cs, "modules");
857                 oldcs = cf_section_sub_find(mainconfig.config, "modules");
858                 if (newcs && oldcs) {
859                         if (!cf_section_migrate(newcs, oldcs)) {
860                                 radlog(L_ERR, "Fatal error migrating configuration data");
861                                 return -1;
862                         }
863                 }
864         }
865 #endif
866
867         /*
868          *      Free the old configuration items, and replace them
869          *      with the new ones.
870          *
871          *      Note that where possible, we do atomic switch-overs,
872          *      to ensure that the pointers are always valid.
873          */
874         cf_section_free(&mainconfig.config);
875         mainconfig.config = cs;
876
877         clients_parse_section(cs);
878
879         DEBUG2("radiusd: #### Loading Realms and Home Servers ####");
880
881         if (!realms_init(cs)) {
882                 return -1;
883         }
884
885         /*
886          *  Register the %{config:section.subsection} xlat function.
887          */
888         xlat_register("config", xlat_config, NULL);
889         xlat_register("client", xlat_client, NULL);
890
891         /*
892          *      Reload: change debug flag if it's changed in the
893          *      configuration file.
894          */
895         if (reload) {
896                 if (mainconfig.debug_level != old_debug_level) {
897                         debug_flag = mainconfig.debug_level;
898                 }
899
900         } else if (debug_flag == 0) {
901
902                 /*
903                  *      Starting the server, WITHOUT "-x" on the
904                  *      command-line: use whatever's in the config
905                  *      file.
906                  */
907                 debug_flag = mainconfig.debug_level;
908         }
909         librad_debug = debug_flag;
910         old_debug_level = mainconfig.debug_level;
911
912         /*
913          *  Go update our behaviour, based on the configuration
914          *  changes.
915          */
916
917         /*
918          *      The first time around, ensure that we can write to the
919          *      log directory.
920          */
921         if (!reload) {
922                 /*
923                  *      We need root to do mkdir() and chown(), so we
924                  *      do this before giving up root.
925                  */
926                 radlogdir_iswritable(uid_name);
927         }
928
929         /*
930          *      We should really switch users earlier in the process.
931          */
932         if (!switch_users()) exit(1);
933
934         /*
935          *      Sanity check the configuration for internal
936          *      consistency.
937          */
938         if (mainconfig.reject_delay > mainconfig.cleanup_delay) {
939                 mainconfig.reject_delay = mainconfig.cleanup_delay;
940         }
941         if (mainconfig.reject_delay < 0) mainconfig.reject_delay = 0;
942
943         /*  Reload the modules.  */
944         if (setup_modules(reload, mainconfig.config) < 0) {
945                 radlog(L_ERR, "Errors initializing modules");
946                 return -1;
947         }
948
949         return 0;
950 }
951
952 /*
953  *      Free the configuration.  Called only when the server is exiting.
954  */
955 int free_mainconfig(void)
956 {
957         /*
958          *      Clean up the configuration data
959          *      structures.
960          */
961         cf_section_free(&mainconfig.config);
962         free(mainconfig.radiusd_conf);
963         realms_free();
964         listen_free(&mainconfig.listen);
965         xlat_free();
966         dict_free();
967         lt_dlexit();
968
969         return 0;
970 }