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