2af8889723c92d2d8902212aab8271b0c348ac6e
[freeradius.git] / src / main / mainconfig.c
1 /*
2  * mainconf.c   Handle the server's configuration.
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2002,2006-2007  The FreeRADIUS server project
21  * Copyright 2002  Alan DeKok <aland@ox.org>
22  */
23
24 RCSID("$Id$")
25
26 #include <freeradius-devel/radiusd.h>
27 #include <freeradius-devel/modules.h>
28 #include <freeradius-devel/rad_assert.h>
29
30 #include <sys/stat.h>
31 #include <pwd.h>
32 #include <grp.h>
33
34 #ifdef HAVE_SYSLOG_H
35 #  include <syslog.h>
36 #endif
37
38 #ifdef HAVE_FCNTL_H
39 #  include <fcntl.h>
40 #endif
41
42 main_config_t           main_config;                            //!< Main server configuration.
43 extern fr_cond_t        *debug_condition;
44 fr_cond_t               *debug_condition = NULL;                        //!< Condition used to mark packets up for checking.
45 bool                    event_loop_started = false;             //!< Whether the main event loop has been started yet.
46
47 typedef struct cached_config_t {
48         struct cached_config_t *next;
49         time_t          created;
50         CONF_SECTION    *cs;
51 } cached_config_t;
52
53 static cached_config_t  *cs_cache = NULL;
54
55 /*
56  *      Temporary local variables for parsing the configuration
57  *      file.
58  */
59 #ifdef HAVE_SETUID
60 /*
61  *      Systems that have set/getresuid also have setuid.
62  */
63 static uid_t server_uid = 0;
64 static gid_t server_gid = 0;
65 static char const *uid_name = NULL;
66 static char const *gid_name = NULL;
67 #endif
68 static char const *chroot_dir = NULL;
69 static bool allow_core_dumps = false;
70 static char const *radlog_dest = NULL;
71
72 /*
73  *      These are not used anywhere else..
74  */
75 static char const       *localstatedir = NULL;
76 static char const       *prefix = NULL;
77 static char const       *my_name = NULL;
78 static char const       *sbindir = NULL;
79 static char const       *run_dir = NULL;
80 static char const       *syslog_facility = NULL;
81 static bool             do_colourise = false;
82
83 static char const       *radius_dir = NULL;     //!< Path to raddb directory
84
85 /**********************************************************************
86  *
87  *      We need to figure out where the logs go, before doing anything
88  *      else.  This is so that the log messages go to the correct
89  *      place.
90  *
91  *      BUT, we want the settings from the command line to over-ride
92  *      the ones in the configuration file.  So, these items are
93  *      parsed ONLY if there is no "-l foo" on the command line.
94  *
95  **********************************************************************/
96
97 /*
98  *      Log destinations
99  */
100 static const CONF_PARSER startup_log_config[] = {
101         { "destination",  FR_CONF_POINTER(PW_TYPE_STRING, &radlog_dest), "files" },
102         { "syslog_facility",  FR_CONF_POINTER(PW_TYPE_STRING, &syslog_facility), STRINGIFY(0) },
103
104         { "localstatedir", FR_CONF_POINTER(PW_TYPE_STRING, &localstatedir), "${prefix}/var"},
105         { "logdir", FR_CONF_POINTER(PW_TYPE_STRING, &radlog_dir), "${localstatedir}/log"},
106         { "file",  FR_CONF_POINTER(PW_TYPE_STRING, &main_config.log_file), "${logdir}/radius.log" },
107         { "requests",  FR_CONF_POINTER(PW_TYPE_STRING | PW_TYPE_DEPRECATED, &default_log.file), NULL },
108         { NULL, -1, 0, NULL, NULL }
109 };
110
111
112 /*
113  *      Basic configuration for the server.
114  */
115 static const CONF_PARSER startup_server_config[] = {
116         { "log",  FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) startup_log_config },
117
118         { "name", FR_CONF_POINTER(PW_TYPE_STRING, &my_name), "radiusd"},
119         { "prefix", FR_CONF_POINTER(PW_TYPE_STRING, &prefix), "/usr/local"},
120
121         { "log_file",  FR_CONF_POINTER(PW_TYPE_STRING, &main_config.log_file), NULL },
122         { "log_destination", FR_CONF_POINTER(PW_TYPE_STRING, &radlog_dest), NULL },
123         { "use_utc", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &log_dates_utc), NULL },
124         { NULL, -1, 0, NULL, NULL }
125 };
126
127
128 /**********************************************************************
129  *
130  *      Now that we've parsed the log destination, AND the security
131  *      items, we can parse the rest of the configuration items.
132  *
133  **********************************************************************/
134 static const CONF_PARSER log_config[] = {
135         { "stripped_names", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &log_stripped_names),"no" },
136         { "auth", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &main_config.log_auth), "no" },
137         { "auth_badpass", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &main_config.log_auth_badpass), "no" },
138         { "auth_goodpass", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &main_config.log_auth_goodpass), "no" },
139         { "msg_badpass", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.auth_badpass_msg), NULL},
140         { "msg_goodpass", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.auth_goodpass_msg), NULL},
141         { "colourise",FR_CONF_POINTER(PW_TYPE_BOOLEAN, &do_colourise), NULL },
142         { "use_utc", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &log_dates_utc), NULL },
143         { "msg_denied", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.denied_msg),
144           "You are already logged in - access denied" },
145
146         { NULL, -1, 0, NULL, NULL }
147 };
148
149
150 /*
151  *  Security configuration for the server.
152  */
153 static const CONF_PARSER security_config[] = {
154         { "max_attributes",  FR_CONF_POINTER(PW_TYPE_INTEGER, &fr_max_attributes), STRINGIFY(0) },
155         { "reject_delay",  FR_CONF_POINTER(PW_TYPE_TIMEVAL, &main_config.reject_delay), STRINGIFY(0) },
156         { "status_server", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &main_config.status_server), "no"},
157 #ifdef ENABLE_OPENSSL_VERSION_CHECK
158         { "allow_vulnerable_openssl", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.allow_vulnerable_openssl), "no"},
159 #endif
160         { NULL, -1, 0, NULL, NULL }
161 };
162
163 static const CONF_PARSER resources[] = {
164         /*
165          *      Don't set a default here.  It's set in the code, below.  This means that
166          *      the config item will *not* get printed out in debug mode, so that no one knows
167          *      it exists.
168          */
169         { "talloc_pool_size", FR_CONF_POINTER(PW_TYPE_INTEGER, &main_config.talloc_pool_size), NULL },
170
171         { NULL, -1, 0, NULL, NULL }
172 };
173
174 static const CONF_PARSER server_config[] = {
175         /*
176          *      FIXME: 'prefix' is the ONLY one which should be
177          *      configured at compile time.  Hard-coding it here is
178          *      bad.  It will be cleaned up once we clean up the
179          *      hard-coded defines for the locations of the various
180          *      files.
181          */
182         { "name", FR_CONF_POINTER(PW_TYPE_STRING, &my_name), "radiusd"},
183         { "prefix", FR_CONF_POINTER(PW_TYPE_STRING, &prefix), "/usr/local"},
184         { "localstatedir", FR_CONF_POINTER(PW_TYPE_STRING, &localstatedir), "${prefix}/var"},
185         { "sbindir", FR_CONF_POINTER(PW_TYPE_STRING, &sbindir), "${prefix}/sbin"},
186         { "logdir", FR_CONF_POINTER(PW_TYPE_STRING, &radlog_dir), "${localstatedir}/log"},
187         { "run_dir", FR_CONF_POINTER(PW_TYPE_STRING, &run_dir), "${localstatedir}/run/${name}"},
188         { "libdir", FR_CONF_POINTER(PW_TYPE_STRING, &radlib_dir), "${prefix}/lib"},
189         { "radacctdir", FR_CONF_POINTER(PW_TYPE_STRING, &radacct_dir), "${logdir}/radacct" },
190         { "panic_action", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.panic_action), NULL},
191         { "hostname_lookups", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &fr_dns_lookups), "no" },
192         { "max_request_time", FR_CONF_POINTER(PW_TYPE_INTEGER, &main_config.max_request_time), STRINGIFY(MAX_REQUEST_TIME) },
193         { "cleanup_delay", FR_CONF_POINTER(PW_TYPE_INTEGER, &main_config.cleanup_delay), STRINGIFY(CLEANUP_DELAY) },
194         { "max_requests", FR_CONF_POINTER(PW_TYPE_INTEGER, &main_config.max_requests), STRINGIFY(MAX_REQUESTS) },
195         { "pidfile", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.pid_file), "${run_dir}/radiusd.pid"},
196         { "checkrad", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.checkrad), "${sbindir}/checkrad" },
197
198         { "debug_level", FR_CONF_POINTER(PW_TYPE_INTEGER, &main_config.debug_level), "0"},
199
200 #ifdef WITH_PROXY
201         { "proxy_requests", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &main_config.proxy_requests), "yes" },
202 #endif
203         { "log", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) log_config },
204
205         { "resources", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) resources },
206
207         /*
208          *      People with old configs will have these.  They are listed
209          *      AFTER the "log" section, so if they exist in radiusd.conf,
210          *      it will prefer "log_foo = bar" to "log { foo = bar }".
211          *      They're listed with default values of NULL, so that if they
212          *      DON'T exist in radiusd.conf, then the previously parsed
213          *      values for "log { foo = bar}" will be used.
214          */
215         { "log_auth", FR_CONF_POINTER(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, &main_config.log_auth), NULL },
216         { "log_auth_badpass", FR_CONF_POINTER(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, &main_config.log_auth_badpass), NULL },
217         { "log_auth_goodpass", FR_CONF_POINTER(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, &main_config.log_auth_goodpass), NULL },
218         { "log_stripped_names", FR_CONF_POINTER(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, &log_stripped_names), NULL },
219
220         {  "security", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) security_config },
221
222         { NULL, -1, 0, NULL, NULL }
223 };
224
225
226 /**********************************************************************
227  *
228  *      The next few items are here as a "bootstrap" for security.
229  *      They allow the server to switch users, chroot, while still
230  *      opening the various output files with the correct permission.
231  *
232  *      It's rare (or impossible) to have parse errors here, so we
233  *      don't worry too much about that.  In contrast, when we parse
234  *      the rest of the configuration, we CAN get parse errors.  We
235  *      want THOSE parse errors to go to the log file, and we want the
236  *      log file to have the correct permissions.
237  *
238  **********************************************************************/
239 static const CONF_PARSER bootstrap_security_config[] = {
240 #ifdef HAVE_SETUID
241         { "user",  FR_CONF_POINTER(PW_TYPE_STRING, &uid_name), NULL },
242         { "group", FR_CONF_POINTER(PW_TYPE_STRING, &gid_name), NULL },
243 #endif
244         { "chroot",  FR_CONF_POINTER(PW_TYPE_STRING, &chroot_dir), NULL },
245         { "allow_core_dumps", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &allow_core_dumps), "no" },
246
247         { NULL, -1, 0, NULL, NULL }
248 };
249
250 static const CONF_PARSER bootstrap_config[] = {
251         {  "security", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) bootstrap_security_config },
252
253         { "name", FR_CONF_POINTER(PW_TYPE_STRING, &my_name), "radiusd"},
254         { "prefix", FR_CONF_POINTER(PW_TYPE_STRING, &prefix), "/usr/local"},
255         { "localstatedir", FR_CONF_POINTER(PW_TYPE_STRING, &localstatedir), "${prefix}/var"},
256
257         { "logdir", FR_CONF_POINTER(PW_TYPE_STRING, &radlog_dir), "${localstatedir}/log"},
258         { "run_dir", FR_CONF_POINTER(PW_TYPE_STRING, &run_dir), "${localstatedir}/run/${name}"},
259
260         /*
261          *      For backwards compatibility.
262          */
263 #ifdef HAVE_SETUID
264         { "user",  FR_CONF_POINTER(PW_TYPE_STRING | PW_TYPE_DEPRECATED, &uid_name), NULL },
265         { "group",  FR_CONF_POINTER(PW_TYPE_STRING | PW_TYPE_DEPRECATED, &gid_name), NULL },
266 #endif
267         { "chroot",  FR_CONF_POINTER(PW_TYPE_STRING | PW_TYPE_DEPRECATED, &chroot_dir), NULL },
268         { "allow_core_dumps", FR_CONF_POINTER(PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED, &allow_core_dumps), NULL },
269
270         { NULL, -1, 0, NULL, NULL }
271 };
272
273
274 static size_t config_escape_func(UNUSED REQUEST *request, char *out, size_t outlen, char const *in, UNUSED void *arg)
275 {
276         size_t len = 0;
277         static char const disallowed[] = "%{}\\'\"`";
278
279         while (in[0]) {
280                 /*
281                  *      Non-printable characters get replaced with their
282                  *      mime-encoded equivalents.
283                  */
284                 if ((in[0] < 32)) {
285                         if (outlen <= 3) break;
286
287                         snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
288                         in++;
289                         out += 3;
290                         outlen -= 3;
291                         len += 3;
292                         continue;
293
294                 } else if (strchr(disallowed, *in) != NULL) {
295                         if (outlen <= 2) break;
296
297                         out[0] = '\\';
298                         out[1] = *in;
299                         in++;
300                         out += 2;
301                         outlen -= 2;
302                         len += 2;
303                         continue;
304                 }
305
306                 /*
307                  *      Only one byte left.
308                  */
309                 if (outlen <= 1) {
310                         break;
311                 }
312
313                 /*
314                  *      Allowed character.
315                  */
316                 *out = *in;
317                 out++;
318                 in++;
319                 outlen--;
320                 len++;
321         }
322         *out = '\0';
323         return len;
324 }
325
326 /*
327  *      Xlat for %{config:section.subsection.attribute}
328  */
329 static ssize_t xlat_config(UNUSED void *instance, REQUEST *request, char const *fmt, char *out, size_t outlen)
330 {
331         char const *value;
332         CONF_PAIR *cp;
333         CONF_ITEM *ci;
334         char buffer[1024];
335
336         /*
337          *      Expand it safely.
338          */
339         if (radius_xlat(buffer, sizeof(buffer), request, fmt, config_escape_func, NULL) < 0) {
340                 return 0;
341         }
342
343         ci = cf_reference_item(request->root->config,
344                                request->root->config, buffer);
345         if (!ci || !cf_item_is_pair(ci)) {
346                 REDEBUG("Config item \"%s\" does not exist", fmt);
347                 *out = '\0';
348                 return -1;
349         }
350
351         cp = cf_item_to_pair(ci);
352
353         /*
354          *  Ensure that we only copy what's necessary.
355          *
356          *  If 'outlen' is too small, then the output is chopped to fit.
357          */
358         value = cf_pair_value(cp);
359         if (!value) {
360                 out[0] = '\0';
361                 return 0;
362         }
363
364         if (outlen > strlen(value)) {
365                 outlen = strlen(value) + 1;
366         }
367
368         strlcpy(out, value, outlen);
369
370         return strlen(out);
371 }
372
373
374 /*
375  *      Xlat for %{client:foo}
376  */
377 static ssize_t xlat_client(UNUSED void *instance, REQUEST *request, char const *fmt, char *out, size_t outlen)
378 {
379         char const *value = NULL;
380         CONF_PAIR *cp;
381
382         if (!fmt || !out || (outlen < 1)) return 0;
383
384         if (!request->client) {
385                 RWDEBUG("No client associated with this request");
386                 *out = '\0';
387                 return 0;
388         }
389
390         cp = cf_pair_find(request->client->cs, fmt);
391         if (!cp || !(value = cf_pair_value(cp))) {
392                 if (strcmp(fmt, "shortname") == 0) {
393                         strlcpy(out, request->client->shortname, outlen);
394                         return strlen(out);
395                 }
396                 *out = '\0';
397                 return 0;
398         }
399
400         strlcpy(out, value, outlen);
401
402         return strlen(out);
403 }
404
405 /*
406  *      Xlat for %{getclient:<ipaddr>.foo}
407  */
408 static ssize_t xlat_getclient(UNUSED void *instance, REQUEST *request, char const *fmt, char *out, size_t outlen)
409 {
410         char const *value = NULL;
411         char buffer[INET6_ADDRSTRLEN], *q;
412         char const *p = fmt;
413         fr_ipaddr_t ip;
414         CONF_PAIR *cp;
415         RADCLIENT *client = NULL;
416
417         if (!fmt || !out || (outlen < 1)) return 0;
418
419         q = strrchr(p, '.');
420         if (!q || (q == p) || (((size_t)(q - p)) > sizeof(buffer))) {
421                 REDEBUG("Invalid client string");
422                 goto error;
423         }
424
425         strlcpy(buffer, p, (q + 1) - p);
426         if (fr_pton(&ip, buffer, -1, AF_UNSPEC, false) < 0) {
427                 REDEBUG("\"%s\" is not a valid IPv4 or IPv6 address", buffer);
428                 goto error;
429         }
430
431         fmt = q + 1;
432
433         client = client_find(NULL, &ip, IPPROTO_IP);
434         if (!client) {
435                 RDEBUG("No client found with IP \"%s\"", buffer);
436                 *out = '\0';
437                 return 0;
438         }
439
440         cp = cf_pair_find(client->cs, fmt);
441         if (!cp || !(value = cf_pair_value(cp))) {
442                 if (strcmp(fmt, "shortname") == 0) {
443                         strlcpy(out, request->client->shortname, outlen);
444                         return strlen(out);
445                 }
446                 *out = '\0';
447                 return 0;
448         }
449
450         strlcpy(out, value, outlen);
451         return strlen(out);
452
453         error:
454         *out = '\0';
455         return -1;
456 }
457
458 #ifdef HAVE_SETUID
459 /*
460  *  Do chroot, if requested.
461  *
462  *  Switch UID and GID to what is specified in the config file
463  */
464 static int switch_users(CONF_SECTION *cs)
465 {
466         bool do_suid = false;
467         bool do_sgid = false;
468
469         /*
470          *      Get the current maximum for core files.  Do this
471          *      before anything else so as to ensure it's properly
472          *      initialized.
473          */
474         if (fr_set_dumpable_init() < 0) {
475                 fr_perror("radiusd");
476                 return 0;
477         }
478
479         /*
480          *      Don't do chroot/setuid/setgid if we're in debugging
481          *      as non-root.
482          */
483         if (rad_debug_lvl && (getuid() != 0)) return 1;
484
485         if (cf_section_parse(cs, NULL, bootstrap_config) < 0) {
486                 fprintf(stderr, "radiusd: Error: Failed to parse user/group information.\n");
487                 return 0;
488         }
489
490 #ifdef HAVE_GRP_H
491         /*
492          *      Get the correct GID for the server.
493          */
494         server_gid = getgid();
495
496         if (gid_name) {
497                 struct group *gr;
498
499                 gr = getgrnam(gid_name);
500                 if (!gr) {
501                         fprintf(stderr, "%s: Cannot get ID for group %s: %s\n",
502                                 progname, gid_name, fr_syserror(errno));
503                         return 0;
504                 }
505
506                 if (server_gid != gr->gr_gid) {
507                         server_gid = gr->gr_gid;
508                         do_sgid = true;
509                 }
510         }
511 #endif
512
513         /*
514          *      Get the correct UID for the server.
515          */
516         server_uid = getuid();
517
518         if (uid_name) {
519                 struct passwd *user;
520
521                 if (rad_getpwnam(cs, &user, uid_name) < 0) {
522                         fprintf(stderr, "%s: Cannot get passwd entry for user %s: %s\n",
523                                 progname, uid_name, fr_strerror());
524                         return 0;
525                 }
526
527                 /*
528                  *      We're not the correct user.  Go set that.
529                  */
530                 if (server_uid != user->pw_uid) {
531                         server_uid = user->pw_uid;
532                         do_suid = true;
533 #ifdef HAVE_INITGROUPS
534                         if (initgroups(uid_name, server_gid) < 0) {
535                                 fprintf(stderr, "%s: Cannot initialize supplementary group list for user %s: %s\n",
536                                         progname, uid_name, fr_syserror(errno));
537                                 talloc_free(user);
538                                 return 0;
539                         }
540 #endif
541                 }
542
543                 talloc_free(user);
544         }
545
546         /*
547          *      Do chroot BEFORE changing UIDs.
548          */
549         if (chroot_dir) {
550                 if (chroot(chroot_dir) < 0) {
551                         fprintf(stderr, "%s: Failed to perform chroot %s: %s",
552                                 progname, chroot_dir, fr_syserror(errno));
553                         return 0;
554                 }
555
556                 /*
557                  *      Note that we leave chdir alone.  It may be
558                  *      OUTSIDE of the root.  This allows us to read
559                  *      the configuration from "-d ./etc/raddb", with
560                  *      the chroot as "./chroot/" for example.  After
561                  *      the server has been loaded, it does a "cd
562                  *      ${logdir}" below, so that core files (if any)
563                  *      go to a logging directory.
564                  *
565                  *      This also allows the configuration of the
566                  *      server to be outside of the chroot.  If the
567                  *      server is statically linked, then the only
568                  *      things needed inside of the chroot are the
569                  *      logging directories.
570                  */
571         }
572
573 #ifdef HAVE_GRP_H
574         /*
575          *      Set the GID.  Don't bother checking it.
576          */
577         if (do_sgid) {
578                 if (setgid(server_gid) < 0){
579                         fprintf(stderr, "%s: Failed setting group to %s: %s",
580                                 progname, gid_name, fr_syserror(errno));
581                         return 0;
582                 }
583         }
584 #endif
585
586         /*
587          *      The directories for PID files and logs must exist.  We
588          *      need to create them if we're told to write files to
589          *      those directories.
590          *
591          *      Because this creation is new in 3.0.9, it's a soft
592          *      fail.
593          *
594          */
595         if (main_config.write_pid) {
596                 char *my_dir;
597
598                 my_dir = talloc_strdup(NULL, run_dir);
599                 if (rad_mkdir(my_dir, 0750, server_uid, server_gid) < 0) {
600                         DEBUG("Failed to create run_dir %s: %s",
601                               my_dir, strerror(errno));
602                 }
603                 talloc_free(my_dir);
604         }
605
606         if (default_log.dst == L_DST_FILES) {
607                 char *my_dir;
608
609                 my_dir = talloc_strdup(NULL, radlog_dir);
610                 if (rad_mkdir(my_dir, 0750, server_uid, server_gid) < 0) {
611                         DEBUG("Failed to create logdir %s: %s",
612                               my_dir, strerror(errno));
613                 }
614                 talloc_free(my_dir);
615         }
616
617         /*
618          *      Once we're done with all of the privileged work,
619          *      permanently change the UID.
620          */
621         if (do_suid) {
622                 rad_suid_set_down_uid(server_uid);
623                 rad_suid_down();
624         }
625
626         /*
627          *      If we don't already have a log file open, open one
628          *      now.  We may not have been logging anything yet.  The
629          *      server normally starts up fairly quietly.
630          */
631         if ((default_log.dst == L_DST_FILES) &&
632             (default_log.fd < 0)) {
633                 default_log.fd = open(main_config.log_file,
634                                       O_WRONLY | O_APPEND | O_CREAT, 0640);
635                 if (default_log.fd < 0) {
636                         fprintf(stderr, "radiusd: Failed to open log file %s: %s\n", main_config.log_file, fr_syserror(errno));
637                         return 0;
638                 }
639         }
640
641         /*
642          *      If we need to change UID, ensure that the log files
643          *      have the correct owner && group.
644          *
645          *      We have to do this because some log files MAY already
646          *      have been written as root.  We need to change them to
647          *      have the correct ownership before proceeding.
648          */
649         if ((do_suid || do_sgid) &&
650             (default_log.dst == L_DST_FILES)) {
651                 if (fchown(default_log.fd, server_uid, server_gid) < 0) {
652                         fprintf(stderr, "%s: Cannot change ownership of log file %s: %s\n",
653                                 progname, main_config.log_file, fr_syserror(errno));
654                         return 0;
655                 }
656         }
657
658         /*
659          *      This also clears the dumpable flag if core dumps
660          *      aren't allowed.
661          */
662         if (fr_set_dumpable(allow_core_dumps) < 0) {
663                 ERROR("%s", fr_strerror());
664         }
665
666         if (allow_core_dumps) {
667                 INFO("Core dumps are enabled");
668         }
669
670         return 1;
671 }
672 #endif  /* HAVE_SETUID */
673
674 /** Set the global radius config directory.
675  *
676  * @param ctx Where to allocate the memory for the path string.
677  * @param path to config dir root e.g. /usr/local/etc/raddb
678  */
679 void set_radius_dir(TALLOC_CTX *ctx, char const *path)
680 {
681         if (radius_dir) {
682                 char *p;
683
684                 memcpy(&p, &radius_dir, sizeof(p));
685                 talloc_free(p);
686                 radius_dir = NULL;
687         }
688         if (path) radius_dir = talloc_strdup(ctx, path);
689 }
690
691 /** Get the global radius config directory.
692  *
693  * @return the global radius config directory.
694  */
695 char const *get_radius_dir(void)
696 {
697         return radius_dir;
698 }
699
700 /*
701  *      Read config files.
702  *
703  *      This function can ONLY be called from the main server process.
704  */
705 int main_config_init(void)
706 {
707         char const *p = NULL;
708         CONF_SECTION *cs, *subcs;
709         struct stat statbuf;
710         cached_config_t *cc;
711         char buffer[1024];
712
713         if (stat(radius_dir, &statbuf) < 0) {
714                 ERROR("Errors reading %s: %s",
715                        radius_dir, fr_syserror(errno));
716                 return -1;
717         }
718
719 #ifdef S_IWOTH
720         if ((statbuf.st_mode & S_IWOTH) != 0) {
721                 ERROR("Configuration directory %s is globally writable.  Refusing to start due to insecure configuration.",
722                        radius_dir);
723           return -1;
724         }
725 #endif
726
727 #if 0 && defined(S_IROTH)
728         if (statbuf.st_mode & S_IROTH != 0) {
729                 ERROR("Configuration directory %s is globally readable.  Refusing to start due to insecure configuration.",
730                        radius_dir);
731                 return -1;
732         }
733 #endif
734         INFO("Starting - reading configuration files ...");
735
736         /*
737          *      We need to load the dictionaries before reading the
738          *      configuration files.  This is because of the
739          *      pre-compilation in conffile.c.  That should probably
740          *      be fixed to be done as a second stage.
741          */
742         if (!main_config.dictionary_dir) {
743                 main_config.dictionary_dir = DICTDIR;
744         }
745
746         /*
747          *      About sizeof(REQUEST) + sizeof(RADIUS_PACKET) * 2 + sizeof(VALUE_PAIR) * 400
748          *
749          *      Which should be enough for many configurations.
750          */
751         main_config.talloc_pool_size = 32 * 1024; /* default */
752
753         /*
754          *      Read the distribution dictionaries first, then
755          *      the ones in raddb.
756          */
757         DEBUG2("including dictionary file %s/%s", main_config.dictionary_dir, RADIUS_DICTIONARY);
758         if (dict_init(main_config.dictionary_dir, RADIUS_DICTIONARY) != 0) {
759                 ERROR("Errors reading dictionary: %s",
760                       fr_strerror());
761                 return -1;
762         }
763
764 #define DICT_READ_OPTIONAL(_d, _n) \
765 do {\
766         switch (dict_read(_d, _n)) {\
767         case -1:\
768                 ERROR("Errors reading %s/%s: %s", _d, _n, fr_strerror());\
769                 return -1;\
770         case 0:\
771                 DEBUG2("including dictionary file %s/%s", _d,_n);\
772                 break;\
773         default:\
774                 break;\
775         }\
776 } while (0)
777
778         /*
779          *      Try to load protocol-specific dictionaries.  It's OK
780          *      if they don't exist.
781          */
782 #ifdef WITH_DHCP
783         DICT_READ_OPTIONAL(main_config.dictionary_dir, "dictionary.dhcp");
784 #endif
785
786 #ifdef WITH_VMPS
787         DICT_READ_OPTIONAL(main_config.dictionary_dir, "dictionary.vqp");
788 #endif
789
790         /*
791          *      It's OK if this one doesn't exist.
792          */
793         DICT_READ_OPTIONAL(radius_dir, RADIUS_DICTIONARY);
794
795         cs = cf_section_alloc(NULL, "main", NULL);
796         if (!cs) return -1;
797
798         /*
799          *      Add a 'feature' subsection off the main config
800          *      We check if it's defined first, as the user may
801          *      have defined their own feature flags, or want
802          *      to manually override the ones set by modules
803          *      or the server.
804          */
805         subcs = cf_section_sub_find(cs, "feature");
806         if (!subcs) {
807                 subcs = cf_section_alloc(cs, "feature", NULL);
808                 if (!subcs) return -1;
809
810                 cf_section_add(cs, subcs);
811         }
812         version_init_features(subcs);
813
814         /*
815          *      Add a 'version' subsection off the main config
816          *      We check if it's defined first, this is for
817          *      backwards compatibility.
818          */
819         subcs = cf_section_sub_find(cs, "version");
820         if (!subcs) {
821                 subcs = cf_section_alloc(cs, "version", NULL);
822                 if (!subcs) return -1;
823                 cf_section_add(cs, subcs);
824         }
825         version_init_numbers(subcs);
826
827         /* Read the configuration file */
828         snprintf(buffer, sizeof(buffer), "%.200s/%.50s.conf", radius_dir, main_config.name);
829         if (cf_file_read(cs, buffer) < 0) {
830                 ERROR("Errors reading or parsing %s", buffer);
831                 talloc_free(cs);
832                 return -1;
833         }
834
835         /*
836          *      If there was no log destination set on the command line,
837          *      set it now.
838          */
839         if (default_log.dst == L_DST_NULL) {
840                 if (cf_section_parse(cs, NULL, startup_server_config) < 0) {
841                         fprintf(stderr, "radiusd: Error: Failed to parse log{} section.\n");
842                         cf_file_free(cs);
843                         return -1;
844                 }
845
846                 if (!radlog_dest) {
847                         fprintf(stderr, "radiusd: Error: No log destination specified.\n");
848                         cf_file_free(cs);
849                         return -1;
850                 }
851
852                 default_log.dst = fr_str2int(log_str2dst, radlog_dest,
853                                               L_DST_NUM_DEST);
854                 if (default_log.dst == L_DST_NUM_DEST) {
855                         fprintf(stderr, "radiusd: Error: Unknown log_destination %s\n",
856                                 radlog_dest);
857                         cf_file_free(cs);
858                         return -1;
859                 }
860
861                 if (default_log.dst == L_DST_SYSLOG) {
862                         /*
863                          *      Make sure syslog_facility isn't NULL
864                          *      before using it
865                          */
866                         if (!syslog_facility) {
867                                 fprintf(stderr, "radiusd: Error: Syslog chosen but no facility was specified\n");
868                                 cf_file_free(cs);
869                                 return -1;
870                         }
871                         main_config.syslog_facility = fr_str2int(syslog_facility_table, syslog_facility, -1);
872                         if (main_config.syslog_facility < 0) {
873                                 fprintf(stderr, "radiusd: Error: Unknown syslog_facility %s\n",
874                                         syslog_facility);
875                                 cf_file_free(cs);
876                                 return -1;
877                         }
878
879 #ifdef HAVE_SYSLOG_H
880                         /*
881                          *      Call openlog only once, when the
882                          *      program starts.
883                          */
884                         openlog(progname, LOG_PID, main_config.syslog_facility);
885 #endif
886
887                 } else if (default_log.dst == L_DST_FILES) {
888                         if (!main_config.log_file) {
889                                 fprintf(stderr, "radiusd: Error: Specified \"files\" as a log destination, but no log filename was given!\n");
890                                 cf_file_free(cs);
891                                 return -1;
892                         }
893                 }
894         }
895
896 #ifdef HAVE_SETUID
897         /*
898          *      Switch users as early as possible.
899          */
900         if (!switch_users(cs)) fr_exit(1);
901 #endif
902
903         /*
904          *      This allows us to figure out where, relative to
905          *      radiusd.conf, the other configuration files exist.
906          */
907         if (cf_section_parse(cs, NULL, server_config) < 0) return -1;
908
909         /*
910          *      We ignore colourization of output until after the
911          *      configuration files have been parsed.
912          */
913         p = getenv("TERM");
914         if (do_colourise && p && isatty(default_log.fd) && strstr(p, "xterm")) {
915                 default_log.colourise = true;
916         } else {
917                 default_log.colourise = false;
918         }
919
920         /*
921          *      Starting the server, WITHOUT "-x" on the
922          *      command-line: use whatever is in the config
923          *      file.
924          */
925         if (rad_debug_lvl == 0) {
926                 rad_debug_lvl = main_config.debug_level;
927         }
928         fr_debug_lvl = rad_debug_lvl;
929
930         FR_INTEGER_COND_CHECK("max_request_time", main_config.max_request_time,
931                               (main_config.max_request_time != 0), 100);
932
933         /*
934          *      reject_delay can be zero.  OR 1 though 10.
935          */
936         if ((main_config.reject_delay.tv_sec != 0) || (main_config.reject_delay.tv_usec != 0)) {
937                 FR_TIMEVAL_BOUND_CHECK("reject_delay", &main_config.reject_delay, >=, 1, 0);
938         }
939         FR_TIMEVAL_BOUND_CHECK("reject_delay", &main_config.reject_delay, <=, 10, 0);
940
941         FR_INTEGER_BOUND_CHECK("cleanup_delay", main_config.cleanup_delay, <=, 10);
942
943         FR_INTEGER_BOUND_CHECK("resources.talloc_pool_size", main_config.talloc_pool_size, >=, 16 * 1024);
944         FR_INTEGER_BOUND_CHECK("resources.talloc_pool_size", main_config.talloc_pool_size, <=, 1024 * 1024);
945
946         /*
947          * Set default initial request processing delay to 1/3 of a second.
948          * Will be updated by the lowest response window across all home servers,
949          * if it is less than this.
950          */
951         main_config.init_delay.tv_sec = 0;
952         main_config.init_delay.tv_usec = 2* (1000000 / 3);
953
954         /*
955          *      Free the old configuration items, and replace them
956          *      with the new ones.
957          *
958          *      Note that where possible, we do atomic switch-overs,
959          *      to ensure that the pointers are always valid.
960          */
961         rad_assert(main_config.config == NULL);
962         root_config = main_config.config = cs;
963
964         DEBUG2("%s: #### Loading Realms and Home Servers ####", main_config.name);
965         if (!realms_init(cs)) {
966                 return -1;
967         }
968
969         DEBUG2("%s: #### Loading Clients ####", main_config.name);
970         if (!client_list_parse_section(cs, false)) {
971                 return -1;
972         }
973
974         /*
975          *  Register the %{config:section.subsection} xlat function.
976          */
977         xlat_register("config", xlat_config, NULL, NULL);
978         xlat_register("client", xlat_client, NULL, NULL);
979         xlat_register("getclient", xlat_getclient, NULL, NULL);
980
981         /*
982          *  Go update our behaviour, based on the configuration
983          *  changes.
984          */
985
986         /*
987          *      Sanity check the configuration for internal
988          *      consistency.
989          */
990         FR_TIMEVAL_BOUND_CHECK("reject_delay", &main_config.reject_delay, <=, main_config.cleanup_delay, 0);
991
992         if (chroot_dir) {
993                 if (chdir(radlog_dir) < 0) {
994                         ERROR("Failed to 'chdir %s' after chroot: %s",
995                                radlog_dir, fr_syserror(errno));
996                         return -1;
997                 }
998         }
999
1000         cc = talloc_zero(NULL, cached_config_t);
1001         if (!cc) return -1;
1002
1003         cc->cs = talloc_steal(cc ,cs);
1004         rad_assert(cs_cache == NULL);
1005         cs_cache = cc;
1006
1007         /* Clear any unprocessed configuration errors */
1008         (void) fr_strerror();
1009
1010         return 0;
1011 }
1012
1013 /*
1014  *      Free the configuration.  Called only when the server is exiting.
1015  */
1016 int main_config_free(void)
1017 {
1018         virtual_servers_free(0);
1019
1020         /*
1021          *      Clean up the configuration data
1022          *      structures.
1023          */
1024         client_list_free(NULL);
1025         realms_free();
1026         listen_free(&main_config.listen);
1027
1028         /*
1029          *      Frees current config and any previous configs.
1030          */
1031         TALLOC_FREE(cs_cache);
1032         dict_free();
1033
1034         return 0;
1035 }
1036
1037 void hup_logfile(void)
1038 {
1039         int fd, old_fd;
1040
1041         if (default_log.dst != L_DST_FILES) return;
1042
1043         fd = open(main_config.log_file,
1044                   O_WRONLY | O_APPEND | O_CREAT, 0640);
1045         if (fd >= 0) {
1046                 /*
1047                  *      Atomic swap. We'd like to keep the old
1048                  *      FD around so that callers don't
1049                  *      suddenly find the FD closed, and the
1050                  *      writes go nowhere.  But that's hard to
1051                  *      do.  So... we have the case where a
1052                  *      log message *might* be lost on HUP.
1053                  */
1054                 old_fd = default_log.fd;
1055                 default_log.fd = fd;
1056                 close(old_fd);
1057         }
1058 }
1059
1060 void main_config_hup(void)
1061 {
1062         int rcode;
1063         cached_config_t *cc;
1064         CONF_SECTION *cs;
1065         char buffer[1024];
1066
1067         /*
1068          *      Re-open the log file.  If we can't, then keep logging
1069          *      to the old log file.
1070          *
1071          *      The "open log file" code is here rather than in log.c,
1072          *      because it makes that function MUCH simpler.
1073          */
1074         hup_logfile();
1075
1076         rcode = cf_file_changed(cs_cache->cs);
1077         if (rcode == CF_FILE_NONE) {
1078                 INFO("HUP - No files changed.  Ignoring");
1079                 return;
1080         }
1081
1082         if (rcode == CF_FILE_ERROR) {
1083                 INFO("HUP - Cannot read configuration files.  Ignoring");
1084                 return;
1085         }
1086
1087         if (rcode == CF_FILE_MODULE) {
1088                 INFO("HUP - Files loaded by a module have changed.");
1089                 return;
1090         }
1091
1092         cs = cf_section_alloc(NULL, "main", NULL);
1093         if (!cs) return;
1094
1095         /* Read the configuration file */
1096         snprintf(buffer, sizeof(buffer), "%.200s/%.50s.conf", radius_dir, main_config.name);
1097
1098         INFO("HUP - Re-reading configuration files");
1099         if (cf_file_read(cs, buffer) < 0) {
1100                 ERROR("Failed to re-read or parse %s", buffer);
1101                 talloc_free(cs);
1102                 return;
1103         }
1104
1105         cc = talloc_zero(cs_cache, cached_config_t);
1106         if (!cc) {
1107                 ERROR("Out of memory");
1108                 return;
1109         }
1110
1111         /*
1112          *      Save the current configuration.  Note that we do NOT
1113          *      free older ones.  We should probably do so at some
1114          *      point.  Doing so will require us to mark which modules
1115          *      are still in use, and which aren't.  Modules that
1116          *      can't be HUPed always use the original configuration.
1117          *      Modules that can be HUPed use one of the newer
1118          *      configurations.
1119          */
1120         cc->created = time(NULL);
1121         cc->cs = talloc_steal(cc, cs);
1122         cc->next = cs_cache;
1123         cs_cache = cc;
1124
1125         INFO("HUP - loading modules");
1126
1127         /*
1128          *      Prefer the new module configuration.
1129          */
1130         modules_hup(cf_section_sub_find(cs, "modules"));
1131
1132         /*
1133          *      Load new servers BEFORE freeing old ones.
1134          */
1135         virtual_servers_load(cs);
1136
1137         virtual_servers_free(cc->created - (main_config.max_request_time * 4));
1138 }