Revert "Delete control socket when the server exits."
[freeradius.git] / src / main / mainconfig.c
index 6f8dad3..7a7bf4b 100644 (file)
@@ -42,7 +42,7 @@ RCSID("$Id$")
 #include <grp.h>
 #endif
 
-#ifdef HAVE_SYS_PRTCL_H
+#ifdef HAVE_SYS_PRCTL_H
 #include <sys/prctl.h>
 #endif
 
@@ -50,14 +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;
-static gid_t server_gid;
+#ifdef HAVE_SETUID
+/*
+ *     Systems that have set/getresuid also have setuid.
+ */
+static uid_t server_uid = 0;
+static gid_t server_gid = 0;
+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..
@@ -65,7 +93,7 @@ static gid_t server_gid;
 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
@@ -130,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 }
@@ -138,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 }
 };
 
@@ -162,229 +215,141 @@ 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) },
 #ifdef DELETE_BLOCKED_REQUESTS
        { "delete_blocked_requests", PW_TYPE_INTEGER, 0, &mainconfig.kill_unresponsive_children, Stringify(FALSE) },
 #endif
-       { "allow_core_dumps", PW_TYPE_BOOLEAN, 0, &mainconfig.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, &mainconfig.uid_name, NULL},
-       { "group", PW_TYPE_STRING_PTR, 0, &mainconfig.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;
+       { NULL, -1, 0, NULL, NULL }
+};
 
-               /*
-                *      Copy the argv over to our buffer.
-                */
-               while (*from) {
-                       if (to >= myfmt + sizeof(myfmt) - 1) {
-                               return 0; /* no error msg */
-                       }
+static const CONF_PARSER bootstrap_config[] = {
+#ifdef HAVE_SETUID
+       { "user",  PW_TYPE_STRING_PTR, 0, &uid_name, NULL },
+       { "group",  PW_TYPE_STRING_PTR, 0, &gid_name, NULL },
+#endif
+       { "chroot",  PW_TYPE_STRING_PTR, 0, &chroot_dir, NULL },
+       { "allow_core_dumps", PW_TYPE_BOOLEAN, 0, &allow_core_dumps, "no" },
 
-                       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;
-                       }
+       { NULL, -1, 0, NULL, NULL }
+};
 
-                       if ((*from == '.') && (flag == 0)) {
-                               from++;
-                               break;
-                       }
-               } /* end of string, or found a period */
 
-               if (flag != 0) {
-                       radlog(L_ERR, "config: Unbalanced '[' in \"%s\"", fmt);
-                       return 0;
-               }
 
-               *(to++) = '\0'; /* terminate the string. */
-       }
+#define MAX_ARGV (256)
 
-       /*
-        *      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.
         *
@@ -404,7 +369,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)
@@ -441,7 +406,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);
@@ -459,77 +424,197 @@ 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_GETPWNAM
-       struct passwd *pwent;
+#ifdef HAVE_SYS_RESOURCE_H
+static struct rlimit core_limits;
 #endif
 
-       if (!radlog_dir || radlog_dir[0] != '/')
-               return(0);
+static void fr_set_dumpable(void)
+{
+       /*
+        *      If configured, turn core dumps off.
+        */
+       if (!allow_core_dumps) {
+#ifdef HAVE_SYS_RESOURCE_H
+               struct rlimit no_core;
 
-       if (r_mkdir(radlog_dir) != 0)
-               return(1);
 
-       /* FIXME: do we have this function? */
-       if (strstr(radlog_dir, "radius") == NULL)
-               return(0);
+               no_core.rlim_cur = 0;
+               no_core.rlim_max = 0;
+               
+               if (setrlimit(RLIMIT_CORE, &no_core) < 0) {
+                       radlog(L_ERR, "Failed disabling core dumps: %s",
+                              strerror(errno));
+               }
+#endif
+               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
+       /*
+        *      Set or re-set the dumpable flag.
         */
+#ifdef HAVE_SYS_PRCTL_H
+#ifdef PR_SET_DUMPABLE
+       if (prctl(PR_SET_DUMPABLE, 1) < 0) {
+               radlog(L_ERR,"Cannot re-enable core dumps: prctl(PR_SET_DUMPABLE) failed: '%s'",
+                      strerror(errno));
+       }
+#endif
+#endif
 
-       if (!effectiveuser) {
-               return 1;
+       /*
+        *      Reset the core dump limits to their original value.
+        */
+#ifdef HAVE_SYS_RESOURCE_H
+       if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
+               radlog(L_ERR, "Cannot update core dump limit: %s",
+                      strerror(errno));
        }
+#endif
+}
 
-#ifdef HAVE_GETPWNAM
-       pwent = getpwnam(effectiveuser);
+#ifdef HAVE_SETUID
+static int doing_setuid = FALSE;
 
-       if (pwent == NULL) /* uh oh! */
-               return(1);
+#if defined(HAVE_SETRESUID) && defined (HAVE_GETRESUID)
+void fr_suid_up(void)
+{
+       uid_t ruid, euid, suid;
+       
+       if (getresuid(&ruid, &euid, &suid) < 0) {
+               radlog(L_ERR, "Failed getting saved UID's");
+               _exit(1);
+       }
 
-       if (chown(radlog_dir, pwent->pw_uid, -1) != 0)
-               return(1);
-#endif
+       if (setresuid(-1, suid, -1) < 0) {
+               radlog(L_ERR, "Failed switching to privileged user");
+               _exit(1);
+       }
 
-       return(0);
+       if (geteuid() != suid) {
+               radlog(L_ERR, "Switched to unknown UID");
+               _exit(1);
+       }
 }
 
+void fr_suid_down(void)
+{
+       if (!doing_setuid) return;
+
+       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);
+       }
+
+       fr_set_dumpable();
+}
+
+void fr_suid_down_permanent(void)
+{
+       if (!doing_setuid) return;
+
+       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 (geteuid() != server_uid) {
+               radlog(L_ERR, "Switched to unknown uid");
+               _exit(1);
+       }
+
+       fr_set_dumpable();
+}
+#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);
+       }
+
+       fr_set_dumpable();
+}
+void fr_suid_down_permanent(void)
+{
+       fr_set_dumpable();
+}
+#endif /* HAVE_SETRESUID && HAVE_GETRESUID */
+#else  /* HAVE_SETUID */
+void fr_suid_up(void)
+{
+}
+void fr_suid_down(void)
+{
+       fr_set_dumpable();
+}
+void fr_suid_down_permanent(void)
+{
+       fr_set_dumpable();
+}
+#endif /* HAVE_SETUID */
+#ifdef HAVE_SETUID
 
 /*
+ *  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)
 {
 #ifdef HAVE_SYS_RESOURCE_H
-       struct rlimit core_limits;
+       /*
+        *      Get the current maximum for core files.  Do this
+        *      before anything else so as to ensure it's properly
+        *      initialized.
+        */
+       if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
+               radlog(L_ERR, "Failed to get current core limit:  %s", strerror(errno));
+               return 0;
+       }
 #endif
 
+       /*
+        *      Don't do chroot/setuid/setgid if we're in debugging
+        *      as non-root.
+        */
+       if (debug_flag && (getuid() != 0)) return 1;
+
+       if (cf_section_parse(cs, NULL, bootstrap_config) < 0) {
+               fprintf(stderr, "radiusd: Error: Failed to parse user/group information.\n");
+               return 0;
+       }
+
+
 #ifdef HAVE_GRP_H
        /*  Set GID.  */
-       if (mainconfig.gid_name != NULL) {
+       if (gid_name) {
                struct group *gr;
 
-               gr = getgrnam(mainconfig.gid_name);
+               gr = getgrnam(gid_name);
                if (gr == NULL) {
-                       if (errno == ENOMEM) {
-                               radlog(L_ERR, "Cannot switch to Group %s: out of memory", mainconfig.gid_name);
-                       } else {
-                               radlog(L_ERR, "Cannot switch group; %s doesn't exist", mainconfig.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",
-                              mainconfig.gid_name, strerror(errno));
-                       return 0;
-               }
        } else {
                server_gid = getgid();
        }
@@ -537,103 +622,116 @@ static int switch_users(void)
 
 #ifdef HAVE_PWD_H
        /*  Set UID.  */
-       if (mainconfig.uid_name != NULL) {
+       if (uid_name) {
                struct passwd *pw;
-
-               pw = getpwnam(mainconfig.uid_name);
+               
+               pw = getpwnam(uid_name);
                if (pw == NULL) {
-                       if (errno == ENOMEM) {
-                               radlog(L_ERR, "Cannot switch to User %s: out of memory", mainconfig.uid_name);
-                       } else {
-                               radlog(L_ERR, "Cannot switch user; %s doesn't exist", mainconfig.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;
+
+               if (getuid() == pw->pw_uid) {
+                       uid_name = NULL;
+               } else {
+
+                       server_uid = pw->pw_uid;
 #ifdef HAVE_INITGROUPS
-               if (initgroups(mainconfig.uid_name, server_gid) < 0) {
-                       if (errno != EPERM) {
-                               radlog(L_ERR, "Failed setting supplementary groups for User %s: %s", mainconfig.uid_name, strerror(errno));
+                       if (initgroups(uid_name, server_gid) < 0) {
+                               fprintf(stderr, "%s: Cannot initialize supplementary group list for user %s: %s\n",
+                                       progname, uid_name, strerror(errno));
                                return 0;
                        }
+#endif
                }
+       } else {
+               server_uid = getuid();
+       }
 #endif
-               if (setuid(server_uid) < 0) {
-                       radlog(L_ERR, "Failed setting User to %s: %s", mainconfig.uid_name, strerror(errno));
+
+       if (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.
+                */
        }
-#endif
 
-#ifdef HAVE_SYS_RESOURCE_H
-       /*  Get the current maximum for core files.  */
-       if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
-               radlog(L_ERR, "Failed to get current core limit:  %s", strerror(errno));
+#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
 
-       if (mainconfig.allow_core_dumps) {
-#ifdef HAVE_SYS_PRTCL_H
-#ifdef PR_SET_DUMPABLE
-               if (prctl(PR_SET_DUMPABLE, 1) < 0) {
-                       radlog(L_ERR,"Cannot enable core dumps: prctl(PR_SET_DUMPABLE) failed: '%s'",
-                              strerror(errno));
+#ifdef HAVE_SETUID
+       /*
+        *      Just before losing root permissions, ensure that the
+        *      log files have the correct owner && group.
+        *
+        *      We have to do this because the log file MAY have been
+        *      specified on the command-line.
+        */
+       if (uid_name || gid_name) {
+               if ((mainconfig.radlog_dest == RADLOG_FILES) &&
+                   (mainconfig.radlog_fd < 0)) {
+                       mainconfig.radlog_fd = open(mainconfig.log_file,
+                                                   O_WRONLY | O_APPEND | O_CREAT, 0640);
+                       if (mainconfig.radlog_fd < 0) {
+                               fprintf(stderr, "radiusd: Failed to open log file %s: %s\n", mainconfig.log_file, strerror(errno));
+                               return 0;
+                       }
+               
+                       if (chown(mainconfig.log_file, server_uid, server_gid) < 0) {
+                               fprintf(stderr, "%s: Cannot change ownership of log file %s: %s\n", 
+                                       progname, mainconfig.log_file, strerror(errno));
+                               return 0;
+                       }
                }
-#endif
-#endif
-
-#ifdef HAVE_SYS_RESOURCE_H
-               if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
-                       radlog(L_ERR, "Cannot update core dump limit: %s",
-                                       strerror(errno));
-                       return 0;
-
-                       /*
-                        *  If we're running as a daemon, and core
-                        *  dumps are enabled, log that information.
-                        */
-               } else if ((core_limits.rlim_cur != 0) && !debug_flag)
-                       radlog(L_INFO, "Core dumps are enabled.");
-#endif
-
-       } else if (!debug_flag) {
-#ifdef HAVE_SYS_RESOURCE_H
-               /*
-                *  Not debugging.  Set the core size to zero, to
-                *  prevent security breaches.  i.e. People
-                *  reading passwords from the 'core' file.
-                */
-               struct rlimit limits;
+       }               
 
-               limits.rlim_cur = 0;
-               limits.rlim_max = core_limits.rlim_max;
+       if (uid_name) {
+               doing_setuid = TRUE;
 
-               if (setrlimit(RLIMIT_CORE, &limits) < 0) {
-                       radlog(L_ERR, "Cannot disable core dumps: %s",
-                                       strerror(errno));
-                       return 0;
-               }
-#endif
+               fr_suid_down();
        }
+#endif
 
-#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.
+        *      This also clears the dumpable flag if core dumps
+        *      aren't allowed.
         */
-       if ((debug_flag == 0) &&
-           (mainconfig.radlog_dest == RADLOG_FILES) &&
-           (mainconfig.log_file != NULL)) {
-               chown(mainconfig.log_file, server_uid, server_gid);
+       fr_set_dumpable();
+
+       if (allow_core_dumps) {
+               radlog(L_INFO, "Core dumps are enabled.");
        }
-#endif
+
        return 1;
 }
+#endif /* HAVE_SETUID */
 
 
-static const LRAD_NAME_NUMBER str2dest[] = {
+static const FR_NAME_NUMBER str2dest[] = {
        { "null", RADLOG_NULL },
        { "files", RADLOG_FILES },
        { "syslog", RADLOG_SYSLOG },
@@ -650,10 +748,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",
@@ -677,138 +782,108 @@ 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 }
-                       };
+#ifdef HAVE_SYSLOG_H
+                       /*
+                        *      Call openlog only once, when the
+                        *      program starts.
+                        */
+                       openlog(progname, LOG_PID, mainconfig.syslog_facility);
+#endif
 
-                       cf_section_parse(cs, NULL, file_config);
+               } else if (mainconfig.radlog_dest == RADLOG_FILES) {
+                       if (!mainconfig.log_file) {
+                               fprintf(stderr, "radiusd: Error: Specified \"files\" as a log destination, but no log filename was given!\n");
+                               cf_section_free(&cs);
+                               return -1;
+                       }
                }
+       }
 
-               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
+
+       /*
+        *      Open the log file AFTER switching uid / gid.  If we
+        *      did switch uid/gid, then the code in switch_users()
+        *      took care of setting the file permissions correctly.
+        */
+       if ((mainconfig.radlog_dest == RADLOG_FILES) &&
+           (mainconfig.radlog_fd < 0)) {
+               mainconfig.radlog_fd = open(mainconfig.log_file,
+                                           O_WRONLY | O_APPEND | O_CREAT, 0640);
+               if (mainconfig.radlog_fd < 0) {
+                       fprintf(stderr, "radiusd: Failed to open log file %s: %s\n", mainconfig.log_file, strerror(errno));
+                       cf_section_free(&cs);
+                       return -1;
+               }
        }
 
        /* 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;
        }
 
@@ -818,24 +893,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.
@@ -846,12 +903,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.
         */
@@ -859,25 +920,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
@@ -885,23 +935,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(mainconfig.uid_name);
-       }
-
-       /*
-        *      We should really switch users earlier in the process.
-        */
-       if (!switch_users()) exit(1);
-
-       /*
         *      Sanity check the configuration for internal
         *      consistency.
         */
@@ -912,9 +945,24 @@ int read_mainconfig(int reload)
 
        /*  Reload the modules.  */
        if (setup_modules(reload, mainconfig.config) < 0) {
-               radlog(L_ERR, "Errors setting up 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;
 }
 
@@ -923,17 +971,101 @@ 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];
+
+       radlog(L_INFO, "HUP - Re-reading configuration files");
+
+       /* 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;
+
+       /*
+        *      Re-open the log file.  If we can't, then keep logging
+        *      to the old log file.
+        *
+        *      The "open log file" code is here rather than in log.c,
+        *      because it makes that function MUCH simpler.
+        */
+       if (mainconfig.radlog_dest == RADLOG_FILES) {
+               int fd, old_fd;
+               
+               fd = open(mainconfig.log_file,
+                         O_WRONLY | O_APPEND | O_CREAT, 0640);
+               if (fd >= 0) {
+                       /*
+                        *      Atomic swap. We'd like to keep the old
+                        *      FD around so that callers don't
+                        *      suddenly find the FD closed, and the
+                        *      writes go nowhere.  But that's hard to
+                        *      do.  So... we have the case where a
+                        *      log message *might* be lost on HUP.
+                        */
+                       old_fd = mainconfig.radlog_fd;
+                       mainconfig.radlog_fd = fd;
+                       close(old_fd);
+               }
+       }
+
+       radlog(L_INFO, "HUP - loading modules");
+
+       /*
+        *      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);
+}