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