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