Extend the logging capabilities of auth good/badpass
[freeradius.git] / src / main / mainconfig.c
index 18a25b4..25d642a 100644 (file)
@@ -50,17 +50,42 @@ RCSID("$Id$")
 #      include <syslog.h>
 #endif
 
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
 struct main_config_t mainconfig;
+char *request_log_file = NULL;
+char *debug_condition = NULL;
+
+typedef struct cached_config_t {
+       struct cached_config_t *next;
+       time_t          created;
+       CONF_SECTION    *cs;
+} cached_config_t;
+
+static cached_config_t *cs_cache = NULL;
 
 /*
  *     Temporary local variables for parsing the configuration
  *     file.
  */
-static uid_t server_uid;
+#ifdef HAVE_SETUID
+/*
+ *     Systems that have set/getresuid also have setuid.
+ */
+uid_t server_uid;
 static gid_t server_gid;
 static const char *uid_name = NULL;
 static const char *gid_name = NULL;
+#endif
+static const char *chroot_dir = NULL;
 static int allow_core_dumps = 0;
+static const char *radlog_dest = NULL;
 
 /*
  *     These are not used anywhere else..
@@ -68,7 +93,7 @@ static int allow_core_dumps = 0;
 static const char *localstatedir = NULL;
 static const char *prefix = NULL;
 static char *syslog_facility = NULL;
-static const LRAD_NAME_NUMBER str2fac[] = {
+static const FR_NAME_NUMBER str2fac[] = {
 #ifdef LOG_KERN
        { "kern", LOG_KERN },
 #endif
@@ -133,7 +158,7 @@ static const LRAD_NAME_NUMBER str2fac[] = {
  *  Security configuration for the server.
  */
 static const CONF_PARSER security_config[] = {
-       { "max_attributes",  PW_TYPE_INTEGER, 0, &librad_max_attributes, Stringify(0) },
+       { "max_attributes",  PW_TYPE_INTEGER, 0, &fr_max_attributes, Stringify(0) },
        { "reject_delay",  PW_TYPE_INTEGER, 0, &mainconfig.reject_delay, Stringify(0) },
        { "status_server", PW_TYPE_BOOLEAN, 0, &mainconfig.status_server, "no"},
        { NULL, -1, 0, NULL, NULL }
@@ -141,10 +166,35 @@ static const CONF_PARSER security_config[] = {
 
 
 /*
- *  syslog configuration for the server.
+ *     Logging configuration for the server.
  */
-static const CONF_PARSER log_config[] = {
+static const CONF_PARSER logdest_config[] = {
+       { "destination",  PW_TYPE_STRING_PTR, 0, &radlog_dest, "files" },
        { "syslog_facility",  PW_TYPE_STRING_PTR, 0, &syslog_facility, Stringify(0) },
+
+       { "file", PW_TYPE_STRING_PTR, 0, &mainconfig.log_file, "${logdir}/radius.log" },
+       { "requests", PW_TYPE_STRING_PTR, 0, &request_log_file, NULL },
+       { NULL, -1, 0, NULL, NULL }
+};
+
+
+static const CONF_PARSER serverdest_config[] = {
+       { "log", PW_TYPE_SUBSECTION, 0, NULL, (const void *) logdest_config },
+       { "log_file", PW_TYPE_STRING_PTR, 0, &mainconfig.log_file, NULL },
+       { "log_destination", PW_TYPE_STRING_PTR, 0, &radlog_dest, NULL },
+       { NULL, -1, 0, NULL, NULL }
+};
+
+
+static const CONF_PARSER log_config_nodest[] = {
+       { "stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names,"no" },
+
+       { "auth", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth, "no" },
+       { "auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, "no" },
+       { "auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, "no" },
+       { "msg_badpass", PW_TYPE_STRING_PTR, 0, &mainconfig.auth_badpass_msg, NULL},
+       { "msg_goodpass", PW_TYPE_STRING_PTR, 0, &mainconfig.auth_goodpass_msg, NULL},
+
        { NULL, -1, 0, NULL, NULL }
 };
 
@@ -165,7 +215,7 @@ static const CONF_PARSER server_config[] = {
        { "logdir",             PW_TYPE_STRING_PTR, 0, &radlog_dir,        "${localstatedir}/log"},
        { "libdir",             PW_TYPE_STRING_PTR, 0, &radlib_dir,        "${prefix}/lib"},
        { "radacctdir",         PW_TYPE_STRING_PTR, 0, &radacct_dir,       "${logdir}/radacct" },
-       { "hostname_lookups",   PW_TYPE_BOOLEAN,    0, &librad_dodns,      "no" },
+       { "hostname_lookups",   PW_TYPE_BOOLEAN,    0, &fr_dns_lookups,      "no" },
        { "max_request_time", PW_TYPE_INTEGER, 0, &mainconfig.max_request_time, Stringify(MAX_REQUEST_TIME) },
        { "cleanup_delay", PW_TYPE_INTEGER, 0, &mainconfig.cleanup_delay, Stringify(CLEANUP_DELAY) },
        { "max_requests", PW_TYPE_INTEGER, 0, &mainconfig.max_requests, Stringify(MAX_REQUESTS) },
@@ -173,221 +223,122 @@ static const CONF_PARSER server_config[] = {
        { "delete_blocked_requests", PW_TYPE_INTEGER, 0, &mainconfig.kill_unresponsive_children, Stringify(FALSE) },
 #endif
        { "allow_core_dumps", PW_TYPE_BOOLEAN, 0, &allow_core_dumps, "no" },
-       { "log_stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names,"no" },
 
-       { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
-       { "log_auth", PW_TYPE_BOOLEAN, -1, &mainconfig.log_auth, "no" },
-       { "log_auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, "no" },
-       { "log_auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, "no" },
        { "pidfile", PW_TYPE_STRING_PTR, 0, &mainconfig.pid_file, "${run_dir}/radiusd.pid"},
-       { "user", PW_TYPE_STRING_PTR, 0, &uid_name, NULL},
-       { "group", PW_TYPE_STRING_PTR, 0, &gid_name, NULL},
        { "checkrad", PW_TYPE_STRING_PTR, 0, &mainconfig.checkrad, "${sbindir}/checkrad" },
 
        { "debug_level", PW_TYPE_INTEGER, 0, &mainconfig.debug_level, "0"},
 
+#ifdef WITH_PROXY
        { "proxy_requests", PW_TYPE_BOOLEAN, 0, &mainconfig.proxy_requests, "yes" },
-       { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
-       { "security", PW_TYPE_SUBSECTION, 0, NULL, (const void *) security_config },
-       { NULL, -1, 0, NULL, NULL }
-};
-
-
-#define MAX_ARGV (256)
-/*
- *     Xlat for %{config:section.subsection.attribute}
- */
-static int xlat_config(void *instance, REQUEST *request,
-                      char *fmt, char *out,
-                      size_t outlen,
-                      RADIUS_ESCAPE_STRING func)
-{
-       CONF_SECTION *cs;
-       CONF_PAIR *cp;
-       int i, argc, left;
-       const char *from, *value;
-       char *to;
-       char myfmt[1024];
-       char argv_buf[1024];
-       char *argv[MAX_ARGV];
-
-       request = request;      /* -Wunused */
-       instance = instance;    /* -Wunused */
-
-       cp = NULL;
-       cs = NULL;
+#endif
+       { "log", PW_TYPE_SUBSECTION, 0, NULL, (const void *) log_config_nodest },
 
        /*
-        *      Split the string into argv's BEFORE doing radius_xlat...
-        *      Copied from exec.c
+        *      People with old configs will have these.  They are listed
+        *      AFTER the "log" section, so if they exist in radiusd.conf,
+        *      it will prefer "log_foo = bar" to "log { foo = bar }".
+        *      They're listed with default values of NULL, so that if they
+        *      DON'T exist in radiusd.conf, then the previously parsed
+        *      values for "log { foo = bar}" will be used.
         */
-       from = fmt;
-       to = myfmt;
-       argc = 0;
-       while (*from) {
-               int flag, length;
+       { "log_auth", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth, NULL },
+       { "log_auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, NULL },
+       { "log_auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, NULL },
+       { "log_stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names, NULL },
 
-               flag = 0;
-               argv[argc] = to;
-               argc++;
+       {  "security", PW_TYPE_SUBSECTION, 0, NULL, (const void *) security_config },
 
-               if (argc >= (MAX_ARGV - 1)) break;
-
-               /*
-                *      Copy the argv over to our buffer.
-                */
-               while (*from) {
-                       if (to >= myfmt + sizeof(myfmt) - 1) {
-                               return 0; /* no error msg */
-                       }
-
-                       switch (*from) {
-                       case '%':
-                               if (from[1] == '{') {
-                                       *(to++) = *(from++);
-
-                                       length = rad_copy_variable(to, from);
-                                       if (length < 0) {
-                                               return -1;
-                                       }
-                                       from += length;
-                                       to += length;
-                               } else { /* FIXME: catch %%{ ? */
-                                       *(to++) = *(from++);
-                               }
-                               break;
-
-                       case '[':
-                               if (flag != 0) {
-                                       radlog(L_ERR, "config: Unexpected nested '[' in \"%s\"", fmt);
-                                       return 0;
-                               }
-                               flag++;
-                               *(to++) = *(from++);
-                               break;
-
-                       case ']':
-                               if (flag == 0) {
-                                       radlog(L_ERR, "config: Unbalanced ']' in \"%s\"", fmt);
-                                       return 0;
-                               }
-                               if (from[1] != '.') {
-                                       radlog(L_ERR, "config: Unexpected text after ']' in \"%s\"", fmt);
-                                       return 0;
-                               }
-
-                               flag--;
-                               *(to++) = *(from++);
-                               break;
-
-                       case '.':
-                               if (flag == 0) break;
-                               /* FALL-THROUGH */
-
-                       default:
-                               *(to++) = *(from++);
-                               break;
-                       }
-
-                       if ((*from == '.') && (flag == 0)) {
-                               from++;
-                               break;
-                       }
-               } /* end of string, or found a period */
+       { NULL, -1, 0, NULL, NULL }
+};
 
-               if (flag != 0) {
-                       radlog(L_ERR, "config: Unbalanced '[' in \"%s\"", fmt);
-                       return 0;
-               }
+#define MAX_ARGV (256)
 
-               *(to++) = '\0'; /* terminate the string. */
-       }
 
-       /*
-        *      Expand each string, as appropriate
-        */
-       to = argv_buf;
-       left = sizeof(argv_buf);
-       for (i = 0; i < argc; i++) {
-               int sublen;
+static size_t config_escape_func(char *out, size_t outlen, const char *in)
+{
+       size_t len = 0;
+       static const char *disallowed = "%{}\\'\"`";
 
+       while (in[0]) {
                /*
-                *      Don't touch argv's which won't be translated.
+                *      Non-printable characters get replaced with their
+                *      mime-encoded equivalents.
                 */
-               if (strchr(argv[i], '%') == NULL) continue;
-
-               sublen = radius_xlat(to, left - 1, argv[i], request, NULL);
-               if (sublen <= 0) {
-                       /*
-                        *      Fail to be backwards compatible.
-                        *
-                        *      It's yucky, but it won't break anything,
-                        *      and it won't cause security problems.
-                        */
-                       sublen = 0;
+               if ((in[0] < 32)) {
+                       if (outlen <= 3) break;
+
+                       snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
+                       in++;
+                       out += 3;
+                       outlen -= 3;
+                       len += 3;
+                       continue;
+
+               } else if (strchr(disallowed, *in) != NULL) {
+                       if (outlen <= 2) break;
+
+                       out[0] = '\\';
+                       out[1] = *in;
+                       in++;
+                       out += 2;
+                       outlen -= 2;
+                       len += 2;
+                       continue;
                }
 
-               argv[i] = to;
-               to += sublen;
-               *(to++) = '\0';
-               left -= sublen;
-               left--;
-
-               if (left <= 0) {
-                       return 0;
+               /*
+                *      Only one byte left.
+                */
+               if (outlen <= 1) {
+                       break;
                }
-       }
-       argv[argc] = NULL;
-
-       cs = request->root->config;
-
-       /*
-        *      Root through section & subsection references.
-        *      The last entry of argv MUST be the CONF_PAIR.
-        */
-       for (i = 0; i < argc - 1; i++) {
-               char *name2 = NULL;
-               CONF_SECTION *subcs;
 
                /*
-                *      FIXME: What about RADIUS attributes containing '['?
+                *      Allowed character.
                 */
-               name2 = strchr(argv[i], '[');
-               if (name2) {
-                       char *p = strchr(name2, ']');
-                       rad_assert(p != NULL);
-                       rad_assert(p[1] =='\0');
-                       *p = '\0';
-                       *name2 = '\0';
-                       name2++;
-               }
+               *out = *in;
+               out++;
+               in++;
+               outlen--;
+               len++;
+       }
+       *out = '\0';
+       return len;
+}
 
-               if (name2) {
-                       subcs = cf_section_sub_find_name2(cs, argv[i],
-                                                         name2);
-                       if (!subcs) {
-                         radlog(L_ERR, "config: section \"%s %s {}\" not found while dereferencing \"%s\"", argv[i], name2, fmt);
-                         return 0;
-                       }
-               } else {
-                       subcs = cf_section_sub_find(cs, argv[i]);
-                       if (!subcs) {
-                         radlog(L_ERR, "config: section \"%s {}\" not found while dereferencing \"%s\"", argv[i], fmt);
-                         return 0;
-                       }
-               }
-               cs = subcs;
-       } /* until argc - 1 */
+/*
+ *     Xlat for %{config:section.subsection.attribute}
+ */
+static size_t xlat_config(void *instance, REQUEST *request,
+                         char *fmt, char *out,
+                         size_t outlen,
+                         RADIUS_ESCAPE_STRING func)
+{
+       const char *value;
+       CONF_PAIR *cp;
+       CONF_ITEM *ci;
+       char buffer[1024];
+
+       request = request;      /* -Wunused */
+       instance = instance;    /* -Wunused */
 
        /*
-        *      This can now have embedded periods in it.
+        *      Expand it safely.
         */
-       cp = cf_pair_find(cs, argv[argc - 1]);
-       if (!cp) {
-               radlog(L_ERR, "config: item \"%s\" not found while dereferencing \"%s\"", argv[argc], fmt);
+       if (!radius_xlat(buffer, sizeof(buffer), fmt, request, config_escape_func)) {
+               return 0;
+       }
+
+       ci = cf_reference_item(request->root->config,
+                              request->root->config, buffer);
+       if (!ci || !cf_item_is_pair(ci)) {
+               *out = '\0';
                return 0;
        }
 
+       cp = cf_itemtopair(ci);
+
        /*
         *  Ensure that we only copy what's necessary.
         *
@@ -407,7 +358,7 @@ static int xlat_config(void *instance, REQUEST *request,
 /*
  *     Xlat for %{client:foo}
  */
-static int xlat_client(UNUSED void *instance, REQUEST *request,
+static size_t xlat_client(UNUSED void *instance, REQUEST *request,
                       char *fmt, char *out,
                       size_t outlen,
                       UNUSED RADIUS_ESCAPE_STRING func)
@@ -444,7 +395,7 @@ static int r_mkdir(const char *part)
        if (stat(part, &st) == 0)
                return(0);
 
-       ptr = strrchr(part, '/');
+       ptr = strrchr(part, FR_DIR_SEP);
 
        if (ptr == part)
                return(0);
@@ -462,79 +413,133 @@ static int r_mkdir(const char *part)
        return(0);
 }
 
-/*
- *     Checks if the log directory is writeable by a particular user.
- */
-static int radlogdir_iswritable(const char *effectiveuser)
+
+#ifdef HAVE_SETUID
+int did_setuid = FALSE;
+
+#if defined(HAVE_SETRESUID) && defined (HAVE_GETRESUID)
+void fr_suid_up(void)
 {
-#ifdef HAVE_GETPWNAM
-       struct passwd *pwent;
-#endif
+       uid_t ruid, euid, suid;
+       
+       if (getresuid(&ruid, &euid, &suid) < 0) {
+               radlog(L_ERR, "Failed getting saved UID's");
+               _exit(1);
+       }
 
-       if (!radlog_dir || radlog_dir[0] != '/')
-               return(0);
+       if (setresuid(-1, suid, -1) < 0) {
+               radlog(L_ERR, "Failed switching to privileged user");
+               _exit(1);
+       }
 
-       if (r_mkdir(radlog_dir) != 0)
-               return(1);
+       if (geteuid() != suid) {
+               radlog(L_ERR, "Switched to unknown UID");
+               _exit(1);
+       }
+}
 
-       /* FIXME: do we have this function? */
-       if (strstr(radlog_dir, "radius") == NULL)
-               return(0);
+void fr_suid_down(void)
+{
+       if (!did_setuid) return;
 
-       /* we have a logdir that mentions 'radius', so it's probably
-        * safe to chown the immediate directory to be owned by the normal
-        * process owner. we gotta do it before we give up root.  -chad
-        */
+       if (setresuid(-1, server_uid, geteuid()) < 0) {
+               fprintf(stderr, "%s: Failed switching to uid %s: %s\n",
+                       progname, uid_name, strerror(errno));
+               _exit(1);
+       }
+               
+       if (geteuid() != server_uid) {
+               fprintf(stderr, "%s: Failed switching uid: UID is incorrect\n",
+                       progname);
+               _exit(1);
+       }
+}
 
-       if (!effectiveuser) {
-               return 1;
+void fr_suid_down_permanent(void)
+{
+       uid_t ruid, euid, suid;
+
+       if (!did_setuid) return;
+
+       if (getresuid(&ruid, &euid, &suid) < 0) {
+               radlog(L_ERR, "Failed getting saved uid's");
+               _exit(1);
        }
 
-#ifdef HAVE_GETPWNAM
-       pwent = getpwnam(effectiveuser);
+       if (setresuid(server_uid, server_uid, server_uid) < 0) {
+               radlog(L_ERR, "Failed in permanent switch to uid %s: %s",
+                      uid_name, strerror(errno));
+               _exit(1);
+       }
 
-       if (pwent == NULL) /* uh oh! */
-               return(1);
+       if (geteuid() != server_uid) {
+               radlog(L_ERR, "Switched to unknown uid");
+               _exit(1);
+       }
 
-       if (chown(radlog_dir, pwent->pw_uid, -1) != 0)
-               return(1);
-#endif
 
-       return(0);
+       if (getresuid(&ruid, &euid, &suid) < 0) {
+               radlog(L_ERR, "Failed getting saved uid's: %s",
+                      strerror(errno));
+               _exit(1);
+       }
+}
+#else
+/*
+ *     Much less secure...
+ */
+void fr_suid_up(void)
+{
 }
+void fr_suid_down(void)
+{
+       if (!uid_name) return;
 
+       if (setuid(server_uid) < 0) {
+               fprintf(stderr, "%s: Failed switching to uid %s: %s\n",
+                       progname, uid_name, strerror(errno));
+               _exit(1);
+       }
+}
+void fr_suid_down_permanent(void)
+{
+}
+#endif
 
 /*
+ *  Do chroot, if requested.
+ *
  *  Switch UID and GID to what is specified in the config file
  */
-static int switch_users(void)
+static int switch_users(CONF_SECTION *cs)
 {
-       int did_setuid = FALSE;
+       CONF_PAIR *cp;
 
 #ifdef HAVE_SYS_RESOURCE_H
        struct rlimit core_limits;
 #endif
 
+       /*
+        *      Don't do chroot/setuid/setgid if we're in debugging
+        *      as non-root.
+        */
+       if (debug_flag && (getuid() != 0)) return 1;
+
 #ifdef HAVE_GRP_H
        /*  Set GID.  */
-       if (gid_name != NULL) {
+       cp = cf_pair_find(cs, "group");
+       if (cp) gid_name = cf_pair_value(cp);
+       if (gid_name) {
                struct group *gr;
 
+               DEBUG2("group = %s", gid_name);
                gr = getgrnam(gid_name);
                if (gr == NULL) {
-                       if (errno == ENOMEM) {
-                               radlog(L_ERR, "Cannot switch to Group %s: out of memory", gid_name);
-                       } else {
-                               radlog(L_ERR, "Cannot switch group; %s doesn't exist", gid_name);
-                       }
+                       fprintf(stderr, "%s: Cannot get ID for group %s: %s\n",
+                               progname, gid_name, strerror(errno));
                        return 0;
                }
                server_gid = gr->gr_gid;
-               if (setgid(server_gid) < 0) {
-                       radlog(L_ERR, "Failed setting Group to %s: %s",
-                              gid_name, strerror(errno));
-                       return 0;
-               }
        } else {
                server_gid = getgid();
        }
@@ -542,39 +547,102 @@ static int switch_users(void)
 
 #ifdef HAVE_PWD_H
        /*  Set UID.  */
-       if (uid_name != NULL) {
+       cp = cf_pair_find(cs, "user");
+       if (cp) uid_name = cf_pair_value(cp);
+       if (uid_name) {
                struct passwd *pw;
-
+               
+               DEBUG2("user = %s", uid_name);
                pw = getpwnam(uid_name);
                if (pw == NULL) {
-                       if (errno == ENOMEM) {
-                               radlog(L_ERR, "Cannot switch to User %s: out of memory", uid_name);
-                       } else {
-                               radlog(L_ERR, "Cannot switch user; %s doesn't exist", uid_name);
-                       }
+                       fprintf(stderr, "%s: Cannot get passwd entry for user %s: %s\n",
+                               progname, uid_name, strerror(errno));
                        return 0;
                }
                server_uid = pw->pw_uid;
 #ifdef HAVE_INITGROUPS
                if (initgroups(uid_name, server_gid) < 0) {
-                       if (errno != EPERM) {
-                               radlog(L_ERR, "Failed setting supplementary groups for User %s: %s", uid_name, strerror(errno));
-                               return 0;
-                       }
+                       fprintf(stderr, "%s: Cannot initialize supplementary group list for user %s: %s\n",
+                               progname, uid_name, strerror(errno));
+                       return 0;
                }
 #endif
-               if (setuid(server_uid) < 0) {
-                       radlog(L_ERR, "Failed setting User to %s: %s", uid_name, strerror(errno));
+       } else {
+               server_uid = getuid();
+       }
+#endif
+
+       cp = cf_pair_find(cs, "chroot");
+       if (cp) chroot_dir = cf_pair_value(cp);
+       if (chroot_dir) {
+               DEBUG2("chroot = %s", chroot_dir);
+               if (chroot(chroot_dir) < 0) {
+                       fprintf(stderr, "%s: Failed to perform chroot %s: %s",
+                               progname, chroot_dir, strerror(errno));
                        return 0;
                }
 
                /*
+                *      Note that we leave chdir alone.  It may be
+                *      OUTSIDE of the root.  This allows us to read
+                *      the configuration from "-d ./etc/raddb", with
+                *      the chroot as "./chroot/" for example.  After
+                *      the server has been loaded, it does a "cd
+                *      ${logdir}" below, so that core files (if any)
+                *      go to a logging directory.
+                *
+                *      This also allows the configuration of the
+                *      server to be outside of the chroot.  If the
+                *      server is statically linked, then the only
+                *      things needed inside of the chroot are the
+                *      logging directories.
+                */
+               radlog(L_INFO, "performing chroot to %s\n", chroot_dir);
+       }
+
+#ifdef HAVE_GRP_H
+       /*  Set GID.  */
+       if (gid_name && (setgid(server_gid) < 0)) {
+               fprintf(stderr, "%s: Failed setting group to %s: %s",
+                       progname, gid_name, strerror(errno));
+               return 0;
+       }
+#endif
+
+#ifdef HAVE_PWD_H
+       if (uid_name) {
+               fr_suid_down();
+
+               /*
                 *      Now core dumps are disabled on most secure systems.
                 */
+               
                did_setuid = TRUE;
        }
 #endif
 
+       /*
+        *      Double check that we can write to the log directory.
+        *
+        *      If we can't, don't start, as we can't log any errors!
+        */
+       if ((mainconfig.radlog_dest == RADLOG_FILES) &&
+           (mainconfig.log_file != NULL)) {
+               int fd = open(mainconfig.log_file,
+                             O_WRONLY | O_APPEND | O_CREAT, 0640);
+               if (fd < 0) {
+                       fprintf(stderr, "%s: Cannot write to log file %s: %s\n",
+                               progname, mainconfig.log_file, strerror(errno));
+                       return 0;
+               }
+               close(fd);
+
+               /*
+                *      After this it's safe to call radlog(), as it's going
+                *      to the right place.
+                */
+       }
+
 #ifdef HAVE_SYS_RESOURCE_H
        /*  Get the current maximum for core files.  */
        if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
@@ -634,6 +702,8 @@ static int switch_users(void)
                        return 0;
                }
 #endif
+
+               radlog(L_INFO, "Core dumps are enabled.");
        }
        /*
         *      Else we're debugging (so core dumps are enabled)
@@ -643,23 +713,12 @@ static int switch_users(void)
         *         core dump capabilities inherited from the parent shell.
         */
 
-#if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
-       /*
-        *      We've probably written to the log file already as
-        *      root.root, so if we have switched users, we've got to
-        *      update the ownership of the file.
-        */
-       if ((debug_flag == 0) &&
-           (mainconfig.radlog_dest == RADLOG_FILES) &&
-           (mainconfig.log_file != NULL)) {
-               chown(mainconfig.log_file, server_uid, server_gid);
-       }
-#endif
        return 1;
 }
+#endif
 
 
-static const LRAD_NAME_NUMBER str2dest[] = {
+static const FR_NAME_NUMBER str2dest[] = {
        { "null", RADLOG_NULL },
        { "files", RADLOG_FILES },
        { "syslog", RADLOG_SYSLOG },
@@ -676,10 +735,17 @@ static const LRAD_NAME_NUMBER str2dest[] = {
  */
 int read_mainconfig(int reload)
 {
-       static int old_debug_level = -1;
-       char buffer[1024];
-       CONF_SECTION *cs, *templates;
+       const char *p = NULL;
+       CONF_PAIR *cp;
+       CONF_SECTION *cs;
        struct stat statbuf;
+       cached_config_t *cc;
+       char buffer[1024];
+
+       if (reload != 0) {
+               radlog(L_ERR, "Reload is not implemented");
+               return -1;
+       }
 
        if (stat(radius_dir, &statbuf) < 0) {
                radlog(L_ERR, "Errors reading %s: %s",
@@ -703,138 +769,77 @@ int read_mainconfig(int reload)
        }
 #endif
 
-       if (!reload) {
-               radlog(L_INFO, "Starting - reading configuration files ...");
-       } else {
-               radlog(L_INFO, "Reloading - reading configuration files...");
-       }
+       radlog(L_INFO, "Starting - reading configuration files ...");
 
        /* Read the configuration file */
-       snprintf(buffer, sizeof(buffer), "%.200s/%.50s",
-                radius_dir, mainconfig.radiusd_conf);
+       snprintf(buffer, sizeof(buffer), "%.200s/%.50s.conf",
+                radius_dir, mainconfig.name);
        if ((cs = cf_file_read(buffer)) == NULL) {
                radlog(L_ERR, "Errors reading %s", buffer);
                return -1;
        }
 
        /*
-        *      Add templates to each kind of subsection.
+        *      If there was no log destination set on the command line,
+        *      set it now.
         */
-       templates = cf_section_sub_find(cs, "templates");
-       if (templates) {
-               CONF_SECTION *ts, *mycs;
-
-               /*
-                *      Loop over the templates, adding them to the
-                *      sections in the main configuration file.
-                */
-               for (ts = cf_subsection_find_next(templates, NULL, NULL);
-                    ts != NULL;
-                    ts = cf_subsection_find_next(templates, ts, NULL)) {
-                       const char *name1 = cf_section_name1(ts);
-
-                       /*
-                        *      Loop over sections in the main config
-                        *      file, adding templats.
-                        */
-                       for (mycs = cf_subsection_find_next(cs, NULL, name1);
-                            mycs != NULL;
-                            mycs = cf_subsection_find_next(cs, mycs, name1)) {
-                               const char *value;
-
-                               value = cf_section_value_find(mycs, "template");
-                               if (value) {
-                                       CONF_SECTION *tts;
-
-                                       tts = cf_section_sub_find_name2(templates,
-                                                                       name1,
-                                                                       value);
-                                       if (!tts) {
-                                               radlog(L_ERR, "%s[%d]: Section refers to non-existent template \"%s\"",
-                                                      cf_section_filename(mycs), cf_section_lineno(mycs), value);
-                                               return -1;
-                                       }
-                                       cf_section_template(mycs, tts);
-                               } else {
-                                       cf_section_template(mycs, ts);
-                               }
-                       }
+       if (mainconfig.radlog_dest == RADLOG_NULL) {
+               if (cf_section_parse(cs, NULL, serverdest_config) < 0) {
+                       fprintf(stderr, "radiusd: Error: Failed to parse log{} section.\n");
+                       cf_section_free(&cs);
+                       return -1;
                }
-       }
-
-       /*
-        *      Debug flag 1 MAY go to files.
-        *      Debug flag 2 ALWAYS goes to stdout
-        *
-        *      Parse the log_destination before printing anything else.
-        *      All messages before this MUST be errors, which log.c
-        *      will print to stderr, since log_file is NULL, too.
-        */
-       if (debug_flag < 2) {
-               int rcode;
-               char *radlog_dest = NULL;
-
-               rcode = cf_item_parse(cs, "log_destination",
-                                     PW_TYPE_STRING_PTR, &radlog_dest,
-                                     "files");
-               if (rcode < 0) return -1;
-
-               mainconfig.radlog_dest = lrad_str2int(str2dest, radlog_dest, RADLOG_NUM_DEST);
+               
+               if (!radlog_dest) {
+                       fprintf(stderr, "radiusd: Error: No log destination specified.\n");
+                       cf_section_free(&cs);
+                       return -1;
+               }
+               
+               mainconfig.radlog_dest = fr_str2int(str2dest, radlog_dest,
+                                                   RADLOG_NUM_DEST);
                if (mainconfig.radlog_dest == RADLOG_NUM_DEST) {
                        fprintf(stderr, "radiusd: Error: Unknown log_destination %s\n",
                                radlog_dest);
-                       free(radlog_dest);
                        cf_section_free(&cs);
                        return -1;
                }
-
+               
                if (mainconfig.radlog_dest == RADLOG_SYSLOG) {
-                       static const CONF_PARSER syslog_config[] = {
-                               { "log", PW_TYPE_SUBSECTION, 0, NULL,  (const void *) log_config},
-                               { NULL, -1, 0, NULL, NULL }
-                       };
-                       cf_section_parse(cs, NULL, syslog_config);
-
                        /*
-                        *      Make sure syslog_facility isn't NULL before using it
+                        *      Make sure syslog_facility isn't NULL
+                        *      before using it
                         */
                        if (!syslog_facility) {
-                               fprintf(stderr, "radiusd: Error: Unknown syslog chosen but no facility spedified\n");
-                               free(radlog_dest);
+                               fprintf(stderr, "radiusd: Error: Syslog chosen but no facility was specified\n");
                                cf_section_free(&cs);
                                return -1;
                        }
-                       mainconfig.syslog_facility = lrad_str2int(str2fac, syslog_facility, -1);
+                       mainconfig.syslog_facility = fr_str2int(str2fac, syslog_facility, -1);
                        if (mainconfig.syslog_facility < 0) {
                                fprintf(stderr, "radiusd: Error: Unknown syslog_facility %s\n",
                                        syslog_facility);
-                               free(radlog_dest);
-                               free(syslog_facility);
                                cf_section_free(&cs);
                                return -1;
                        }
                }
-
-               if (mainconfig.radlog_dest == RADLOG_FILES) {
-                       static const CONF_PARSER file_config[] = {
-                               { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
-                               { NULL, -1, 0, NULL, NULL }
-                       };
-
-                       cf_section_parse(cs, NULL, file_config);
-               }
-
-               free(radlog_dest);
-       } else {
-               mainconfig.radlog_dest = RADLOG_STDOUT;
-               mainconfig.radlog_fd = STDOUT_FILENO;
        }
 
+#ifdef HAVE_SETUID
+       /*
+        *      Switch users as early as possible.
+        */
+       if (!switch_users(cs)) exit(1);
+#endif
+
        /* Initialize the dictionary */
-       DEBUG2("including dictionary file %s/%s", radius_dir, RADIUS_DICTIONARY);
-       if (dict_init(radius_dir, RADIUS_DICTIONARY) != 0) {
+       cp = cf_pair_find(cs, "dictionary");
+       if (cp) p = cf_pair_value(cp);
+       if (!p) p = radius_dir;
+       DEBUG2("including dictionary file %s/%s", p, RADIUS_DICTIONARY);
+       if (dict_init(p, RADIUS_DICTIONARY) != 0) {
                radlog(L_ERR, "Errors reading dictionary: %s",
-                               librad_errstr);
+                               fr_strerror());
                return -1;
        }
 
@@ -844,24 +849,6 @@ int read_mainconfig(int reload)
         */
        cf_section_parse(cs, NULL, server_config);
 
-#if 0
-       /*
-        *      Merge the old with the new.
-        */
-       if (reload) {
-               CONF_SECTION *newcs;
-
-               newcs = cf_section_sub_find(cs, "modules");
-               oldcs = cf_section_sub_find(mainconfig.config, "modules");
-               if (newcs && oldcs) {
-                       if (!cf_section_migrate(newcs, oldcs)) {
-                               radlog(L_ERR, "Fatal error migrating configuration data");
-                               return -1;
-                       }
-               }
-       }
-#endif
-
        /*
         *      Free the old configuration items, and replace them
         *      with the new ones.
@@ -872,12 +859,16 @@ int read_mainconfig(int reload)
        cf_section_free(&mainconfig.config);
        mainconfig.config = cs;
 
-       DEBUG2("radiusd: #### Loading Realms and Home Servers ####");
-
+       DEBUG2("%s: #### Loading Realms and Home Servers ####", mainconfig.name);
        if (!realms_init(cs)) {
                return -1;
        }
 
+       DEBUG2("%s: #### Loading Clients ####", mainconfig.name);
+       if (!clients_parse_section(cs)) {
+               return -1;
+       }
+
        /*
         *  Register the %{config:section.subsection} xlat function.
         */
@@ -885,25 +876,14 @@ int read_mainconfig(int reload)
        xlat_register("client", xlat_client, NULL);
 
        /*
-        *      Reload: change debug flag if it's changed in the
-        *      configuration file.
+        *      Starting the server, WITHOUT "-x" on the
+        *      command-line: use whatever is in the config
+        *      file.
         */
-       if (reload) {
-               if (mainconfig.debug_level != old_debug_level) {
-                       debug_flag = mainconfig.debug_level;
-               }
-
-       } else if (debug_flag == 0) {
-
-               /*
-                *      Starting the server, WITHOUT "-x" on the
-                *      command-line: use whatever's in the config
-                *      file.
-                */
+       if (debug_flag == 0) {
                debug_flag = mainconfig.debug_level;
        }
-       librad_debug = debug_flag;
-       old_debug_level = mainconfig.debug_level;
+       fr_debug_flag = debug_flag;
 
        /*
         *  Go update our behaviour, based on the configuration
@@ -911,23 +891,6 @@ int read_mainconfig(int reload)
         */
 
        /*
-        *      The first time around, ensure that we can write to the
-        *      log directory.
-        */
-       if (!reload) {
-               /*
-                *      We need root to do mkdir() and chown(), so we
-                *      do this before giving up root.
-                */
-               radlogdir_iswritable(uid_name);
-       }
-
-       /*
-        *      We should really switch users earlier in the process.
-        */
-       if (!switch_users()) exit(1);
-
-       /*
         *      Sanity check the configuration for internal
         *      consistency.
         */
@@ -938,9 +901,24 @@ int read_mainconfig(int reload)
 
        /*  Reload the modules.  */
        if (setup_modules(reload, mainconfig.config) < 0) {
-               radlog(L_ERR, "Errors initializing modules");
                return -1;
        }
+
+       if (chroot_dir) {
+               if (chdir(radlog_dir) < 0) {
+                       radlog(L_ERR, "Failed to 'chdir %s' after chroot: %s",
+                              radlog_dir, strerror(errno));
+                       return -1;
+               }
+       }
+
+       cc = rad_malloc(sizeof(*cc));
+       memset(cc, 0, sizeof(*cc));
+
+       cc->cs = cs;
+       rad_assert(cs_cache == NULL);
+       cs_cache = cc;
+
        return 0;
 }
 
@@ -949,17 +927,70 @@ int read_mainconfig(int reload)
  */
 int free_mainconfig(void)
 {
+       cached_config_t *cc, *next;
+
+       virtual_servers_free(0);
+
+       /*
+        *      Free all of the cached configurations.
+        */
+       for (cc = cs_cache; cc != NULL; cc = next) {
+               next = cc->next;
+               cf_section_free(&cc->cs);
+               free(cc);
+       }
+
        /*
         *      Clean up the configuration data
         *      structures.
         */
-       cf_section_free(&mainconfig.config);
-       free(mainconfig.radiusd_conf);
        realms_free();
        listen_free(&mainconfig.listen);
-       xlat_free();
        dict_free();
-       lt_dlexit();
 
        return 0;
 }
+
+void hup_mainconfig(void)
+{
+       cached_config_t *cc;
+       CONF_SECTION *cs;
+       char buffer[1024];
+
+       /* Read the configuration file */
+       snprintf(buffer, sizeof(buffer), "%.200s/%.50s.conf",
+                radius_dir, mainconfig.name);
+       if ((cs = cf_file_read(buffer)) == NULL) {
+               radlog(L_ERR, "Failed to re-read %s", buffer);
+               return;
+       }
+
+       cc = rad_malloc(sizeof(*cc));
+       memset(cc, 0, sizeof(*cc));
+
+       /*
+        *      Save the current configuration.  Note that we do NOT
+        *      free older ones.  We should probably do so at some
+        *      point.  Doing so will require us to mark which modules
+        *      are still in use, and which aren't.  Modules that
+        *      can't be HUPed always use the original configuration.
+        *      Modules that can be HUPed use one of the newer
+        *      configurations.
+        */
+       cc->created = time(NULL);
+       cc->cs = cs;
+       cc->next = cs_cache;
+       cs_cache = cc;
+
+       /*
+        *      Prefer the new module configuration.
+        */
+       module_hup(cf_section_sub_find(cs, "modules"));
+
+       /*
+        *      Load new servers BEFORE freeing old ones.
+        */
+       virtual_servers_load(cs);
+
+       virtual_servers_free(cc->created - mainconfig.max_request_time * 4);
+}