document rlm_otp fd leak fix
[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  The FreeRADIUS server project
21  * Copyright 2002  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/autoconf.h>
25
26 #include <stdlib.h>
27 #include <string.h>
28
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
31 #endif
32
33 #ifdef HAVE_ARPA_INET_H
34 #include <arpa/inet.h>
35 #endif
36
37 #include <freeradius-devel/radiusd.h>
38 #include <freeradius-devel/rad_assert.h>
39 #include <freeradius-devel/modules.h>
40 #include <freeradius-devel/request_list.h>
41
42 #include <sys/resource.h>
43 #include <netdb.h>
44 #include <sys/stat.h>
45 #include <grp.h>
46 #include <pwd.h>
47
48 #ifdef HAVE_SYS_PRTCL_H
49 #include <sys/prctl.h>
50 #endif
51
52 #ifdef HAVE_SYSLOG_H
53 #       include <syslog.h>
54 #endif
55
56 struct main_config_t mainconfig;
57
58 /*
59  *      Temporary local variables for parsing the configuration
60  *      file.
61  */
62 static uid_t server_uid;
63 static gid_t server_gid;
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  *  Map the proxy server configuration parameters to variables.
134  */
135 static const CONF_PARSER proxy_config[] = {
136         { "retry_delay",  PW_TYPE_INTEGER, 0, &mainconfig.proxy_retry_delay, Stringify(RETRY_DELAY) },
137         { "retry_count",  PW_TYPE_INTEGER, 0, &mainconfig.proxy_retry_count, Stringify(RETRY_COUNT) },
138         { "default_fallback", PW_TYPE_BOOLEAN, 0, &mainconfig.proxy_fallback, "no" },
139         { "dead_time",    PW_TYPE_INTEGER, 0, &mainconfig.proxy_dead_time, Stringify(DEAD_TIME) },
140         { "wake_all_if_all_dead", PW_TYPE_BOOLEAN, 0, &mainconfig.wake_all_if_all_dead, "no" },
141         { "proxy_fail_type", PW_TYPE_STRING_PTR, 0, &mainconfig.proxy_fail_type, NULL},
142         { NULL, -1, 0, NULL, NULL }
143 };
144
145
146 /*
147  *  Security configuration for the server.
148  */
149 static const CONF_PARSER security_config[] = {
150         { "max_attributes",  PW_TYPE_INTEGER, 0, &librad_max_attributes, Stringify(0) },
151         { "reject_delay",  PW_TYPE_INTEGER, 0, &mainconfig.reject_delay, Stringify(0) },
152         { "status_server", PW_TYPE_BOOLEAN, 0, &mainconfig.status_server, "no"},
153         { NULL, -1, 0, NULL, NULL }
154 };
155
156
157 /*
158  *  syslog configuration for the server.
159  */
160 static const CONF_PARSER log_config[] = {
161         { "syslog_facility",  PW_TYPE_STRING_PTR, 0, &syslog_facility, Stringify(0) },
162         { NULL, -1, 0, NULL, NULL }
163 };
164
165
166 /*
167  *  A mapping of configuration file names to internal variables
168  */
169 static const CONF_PARSER server_config[] = {
170         /*
171          *      FIXME: 'prefix' is the ONLY one which should be
172          *      configured at compile time.  Hard-coding it here is
173          *      bad.  It will be cleaned up once we clean up the
174          *      hard-coded defines for the locations of the various
175          *      files.
176          */
177         { "prefix",             PW_TYPE_STRING_PTR, 0, &prefix,            "/usr/local"},
178         { "localstatedir",      PW_TYPE_STRING_PTR, 0, &localstatedir,     "${prefix}/var"},
179         { "logdir",             PW_TYPE_STRING_PTR, 0, &radlog_dir,        "${localstatedir}/log"},
180         { "libdir",             PW_TYPE_STRING_PTR, 0, &radlib_dir,        "${prefix}/lib"},
181         { "radacctdir",         PW_TYPE_STRING_PTR, 0, &radacct_dir,       "${logdir}/radacct" },
182         { "hostname_lookups",   PW_TYPE_BOOLEAN,    0, &librad_dodns,      "no" },
183 #ifdef WITH_SNMP
184         { "snmp",               PW_TYPE_BOOLEAN,    0, &mainconfig.do_snmp,      "no" },
185 #endif
186         { "max_request_time", PW_TYPE_INTEGER, 0, &mainconfig.max_request_time, Stringify(MAX_REQUEST_TIME) },
187         { "cleanup_delay", PW_TYPE_INTEGER, 0, &mainconfig.cleanup_delay, Stringify(CLEANUP_DELAY) },
188         { "max_requests", PW_TYPE_INTEGER, 0, &mainconfig.max_requests, Stringify(MAX_REQUESTS) },
189         { "delete_blocked_requests", PW_TYPE_INTEGER, 0, &mainconfig.kill_unresponsive_children, Stringify(FALSE) },
190         { "allow_core_dumps", PW_TYPE_BOOLEAN, 0, &mainconfig.allow_core_dumps, "no" },
191         { "log_stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names,"no" },
192
193         { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
194         { "log_auth", PW_TYPE_BOOLEAN, -1, &mainconfig.log_auth, "no" },
195         { "log_auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, "no" },
196         { "log_auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, "no" },
197         { "pidfile", PW_TYPE_STRING_PTR, 0, &mainconfig.pid_file, "${run_dir}/radiusd.pid"},
198         { "user", PW_TYPE_STRING_PTR, 0, &mainconfig.uid_name, NULL},
199         { "group", PW_TYPE_STRING_PTR, 0, &mainconfig.gid_name, NULL},
200         { "checkrad", PW_TYPE_STRING_PTR, 0, &mainconfig.checkrad, "${sbindir}/checkrad" },
201
202         { "debug_level", PW_TYPE_INTEGER, 0, &mainconfig.debug_level, "0"},
203
204         { "proxy_requests", PW_TYPE_BOOLEAN, 0, &mainconfig.proxy_requests, "yes" },
205         { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
206         { "proxy", PW_TYPE_SUBSECTION, 0, NULL, (const void *) proxy_config },
207         { "security", PW_TYPE_SUBSECTION, 0, NULL, (const void *) security_config },
208         { NULL, -1, 0, NULL, NULL }
209 };
210
211
212 #define MAX_ARGV (256)
213 /*
214  *      Xlat for %{config:section.subsection.attribute}
215  */
216 static int xlat_config(void *instance, REQUEST *request,
217                        char *fmt, char *out,
218                        size_t outlen,
219                        RADIUS_ESCAPE_STRING func)
220 {
221         CONF_SECTION *cs;
222         CONF_PAIR *cp;
223         int i, argc, left;
224         const char *from, *value;
225         char *to;
226         char myfmt[1024];
227         char argv_buf[1024];
228         char *argv[MAX_ARGV];
229
230         request = request;      /* -Wunused */
231         instance = instance;    /* -Wunused */
232
233         cp = NULL;
234         cs = NULL;
235
236         /*
237          *      Split the string into argv's BEFORE doing radius_xlat...
238          *      Copied from exec.c
239          */
240         from = fmt;
241         to = myfmt; 
242         argc = 0;
243         while (*from) {
244                 int flag, length;
245                 
246                 flag = 0;
247                 argv[argc] = to;
248                 argc++;
249                 
250                 if (argc >= (MAX_ARGV - 1)) break;
251                 
252                 /*
253                  *      Copy the argv over to our buffer.
254                  */
255                 while (*from) {
256                         if (to >= myfmt + sizeof(myfmt) - 1) {
257                                 return 0; /* no error msg */
258                         }
259
260                         switch (*from) {
261                         case '%':
262                                 if (from[1] == '{') {
263                                         *(to++) = *(from++);
264                                         
265                                         length = rad_copy_variable(to, from);
266                                         if (length < 0) {
267                                                 return -1;
268                                         }
269                                         from += length;
270                                         to += length;
271                                 } else { /* FIXME: catch %%{ ? */
272                                         *(to++) = *(from++);
273                                 }
274                                 break;
275
276                         case '[':
277                                 if (flag != 0) {
278                                         radlog(L_ERR, "config: Unexpected nested '[' in \"%s\"", fmt);
279                                         return 0;
280                                 }
281                                 flag++;
282                                 *(to++) = *(from++);
283                                 break;
284
285                         case ']':
286                                 if (flag == 0) {
287                                         radlog(L_ERR, "config: Unbalanced ']' in \"%s\"", fmt);
288                                         return 0;
289                                 }
290                                 if (from[1] != '.') {
291                                         radlog(L_ERR, "config: Unexpected text after ']' in \"%s\"", fmt);
292                                         return 0;
293                                 }
294
295                                 flag--;
296                                 *(to++) = *(from++);
297                                 break;
298
299                         case '.':
300                                 if (flag == 0) break;
301                                 /* FALL-THROUGH */
302
303                         default:
304                                 *(to++) = *(from++);
305                                 break;
306                         }
307
308                         if ((*from == '.') && (flag == 0)) {
309                                 from++;
310                                 break;
311                         }
312                 } /* end of string, or found a period */
313
314                 if (flag != 0) {
315                         radlog(L_ERR, "config: Unbalanced '[' in \"%s\"", fmt);
316                         return 0;
317                 }
318
319                 *(to++) = '\0'; /* terminate the string. */
320         }
321
322         /*
323          *      Expand each string, as appropriate
324          */
325         to = argv_buf;
326         left = sizeof(argv_buf);
327         for (i = 0; i < argc; i++) {
328                 int sublen;
329
330                 /*
331                  *      Don't touch argv's which won't be translated.
332                  */
333                 if (strchr(argv[i], '%') == NULL) continue;
334
335                 sublen = radius_xlat(to, left - 1, argv[i], request, NULL);
336                 if (sublen <= 0) {
337                         /*
338                          *      Fail to be backwards compatible.
339                          *
340                          *      It's yucky, but it won't break anything,
341                          *      and it won't cause security problems.
342                          */
343                         sublen = 0;
344                 }
345                 
346                 argv[i] = to;
347                 to += sublen;
348                 *(to++) = '\0';
349                 left -= sublen;
350                 left--;
351
352                 if (left <= 0) {
353                         return 0;
354                 }
355         }
356         argv[argc] = NULL;
357
358         cs = cf_section_find(NULL); /* get top-level section */
359
360         /*
361          *      Root through section & subsection references.
362          *      The last entry of argv MUST be the CONF_PAIR.
363          */
364         for (i = 0; i < argc - 1; i++) {
365                 char *name2 = NULL;
366                 CONF_SECTION *subcs;
367
368                 /*
369                  *      FIXME: What about RADIUS attributes containing '['?
370                  */
371                 name2 = strchr(argv[i], '[');
372                 if (name2) {
373                         char *p = strchr(name2, ']');
374                         rad_assert(p != NULL);
375                         rad_assert(p[1] =='\0');
376                         *p = '\0';
377                         *name2 = '\0';
378                         name2++;
379                 }
380
381                 if (name2) {
382                         subcs = cf_section_sub_find_name2(cs, argv[i],
383                                                           name2);
384                         if (!subcs) {
385                           radlog(L_ERR, "config: section \"%s %s {}\" not found while dereferencing \"%s\"", argv[i], name2, fmt);
386                           return 0;
387                         }
388                 } else {
389                         subcs = cf_section_sub_find(cs, argv[i]);
390                         if (!subcs) {
391                           radlog(L_ERR, "config: section \"%s {}\" not found while dereferencing \"%s\"", argv[i], fmt);
392                           return 0;
393                         }
394                 }
395                 cs = subcs;
396         } /* until argc - 1 */
397
398         /*
399          *      This can now have embedded periods in it.
400          */
401         cp = cf_pair_find(cs, argv[argc - 1]);
402         if (!cp) {
403                 radlog(L_ERR, "config: item \"%s\" not found while dereferencing \"%s\"", argv[argc], fmt);
404                 return 0;
405         }
406
407         /*
408          *  Ensure that we only copy what's necessary.
409          *
410          *  If 'outlen' is too small, then the output is chopped to fit.
411          */
412         value = cf_pair_value(cp);
413         if (value) {
414                 if (outlen > strlen(value)) {
415                         outlen = strlen(value) + 1;
416                 }
417         }
418
419         return func(out, outlen, value);
420 }
421
422
423 /*
424  *      Recursively make directories.
425  */
426 static int r_mkdir(const char *part)
427 {
428         char *ptr, parentdir[500];
429         struct stat st;
430
431         if (stat(part, &st) == 0)
432                 return(0);
433
434         ptr = strrchr(part, '/');
435
436         if (ptr == part)
437                 return(0);
438
439         snprintf(parentdir, (ptr - part)+1, "%s", part);
440
441         if (r_mkdir(parentdir) != 0)
442                 return(1);
443
444         if (mkdir(part, 0770) != 0) {
445                 radlog(L_ERR, "mkdir(%s) error: %s\n", part, strerror(errno));
446                 return(1);
447         }
448
449         return(0);
450 }
451
452 /*
453  *      Checks if the log directory is writeable by a particular user.
454  */
455 static int radlogdir_iswritable(const char *effectiveuser)
456 {
457         struct passwd *pwent;
458
459         if (radlog_dir[0] != '/')
460                 return(0);
461
462         if (r_mkdir(radlog_dir) != 0)
463                 return(1);
464
465         /* FIXME: do we have this function? */
466         if (strstr(radlog_dir, "radius") == NULL)
467                 return(0);
468
469         /* we have a logdir that mentions 'radius', so it's probably
470          * safe to chown the immediate directory to be owned by the normal
471          * process owner. we gotta do it before we give up root.  -chad
472          */
473
474         if (!effectiveuser) {
475                 return 1;
476         }
477
478         pwent = getpwnam(effectiveuser);
479
480         if (pwent == NULL) /* uh oh! */
481                 return(1);
482
483         if (chown(radlog_dir, pwent->pw_uid, -1) != 0)
484                 return(1);
485
486         return(0);
487 }
488
489
490 /*
491  *  Switch UID and GID to what is specified in the config file
492  */
493 static int switch_users(void)
494 {
495         struct rlimit core_limits;
496
497         /*  Set GID.  */
498         if (mainconfig.gid_name != NULL) {
499                 struct group *gr;
500
501                 gr = getgrnam(mainconfig.gid_name);
502                 if (gr == NULL) {
503                         if (errno == ENOMEM) {
504                                 radlog(L_ERR|L_CONS, "Cannot switch to Group %s: out of memory", mainconfig.gid_name);
505                         } else {
506                                 radlog(L_ERR|L_CONS, "Cannot switch group; %s doesn't exist", mainconfig.gid_name);
507                         }
508                         exit(1);
509                 }
510                 server_gid = gr->gr_gid;
511                 if (setgid(server_gid) < 0) {
512                         radlog(L_ERR|L_CONS, "Failed setting Group to %s: %s",
513                                mainconfig.gid_name, strerror(errno));
514                         exit(1);
515                 }
516         } else {
517                 server_gid = getgid();
518         }
519
520         /*  Set UID.  */
521         if (mainconfig.uid_name != NULL) {
522                 struct passwd *pw;
523
524                 pw = getpwnam(mainconfig.uid_name);
525                 if (pw == NULL) {
526                         if (errno == ENOMEM) {
527                                 radlog(L_ERR|L_CONS, "Cannot switch to User %s: out of memory", mainconfig.uid_name);
528                         } else {
529                                 radlog(L_ERR|L_CONS, "Cannot switch user; %s doesn't exist", mainconfig.uid_name);
530                         }
531                         exit(1);
532                 }
533                 server_uid = pw->pw_uid;
534 #ifdef HAVE_INITGROUPS
535                 if (initgroups(mainconfig.uid_name, server_gid) < 0) {
536                         if (errno != EPERM) {
537                                 radlog(L_ERR|L_CONS, "Failed setting supplementary groups for User %s: %s", mainconfig.uid_name, strerror(errno));
538                                 exit(1);
539                         }
540                 }
541 #endif
542                 if (setuid(server_uid) < 0) {
543                         radlog(L_ERR|L_CONS, "Failed setting User to %s: %s", mainconfig.uid_name, strerror(errno));
544                         exit(1);
545                 }
546         }
547
548         /*  Get the current maximum for core files.  */
549         if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
550                 radlog(L_ERR|L_CONS, "Failed to get current core limit:  %s", strerror(errno));
551                 exit(1);
552         }
553
554         if (mainconfig.allow_core_dumps) {
555 #ifdef HAVE_SYS_PRTCL_H
556 #ifdef PR_SET_DUMPABLE
557                 if (prctl(PR_SET_DUMPABLE, 1) < 0) {
558                         radlog(L_ERR|L_CONS,"Cannot enable core dumps: prctl(PR_SET_DUMPABLE) failed: '%s'",
559                                strerror(errno));
560                 }
561 #endif
562 #endif
563
564                 if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
565                         radlog(L_ERR|L_CONS, "Cannot update core dump limit: %s",
566                                         strerror(errno));
567                         exit(1);
568
569                         /*
570                          *  If we're running as a daemon, and core
571                          *  dumps are enabled, log that information.
572                          */
573                 } else if ((core_limits.rlim_cur != 0) && !debug_flag)
574                         radlog(L_INFO|L_CONS, "Core dumps are enabled.");
575
576         } else if (!debug_flag) {
577                 /*
578                  *  Not debugging.  Set the core size to zero, to
579                  *  prevent security breaches.  i.e. People
580                  *  reading passwords from the 'core' file.
581                  */
582                 struct rlimit limits;
583
584                 limits.rlim_cur = 0;
585                 limits.rlim_max = core_limits.rlim_max;
586
587                 if (setrlimit(RLIMIT_CORE, &limits) < 0) {
588                         radlog(L_ERR|L_CONS, "Cannot disable core dumps: %s",
589                                         strerror(errno));
590                         exit(1);
591                 }
592         }
593
594         /*
595          *      We've probably written to the log file already as
596          *      root.root, so if we have switched users, we've got to
597          *      update the ownership of the file.
598          */
599         if ((debug_flag == 0) &&
600             (mainconfig.radlog_dest == RADLOG_FILES) &&
601             (mainconfig.log_file != NULL)) {
602                 chown(mainconfig.log_file, server_uid, server_gid);
603         }
604
605         return(0);
606 }
607
608
609 /*
610  * Create the linked list of realms from the new configuration type
611  * This way we don't have to change to much in the other source-files
612  */
613 static int generate_realms(const char *filename)
614 {
615         CONF_SECTION *cs;
616         REALM *my_realms = NULL;
617         REALM *c, **tail;
618         char *s, *t, *authhost, *accthost;
619         const char *name2;
620
621         tail = &my_realms;
622         for (cs = cf_subsection_find_next(mainconfig.config, NULL, "realm");
623              cs != NULL;
624              cs = cf_subsection_find_next(mainconfig.config, cs, "realm")) {
625                 name2 = cf_section_name2(cs);
626                 if (!name2) {
627                         radlog(L_CONS|L_ERR, "%s[%d]: Missing realm name",
628                                filename, cf_section_lineno(cs));
629                         return -1;
630                 }
631                 /*
632                  * We've found a realm, allocate space for it
633                  */
634                 c = rad_malloc(sizeof(REALM));
635                 memset(c, 0, sizeof(REALM));
636
637                 c->secret[0] = '\0';
638
639                 /*
640                  *      No authhost means LOCAL.
641                  */
642                 if ((authhost = cf_section_value_find(cs, "authhost")) == NULL) {
643                         c->ipaddr.af = AF_INET;
644                         c->ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
645                         c->auth_port = 0;
646                 } else {
647                         if ((s = strchr(authhost, ':')) != NULL) {
648                                 *s++ = 0;
649                                 c->auth_port = atoi(s);
650                         } else {
651                                 c->auth_port = PW_AUTH_UDP_PORT;
652                         }
653                         if (strcmp(authhost, "LOCAL") == 0) {
654                                 /*
655                                  *      Local realms don't have an IP address,
656                                  *      secret, or port.
657                                  */
658                                 c->ipaddr.af = AF_INET;
659                                 c->ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
660                                 c->auth_port = 0;
661                         } else {
662                                 if (ip_hton(authhost, AF_INET,
663                                             &c->ipaddr) < 0) {
664                                         radlog(L_ERR, "%s[%d]: Host %s not found",
665                                                filename, cf_section_lineno(cs),
666                                                authhost);
667                                         return -1;
668                                 }
669                         }
670
671                         /*
672                          * Double check length, just to be sure!
673                          */
674                         if (strlen(authhost) >= sizeof(c->server)) {
675                                 radlog(L_ERR, "%s[%d]: Server name of length %u is greater than allowed: %u",
676                                        filename, cf_section_lineno(cs),
677                                        strlen(authhost),
678                                        sizeof(c->server) - 1);
679                                 return -1;
680                         }
681                 }
682
683                 /*
684                  *      No accthost means LOCAL
685                  */
686                 if ((accthost = cf_section_value_find(cs, "accthost")) == NULL) {
687                         c->acct_ipaddr.af = AF_INET;
688                         c->acct_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
689                         c->acct_port = 0;
690                 } else {
691                         if ((s = strchr(accthost, ':')) != NULL) {
692                                 *s++ = 0;
693                                 c->acct_port = atoi(s);
694                         } else {
695                                 c->acct_port = PW_ACCT_UDP_PORT;
696                         }
697                         if (strcmp(accthost, "LOCAL") == 0) {
698                                 /*
699                                  *      Local realms don't have an IP address,
700                                  *      secret, or port.
701                                  */
702                                 c->acct_ipaddr.af = AF_INET;
703                                 c->acct_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
704                                 c->acct_port = 0;
705                         } else {
706                                 if (ip_hton(accthost, AF_INET,
707                                             &c->acct_ipaddr) < 0) {
708                                         radlog(L_ERR, "%s[%d]: Host %s not found",
709                                                filename, cf_section_lineno(cs),
710                                                accthost);
711                                         return -1;
712                                 }
713                         }
714
715                         if (strlen(accthost) >= sizeof(c->acct_server)) {
716                                 radlog(L_ERR, "%s[%d]: Server name of length %u is greater than allowed: %u",
717                                        filename, cf_section_lineno(cs),
718                                        strlen(accthost),
719                                        sizeof(c->acct_server) - 1);
720                                 return -1;
721                         }
722                 }
723
724                 if (strlen(name2) >= sizeof(c->realm)) {
725                         radlog(L_ERR, "%s[%d]: Realm name of length %u is greater than allowed %u",
726                                filename, cf_section_lineno(cs),
727                                strlen(name2),
728                                sizeof(c->server) - 1);
729                         return -1;
730                 }
731
732                 strcpy(c->realm, name2);
733                 if (authhost) strcpy(c->server, authhost);
734                 if (accthost) strcpy(c->acct_server, accthost);
735
736                 /*
737                  *      If one or the other of authentication/accounting
738                  *      servers is set to LOCALHOST, then don't require
739                  *      a shared secret.
740                  */
741                 rad_assert(c->ipaddr.af == AF_INET);
742                 rad_assert(c->acct_ipaddr.af == AF_INET);
743                 if ((c->ipaddr.ipaddr.ip4addr.s_addr != htonl(INADDR_NONE)) ||
744                     (c->acct_ipaddr.ipaddr.ip4addr.s_addr != htonl(INADDR_NONE))) {
745                         if ((s = cf_section_value_find(cs, "secret")) == NULL ) {
746                                 radlog(L_ERR, "%s[%d]: No shared secret supplied for realm: %s",
747                                        filename, cf_section_lineno(cs), name2);
748                                 return -1;
749                         }
750
751                         if (strlen(s) >= sizeof(c->secret)) {
752                                 radlog(L_ERR, "%s[%d]: Secret of length %u is greater than the allowed maximum of %u.",
753                                        filename, cf_section_lineno(cs),
754                                        strlen(s), sizeof(c->secret) - 1);
755                                 return -1;
756                         }
757                         strNcpy((char *)c->secret, s, sizeof(c->secret));
758                 }
759
760                 c->striprealm = 1;
761
762                 if ((cf_section_value_find(cs, "nostrip")) != NULL)
763                         c->striprealm = 0;
764                 if ((cf_section_value_find(cs, "noacct")) != NULL)
765                         c->acct_port = 0;
766                 if ((cf_section_value_find(cs, "trusted")) != NULL)
767                         c->trusted = 1;
768                 if ((cf_section_value_find(cs, "notrealm")) != NULL)
769                         c->notrealm = 1;
770                 if ((cf_section_value_find(cs, "notsuffix")) != NULL)
771                         c->notrealm = 1;
772                 if ((t = cf_section_value_find(cs,"ldflag")) != NULL) {
773                         static const LRAD_NAME_NUMBER ldflags[] = {
774                                 { "fail_over",   0 },
775                                 { "round_robin", 1 },
776                                 { NULL, 0 }
777                         };
778
779                         c->ldflag = lrad_str2int(ldflags, t, -1);
780                         if (c->ldflag == -1) {
781                                 radlog(L_ERR, "%s[%d]: Unknown value \"%s\" for ldflag",
782                                        filename, cf_section_lineno(cs),
783                                        t);
784                                 return -1;
785                         }
786
787                 } else {
788                         c->ldflag = 0; /* non, make it fail-over */
789                 }
790                 c->active = TRUE;
791                 c->acct_active = TRUE;
792
793                 c->next = NULL;
794                 *tail = c;
795                 tail = &c->next;
796         }
797
798         /*
799          *      And make these realms preferred over the ones
800          *      in the 'realms' file.
801          */
802         *tail = mainconfig.realms;
803         mainconfig.realms = my_realms;
804
805         /*
806          *  Ensure that all of the flags agree for the realms.
807          *
808          *      Yeah, it's O(N^2), but it's only once, and the
809          *      maximum number of realms is small.
810          */
811         for(c = mainconfig.realms; c != NULL; c = c->next) {
812                 REALM *this;
813
814                 /*
815                  *      Check that we cannot load balance to LOCAL
816                  *      realms, as that doesn't make any sense.
817                  */
818                 rad_assert(c->ipaddr.af == AF_INET);
819                 rad_assert(c->acct_ipaddr.af == AF_INET);
820                 if ((c->ldflag == 1) &&
821                     ((c->ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_NONE)) ||
822                      (c->acct_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_NONE)))) {
823                         radlog(L_ERR | L_CONS, "ERROR: Realm %s cannot be load balanced to LOCAL",
824                                c->realm);
825                         exit(1);
826                 }
827
828                 /*
829                  *      Compare this realm to all others, to ensure
830                  *      that the configuration is consistent.
831                  */
832                 for (this = c->next; this != NULL; this = this->next) {
833                         if (strcasecmp(c->realm, this->realm) != 0) {
834                                 continue;
835                         }
836
837                         /*
838                          *      Same realm: Different load balancing
839                          *      flag: die.
840                          */
841                         if (c->ldflag != this->ldflag) {
842                                 radlog(L_ERR | L_CONS, "ERROR: Inconsistent value in realm %s for load balancing 'ldflag' attribute",
843                                        c->realm);
844                                 exit(1);
845                         }
846                 }
847         }
848
849         return 0;
850 }
851
852
853 static const LRAD_NAME_NUMBER str2dest[] = {
854         { "null", RADLOG_NULL },
855         { "files", RADLOG_FILES },
856         { "syslog", RADLOG_SYSLOG },
857         { "stdout", RADLOG_STDOUT },
858         { "stderr", RADLOG_STDERR },
859         { NULL, RADLOG_NUM_DEST }
860 };
861
862
863 /*
864  *      Read config files.
865  *
866  *      This function can ONLY be called from the main server process.
867  */
868 int read_mainconfig(int reload)
869 {
870         static int old_debug_level = -1;
871         char buffer[1024];
872         CONF_SECTION *cs, *oldcs;
873         rad_listen_t *listener;
874
875         /* Read the configuration file */
876         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
877                  radius_dir, mainconfig.radiusd_conf);
878         if ((cs = cf_file_read(buffer)) == NULL) {
879                 radlog(L_ERR|L_CONS, "Errors reading %s", buffer);
880                 return -1;
881         }
882
883         /*
884          *      Debug flag 1 MAY go to files.
885          *      Debug flag 2 ALWAYS goes to stdout
886          *
887          *      Parse the log_destination before printing anything else.
888          *      All messages before this MUST be errors, which log.c
889          *      will print to stderr, since log_file is NULL, too.
890          */
891         if (debug_flag < 2) {
892                 int rcode;
893                 char *radlog_dest = NULL;
894
895                 rcode = cf_item_parse(cs, "log_destination",
896                                       PW_TYPE_STRING_PTR, &radlog_dest,
897                                       "files");
898                 if (rcode < 0) return -1;
899         
900                 mainconfig.radlog_dest = lrad_str2int(str2dest, radlog_dest, RADLOG_NUM_DEST);
901                 if (mainconfig.radlog_dest == RADLOG_NUM_DEST) {
902                         fprintf(stderr, "radiusd: Error: Unknown log_destination %s\n",
903                                 radlog_dest);
904                         free(radlog_dest);
905                         cf_section_free(&cs);
906                         return -1;
907                 }
908                 
909                 if (mainconfig.radlog_dest == RADLOG_SYSLOG) {
910                         static const CONF_PARSER syslog_config[] = {
911                                 { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
912                                 { NULL, -1, 0, NULL, NULL }
913                         };
914                         cf_section_parse(cs, NULL, syslog_config);
915
916                         /*
917                          *      Make sure syslog_facility isn't NULL before using it
918                          */
919                         if (!syslog_facility) {
920                                 fprintf(stderr, "radiusd: Error: Unknown syslog chosen but no facility spedified\n");
921                                 free(radlog_dest);
922                                 cf_section_free(&cs);
923                                 return -1;
924                         }
925                         mainconfig.syslog_facility = lrad_str2int(str2fac, syslog_facility, -1);
926                         if (mainconfig.syslog_facility < 0) {
927                                 fprintf(stderr, "radiusd: Error: Unknown syslog_facility %s\n",
928                                         syslog_facility);
929                                 free(radlog_dest);
930                                 free(syslog_facility);
931                                 cf_section_free(&cs);
932                                 return -1;
933                         }
934                 }
935
936                 if (mainconfig.radlog_dest == RADLOG_FILES) {
937                         static const CONF_PARSER file_config[] = {
938                                 { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
939                                 { NULL, -1, 0, NULL, NULL }
940                         };
941
942                         cf_section_parse(cs, NULL, file_config);
943                 }
944
945                 free(radlog_dest);
946         } else {
947                 mainconfig.radlog_dest = RADLOG_STDOUT;
948                 mainconfig.radlog_fd = STDOUT_FILENO;
949         }
950
951         radlog(L_INFO, "%s", radiusd_version);
952         if (!reload) {
953                 radlog(L_INFO, "Starting - reading configuration files ...");
954         } else {
955                 radlog(L_INFO, "Reloading - reading configuration files...");
956         }
957
958         /* Initialize the dictionary */
959         DEBUG2("read_config_files:  reading dictionary");
960         if (dict_init(radius_dir, RADIUS_DICTIONARY) != 0) {
961                 radlog(L_ERR|L_CONS, "Errors reading dictionary: %s",
962                                 librad_errstr);
963                 return -1;
964         }
965
966         /*
967          *      This allows us to figure out where, relative to
968          *      radiusd.conf, the other configuration files exist.
969          */
970         cf_section_parse(cs, NULL, server_config);
971
972 #if 0
973         /*
974          *      Merge the old with the new.
975          */
976         if (reload) {
977                 CONF_SECTION *newcs;
978
979                 newcs = cf_section_sub_find(cs, "modules");
980                 oldcs = cf_section_sub_find(mainconfig.config, "modules");
981                 if (newcs && oldcs) {
982                         if (!cf_section_migrate(newcs, oldcs)) {
983                                 radlog(L_ERR|L_CONS, "Fatal error migrating configuration data");
984                                 return -1;
985                         }
986                 }
987         }
988 #endif
989
990         /*
991          *      Free the old configuration items, and replace them
992          *      with the new ones.
993          *
994          *      Note that where possible, we do atomic switch-overs,
995          *      to ensure that the pointers are always valid.
996          */
997         oldcs = mainconfig.config;
998         mainconfig.config = cs;
999         cf_section_free(&oldcs);
1000
1001         /*
1002          *      Old-style realms file.
1003          */
1004         snprintf(buffer, sizeof(buffer), "%.200s/%.50s", radius_dir, RADIUS_REALMS);
1005         DEBUG2("read_config_files:  reading realms");
1006         if (read_realms_file(buffer) < 0) {
1007                 radlog(L_ERR|L_CONS, "Errors reading realms");
1008                 return -1;
1009         }
1010
1011         /*
1012          *      If there isn't any realms it isn't fatal..
1013          */
1014         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
1015                  radius_dir, mainconfig.radiusd_conf);
1016         if (generate_realms(buffer) < 0) {
1017                 return -1;
1018         }
1019
1020         /*
1021          *  Register the %{config:section.subsection} xlat function.
1022          */
1023         xlat_register("config", xlat_config, NULL);
1024
1025         /*
1026          *      Set the libraries debugging flag to whatever the main
1027          *      flag is.  Note that on a SIGHUP, to turn the debugging
1028          *      off, we do other magic.
1029          *
1030          *      Increase the debug level, if the configuration file
1031          *      says to, OR, if we're decreasing the debug from what it
1032          *      was before, allow that, too.
1033          */
1034         if ((mainconfig.debug_level > debug_flag) ||
1035             (mainconfig.debug_level <= old_debug_level)) {
1036                 debug_flag = mainconfig.debug_level;
1037         }
1038         librad_debug = debug_flag;
1039         old_debug_level = mainconfig.debug_level;
1040
1041         /*
1042          *  Go update our behaviour, based on the configuration
1043          *  changes.
1044          */
1045
1046         /*
1047          *      The first time around, ensure that we can write to the
1048          *      log directory.
1049          */
1050         if (!reload) {
1051                 /*
1052                  *      We need root to do mkdir() and chown(), so we
1053                  *      do this before giving up root.
1054                  */
1055                 radlogdir_iswritable(mainconfig.uid_name);
1056         }
1057
1058         /*
1059          *      We should really switch users earlier in the process.
1060          */
1061         switch_users();
1062
1063         /*
1064          *      Sanity check the configuration for internal
1065          *      consistency.
1066          */
1067         if (mainconfig.reject_delay > mainconfig.cleanup_delay) {
1068                 mainconfig.reject_delay = mainconfig.cleanup_delay;
1069         }
1070
1071         /*
1072          *      Initialize the old "bind_address" and "port", first.
1073          */
1074         listener = NULL;
1075
1076         /*
1077          *      Read the list of listeners.
1078          */
1079         snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
1080                  radius_dir, mainconfig.radiusd_conf);
1081         if (listen_init(buffer, &listener) < 0) {
1082                 exit(1);
1083         }
1084
1085         if (!listener) {
1086                 radlog(L_ERR|L_CONS, "Server is not configured to listen on any ports.  Exiting.");
1087                 exit(1);
1088         }
1089
1090         listen_free(&mainconfig.listen);
1091         mainconfig.listen = listener;
1092
1093         /*
1094          *      Walk through the listeners.  If we're listening on acct
1095          *      or auth, read in the clients files, else ignore them.
1096          */
1097         for (listener = mainconfig.listen;
1098              listener != NULL;
1099              listener = listener->next) {
1100                 if ((listener->type == RAD_LISTEN_AUTH) ||
1101                     (listener->type == RAD_LISTEN_ACCT)) {
1102                         break;
1103                 }
1104         }
1105
1106         if (listener != NULL) {
1107                 RADCLIENT_LIST *clients, *old_clients;
1108
1109                 /*
1110                  *      Create the new clients first, and add them
1111                  *      to the CONF_SECTION, where they're automagically
1112                  *      freed if anything goes wrong.
1113                  */
1114                 snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
1115                          radius_dir, mainconfig.radiusd_conf);
1116                 clients = clients_parse_section(buffer, mainconfig.config);
1117                 if (!clients) {
1118                         return -1;
1119                 }
1120
1121                 /*
1122                  *      Free the old trees AFTER replacing them with
1123                  *      the new ones...
1124                  */
1125                 old_clients = mainconfig.clients;
1126                 mainconfig.clients = clients;
1127         }
1128
1129         rl_init_proxy();
1130
1131         /*  Reload the modules.  */
1132         DEBUG2("radiusd:  entering modules setup");
1133         if (setup_modules(reload) < 0) {
1134                 radlog(L_ERR|L_CONS, "Errors setting up modules");
1135                 return -1;
1136         }
1137         return 0;
1138 }
1139
1140 /*
1141  *      Free the configuration.  Called only when the server is exiting.
1142  */
1143 int free_mainconfig(void)
1144 {
1145         /*
1146          *      Clean up the configuration data
1147          *      structures.
1148          */
1149         cf_section_free(&mainconfig.config);
1150         realm_free(mainconfig.realms);
1151         listen_free(&mainconfig.listen);
1152
1153         return 0;
1154 }