separated udp
[radsecproxy.git] / radsecproxy.c
index 8b7906c..63dba64 100644 (file)
  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
 */
 
+/* Bugs:
+ * TCP accounting not yet supported
+ * We are not removing client requests from dynamic servers, see removeclientrqs()
+ */
+
+#include <signal.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <netdb.h>
 #include <string.h>
 #include <unistd.h>
+#include <limits.h>
 #ifdef SYS_SOLARIS9
 #include <fcntl.h>
 #endif
 #include <sys/time.h>
 #include <sys/types.h>
+#include <sys/select.h>
+#include <ctype.h>
+#include <sys/wait.h>
 #include <arpa/inet.h>
 #include <regex.h>
 #include <libgen.h>
 #include "util.h"
 #include "gconfig.h"
 #include "radsecproxy.h"
+#include "udp.h"
+#include "tcp.h"
+#include "tls.h"
+#include "dtls.h"
 
 static struct options options;
-struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
+static struct list *clconfs, *srvconfs;
+struct list *realms, *tlsconfs, *rewriteconfs;
 
-static int client_udp_count = 0;
-static int client_tls_count = 0;
-static int server_udp_count = 0;
-static int server_tls_count = 0;
+static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
 
-static struct clsrvconf *srcudpres = NULL;
-static struct clsrvconf *srctcpres = NULL;
-
-static struct replyq *udp_server_replyq = NULL;
-static int udp_server_sock = -1;
-static int udp_accserver_sock = -1;
+static struct queue *udp_server_replyq = NULL;
 static int udp_client4_sock = -1;
 static int udp_client6_sock = -1;
-static pthread_mutex_t *ssl_locks;
+static int dtls_client4_sock = -1;
+static int dtls_client6_sock = -1;
+static pthread_mutex_t tlsconfs_lock;
+static pthread_mutex_t *ssl_locks = NULL;
 static long *ssl_lock_count;
 extern int optind;
 extern char *optarg;
 
+/* minimum required declarations to avoid reordering code */
+void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
+int dynamicconfig(struct server *server);
+int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
+void freerealm(struct realm *realm);
+void freeclsrvconf(struct clsrvconf *conf);
+void freerqdata(struct request *rq);
+
+static const struct protodefs protodefs[] = {
+    {   "udp", /* UDP, assuming RAD_UDP defined as 0 */
+       NULL, /* secretdefault */
+       SOCK_DGRAM, /* socktype */
+       "1812", /* portdefault */
+       REQUEST_RETRY_COUNT, /* retrycountdefault */
+       10, /* retrycountmax */
+       REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
+       60, /* retryintervalmax */
+       udpserverrd, /* listener */
+       &options.sourceudp, /* srcaddrport */
+       NULL, /* connecter */
+       udpclientrd, /* clientreader */
+       clientradputudp /* clientradput */
+    },
+    {   "tls", /* TLS, assuming RAD_TLS defined as 1 */
+       "mysecret", /* secretdefault */
+       SOCK_STREAM, /* socktype */
+       "2083", /* portdefault */
+       0, /* retrycountdefault */
+       0, /* retrycountmax */
+       REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
+       60, /* retryintervalmax */
+       tlslistener, /* listener */
+       &options.sourcetls, /* srcaddrport */
+       tlsconnect, /* connecter */
+       tlsclientrd, /* clientreader */
+       clientradputtls /* clientradput */
+    },
+    {   "tcp", /* TCP, assuming RAD_TCP defined as 2 */
+       NULL, /* secretdefault */
+       SOCK_STREAM, /* socktype */
+       "1812", /* portdefault */
+       0, /* retrycountdefault */
+       0, /* retrycountmax */
+       REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
+       60, /* retryintervalmax */
+       tcplistener, /* listener */
+       &options.sourcetcp, /* srcaddrport */
+       tcpconnect, /* connecter */
+       tcpclientrd, /* clientreader */
+       clientradputtcp /* clientradput */
+    },
+    {   "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
+       "mysecret", /* secretdefault */
+       SOCK_DGRAM, /* socktype */
+       "2083", /* portdefault */
+       REQUEST_RETRY_COUNT, /* retrycountdefault */
+       10, /* retrycountmax */
+       REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
+       60, /* retryintervalmax */
+       udpdtlsserverrd, /* listener */
+       &options.sourcedtls, /* srcaddrport */
+       dtlsconnect, /* connecter */
+       dtlsclientrd, /* clientreader */
+       clientradputdtls /* clientradput */
+    },
+    {   NULL
+    }
+};
+
+uint8_t protoname2int(const char *name) {
+    int i;
+
+    for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
+    return i;
+}
+    
 /* callbacks for making OpenSSL thread safe */
 unsigned long ssl_thread_id() {
         return (unsigned long)pthread_self();
@@ -139,10 +225,14 @@ static int verify_cb(int ok, X509_STORE_CTX *ctx) {
   return ok;
 }
 
+struct addrinfo *getsrcprotores(uint8_t type) {
+    return srcprotores[type];
+}
+
 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
     struct addrinfo hints, *addrinfo, *res;
     char *slash, *s;
-    int plen;
+    int plen = 0;
 
     slash = conf->host ? strchr(conf->host, '/') : NULL;
     if (slash) {
@@ -164,12 +254,12 @@ int resolvepeer(struct clsrvconf *conf, int ai_flags) {
        *slash = '\0';
     }
     memset(&hints, 0, sizeof(hints));
-    hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
+    hints.ai_socktype = conf->pdef->socktype;
     hints.ai_family = AF_UNSPEC;
     hints.ai_flags = ai_flags;
     if (!conf->host && !conf->port) {
        /* getaddrinfo() doesn't like host and port to be NULL */
-       if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
+       if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
            debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
            return 0;
        }
@@ -282,7 +372,7 @@ char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
     return p;
 }
 
-struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
+struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
     struct clsrvconf *conf;
 
     conf = malloc(sizeof(struct clsrvconf));
@@ -290,6 +380,7 @@ struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
        debugx(1, DBG_ERR, "malloc failed");
     memset(conf, 0, sizeof(struct clsrvconf));
     conf->type = type;
+    conf->pdef = &protodefs[conf->type];
     if (lconf) {
        parsehostport(lconf, conf, default_port);
        if (!strcmp(conf->host, "*")) {
@@ -303,13 +394,21 @@ struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
     return conf;
 }
 
-int connecttcp(struct addrinfo *addrinfo) {
+void freeclsrvres(struct clsrvconf *res) {
+    free(res->host);
+    free(res->port);
+    if (res->addrinfo)
+       freeaddrinfo(res->addrinfo);
+    free(res);
+}
+
+int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
     int s;
     struct addrinfo *res;
 
     s = -1;
     for (res = addrinfo; res; res = res->ai_next) {
-       s = bindtoaddr(srctcpres->addrinfo, res->ai_family, 1, 1);
+       s = bindtoaddr(src, res->ai_family, 1, 1);
         if (s < 0) {
             debug(DBG_WARN, "connecttoserver: socket failed");
             continue;
@@ -335,13 +434,13 @@ int prefixmatch(void *a1, void *a2, uint8_t len) {
     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
 }
 
-/* returns the config with matching address, or NULL */
-/* if conf argument is not NULL, we only check that one */
-struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
+/* returns next config with matching address, or NULL */
+struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
     struct sockaddr_in6 *sa6 = NULL;
     struct in_addr *a4 = NULL;
     struct addrinfo *res;
     struct list_node *entry;
+    struct clsrvconf *conf;
     
     if (addr->sa_family == AF_INET6) {
         sa6 = (struct sockaddr_in6 *)addr;
@@ -352,64 +451,94 @@ struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs
     } else
        a4 = &((struct sockaddr_in *)addr)->sin_addr;
 
-    if (conf) {
+    for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
+       conf = (struct clsrvconf *)entry->data;
        if (conf->type == type) {
            if (conf->prefixlen == 255) {
                for (res = conf->addrinfo; res; res = res->ai_next)
                    if ((a4 && res->ai_family == AF_INET &&
                         !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
                        (sa6 && res->ai_family == AF_INET6 &&
-                        !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
+                        !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
+                       if (cur)
+                           *cur = entry;
                        return conf;
+                   }
            } else {
                res = conf->addrinfo;
                if (res &&
                    ((a4 && res->ai_family == AF_INET &&
                      prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
                     (sa6 && res->ai_family == AF_INET6 &&
-                     prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
+                     prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
+                   if (cur)
+                       *cur = entry;
                    return conf;
+               }
            }
        }
-       return NULL;
-    }
+    }    
+    return NULL;
+}
+
+struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
+    return find_conf(type, addr, clconfs, cur);
+}
+
+struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
+    return find_conf(type, addr, srvconfs, cur);
+}
 
-    for (entry = list_first(confs); entry; entry = list_next(entry)) { 
+/* returns next config of given type, or NULL */
+struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
+    struct list_node *entry;
+    struct clsrvconf *conf;
+    
+    for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
        conf = (struct clsrvconf *)entry->data;
        if (conf->type == type) {
-           if (conf->prefixlen == 255) {
-               for (res = conf->addrinfo; res; res = res->ai_next)
-                   if ((a4 && res->ai_family == AF_INET &&
-                        !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
-                       (sa6 && res->ai_family == AF_INET6 &&
-                        !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
-                       return conf;
-           } else {
-               res = conf->addrinfo;
-               if (res &&
-                   ((a4 && res->ai_family == AF_INET &&
-                     prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
-                    (sa6 && res->ai_family == AF_INET6 &&
-                     prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
-                   return conf;
-           }
+           if (cur)
+               *cur = entry;
+           return conf;
        }
     }    
     return NULL;
 }
 
-struct replyq *newreplyq() {
-    struct replyq *replyq;
+struct queue *newqueue() {
+    struct queue *q;
     
-    replyq = malloc(sizeof(struct replyq));
-    if (!replyq)
+    q = malloc(sizeof(struct queue));
+    if (!q)
        debugx(1, DBG_ERR, "malloc failed");
-    replyq->replies = list_create();
-    if (!replyq->replies)
+    q->entries = list_create();
+    if (!q->entries)
        debugx(1, DBG_ERR, "malloc failed");
-    pthread_mutex_init(&replyq->mutex, NULL);
-    pthread_cond_init(&replyq->cond, NULL);
-    return replyq;
+    pthread_mutex_init(&q->mutex, NULL);
+    pthread_cond_init(&q->cond, NULL);
+    return q;
+}
+
+void removequeue(struct queue *q) {
+    struct list_node *entry;
+    
+    pthread_mutex_lock(&q->mutex);
+    for (entry = list_first(q->entries); entry; entry = list_next(entry))
+       free(((struct reply *)entry)->buf);
+    list_destroy(q->entries);
+    pthread_cond_destroy(&q->cond);
+    pthread_mutex_unlock(&q->mutex);
+    pthread_mutex_destroy(&q->mutex);
+}
+
+void freebios(struct queue *q) {
+    BIO *bio;
+    
+    pthread_mutex_lock(&q->mutex);
+    while ((bio = (BIO *)list_shift(q->entries)))
+       BIO_free(bio);
+    pthread_mutex_unlock(&q->mutex);
+    removequeue(q);
 }
 
 struct client *addclient(struct clsrvconf *conf) {
@@ -429,23 +558,19 @@ struct client *addclient(struct clsrvconf *conf) {
     
     memset(new, 0, sizeof(struct client));
     new->conf = conf;
-    new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
-
+    new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newqueue();
+    if (conf->type == RAD_DTLS)
+       new->rbios = newqueue();
     list_push(conf->clients, new);
     return new;
 }
 
 void removeclient(struct client *client) {
-    struct list_node *entry;
-    
     if (!client || !client->conf->clients)
        return;
-
-    pthread_mutex_lock(&client->replyq->mutex);
-    for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
-       free(((struct reply *)entry)->buf);
-    list_destroy(client->replyq->replies);
-    pthread_mutex_unlock(&client->replyq->mutex);
+    removequeue(client->replyq);
+    if (client->rbios)
+       freebios(client->rbios);
     list_removedata(client->conf->clients, client);
     free(client);
 }
@@ -458,6 +583,8 @@ void removeclientrqs(struct client *client) {
     
     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
        server = ((struct clsrvconf *)entry->data)->servers;
+       if (!server)
+           continue;
        pthread_mutex_lock(&server->newrq_mutex);
        for (i = 0; i < MAX_REQUESTS; i++) {
            rq = server->requests + i;
@@ -467,24 +594,63 @@ void removeclientrqs(struct client *client) {
        pthread_mutex_unlock(&server->newrq_mutex);
     }
 }
-                    
-void addserver(struct clsrvconf *conf) {
-    if (conf->servers)
-       debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
+
+void freeserver(struct server *server, uint8_t destroymutex) {
+    struct request *rq, *end;
+
+    if (!server)
+       return;
+
+    if (server->requests) {
+       rq = server->requests;
+       for (end = rq + MAX_REQUESTS; rq < end; rq++)
+           freerqdata(rq);
+       free(server->requests);
+    }
+    if (server->rbios)
+       freebios(server->rbios);
+    free(server->dynamiclookuparg);
+    if (destroymutex) {
+       pthread_mutex_destroy(&server->lock);
+       pthread_cond_destroy(&server->newrq_cond);
+       pthread_mutex_destroy(&server->newrq_mutex);
+    }
+    free(server);
+}
+
+int addserver(struct clsrvconf *conf) {
+    struct clsrvconf *res;
+    uint8_t type;
     
+    if (conf->servers) {
+       debug(DBG_ERR, "addserver: currently works with just one server per conf");
+       return 0;
+    }
     conf->servers = malloc(sizeof(struct server));
-    if (!conf->servers)
-       debugx(1, DBG_ERR, "malloc failed");
+    if (!conf->servers) {
+       debug(DBG_ERR, "malloc failed");
+       return 0;
+    }
     memset(conf->servers, 0, sizeof(struct server));
     conf->servers->conf = conf;
 
-    if (conf->type == 'U') {
-       if (!srcudpres)
-           srcudpres = resolve_hostport('U', options.sourceudp, NULL);
+    type = conf->type;
+    if (type == RAD_DTLS)
+       conf->servers->rbios = newqueue();
+    
+    if (!srcprotores[type]) {
+       res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
+       srcprotores[type] = res->addrinfo;
+       res->addrinfo = NULL;
+       freeclsrvres(res);
+    }
+
+    switch (type) {
+    case RAD_UDP:
        switch (conf->addrinfo->ai_family) {
        case AF_INET:
            if (udp_client4_sock < 0) {
-               udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
+               udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
                if (udp_client4_sock < 0)
                    debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
            }
@@ -492,7 +658,7 @@ void addserver(struct clsrvconf *conf) {
            break;
        case AF_INET6:
            if (udp_client6_sock < 0) {
-               udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
+               udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
                if (udp_client6_sock < 0)
                    debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
            }
@@ -501,98 +667,61 @@ void addserver(struct clsrvconf *conf) {
        default:
            debugx(1, DBG_ERR, "addserver: unsupported address family");
        }
-       
-    } else {
-       if (!srctcpres)
-           srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
+       break;
+    case RAD_DTLS:
+       switch (conf->addrinfo->ai_family) {
+       case AF_INET:
+           if (dtls_client4_sock < 0) {
+               dtls_client4_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET, 0, 1);
+               if (dtls_client4_sock < 0)
+                   debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
+           }
+           conf->servers->sock = dtls_client4_sock;
+           break;
+       case AF_INET6:
+           if (dtls_client6_sock < 0) {
+               dtls_client6_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET6, 0, 1);
+               if (dtls_client6_sock < 0)
+                   debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
+           }
+           conf->servers->sock = dtls_client6_sock;
+           break;
+       default:
+           debugx(1, DBG_ERR, "addserver: unsupported address family");
+       }
+       break;
+    default:
        conf->servers->sock = -1;
     }
     
-    pthread_mutex_init(&conf->servers->lock, NULL);
     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
-    if (!conf->servers->requests)
-       debugx(1, DBG_ERR, "malloc failed");
+    if (!conf->servers->requests) {
+       debug(DBG_ERR, "malloc failed");
+       goto errexit;
+    }
+    if (pthread_mutex_init(&conf->servers->lock, NULL)) {
+       debug(DBG_ERR, "mutex init failed");
+       goto errexit;
+    }
     conf->servers->newrq = 0;
-    pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
-    pthread_cond_init(&conf->servers->newrq_cond, NULL);
-}
-
-/* exactly one of client and server must be non-NULL */
-/* should probably take peer list (client(s) or server(s)) as argument instead */
-/* if *peer == NULL we return who we received from, else require it to be from peer */
-/* return from in sa if not NULL */
-unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
-    int cnt, len;
-    unsigned char buf[65536], *rad;
-    struct sockaddr_storage from;
-    socklen_t fromlen = sizeof(from);
-    struct clsrvconf *p;
-    struct list_node *node;
-    
-    for (;;) {
-       cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
-       if (cnt == -1) {
-           debug(DBG_WARN, "radudpget: recv failed");
-           continue;
-       }
-       debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
+    if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
+       debug(DBG_ERR, "mutex init failed");
+       pthread_mutex_destroy(&conf->servers->lock);
+       goto errexit;
+    }
+    if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
+       debug(DBG_ERR, "mutex init failed");
+       pthread_mutex_destroy(&conf->servers->newrq_mutex);
+       pthread_mutex_destroy(&conf->servers->lock);
+       goto errexit;
+    }
 
-       if (cnt < 20) {
-           debug(DBG_WARN, "radudpget: packet too small");
-           continue;
-       }
+    return 1;
     
-       len = RADLEN(buf);
-       if (len < 20) {
-           debug(DBG_WARN, "radudpget: length too small");
-           continue;
-       }
-
-       if (cnt < len) {
-           debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
-           continue;
-       }
-       if (cnt > len)
-           debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
-
-       if (client)
-           if (*client)
-               p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
-           else
-               p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
-       else
-           if (*server)
-               p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
-           else
-               p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
-
-       if (!p) {
-           debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
-           continue;
-       }
-       
-       rad = malloc(len);
-       if (!rad) {
-           debug(DBG_ERR, "radudpget: malloc failed");
-           continue;
-       }
-       
-       if (client && !*client) {
-           node = list_first(p->clients);
-           *client = node ? (struct client *)node->data : addclient(p);
-           if (!*client) {
-               free(rad);
-               continue;
-           }
-       } else if (server && !*server)
-           *server = p->servers;
-       
-       break;
-    }
-    memcpy(rad, buf, len);
-    if (sa)
-       *sa = from;
-    return rad;
+ errexit:
+    freeserver(conf->servers, 0);
+    conf->servers = NULL;
+    return 0;
 }
 
 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
@@ -723,27 +852,29 @@ int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
     return r;
 }
 
-int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
-    int r;
+X509 *verifytlscert(SSL *ssl) {
     X509 *cert;
-    uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
     unsigned long error;
-    struct in6_addr addr;
     
     if (SSL_get_verify_result(ssl) != X509_V_OK) {
-       debug(DBG_ERR, "tlsverifycert: basic validation failed");
+       debug(DBG_ERR, "verifytlscert: basic validation failed");
        while ((error = ERR_get_error()))
-           debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
-       return 0;
+           debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
+       return NULL;
     }
 
     cert = SSL_get_peer_certificate(ssl);
-    if (!cert) {
-       debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
-       return 0;
-    }
-
-    if (conf->prefixlen == 255) {
+    if (!cert)
+       debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
+    return cert;
+}
+    
+int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
+    int r;
+    uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
+    struct in6_addr addr;
+    
+    if (conf->certnamecheck && conf->prefixlen == 255) {
        if (inet_pton(AF_INET, conf->host, &addr))
            type = AF_INET;
        else if (inet_pton(AF_INET6, conf->host, &addr))
@@ -752,166 +883,32 @@ int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
        r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
        if (r) {
            if (r < 0) {
-               debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
-               goto errexit;
+               debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
+               return 0;
            }
-           debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
+           debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
        } else {
            if (!cnregexp(cert, conf->host, NULL)) {
-               debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
-               goto errexit;
+               debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
+               return 0;
            }           
-           debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
+           debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
        }
     }
     if (conf->certcnregex) {
        if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
-           debug(DBG_DBG, "tlsverifycert: CN not matching regex");
-           goto errexit;
+           debug(DBG_WARN, "verifyconfcert: CN not matching regex");
+           return 0;
        }
-       debug(DBG_DBG, "tlsverifycert: CN matching regex");
+       debug(DBG_DBG, "verifyconfcert: CN matching regex");
     }
     if (conf->certuriregex) {
        if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
-           debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
-           goto errexit;
-       }
-       debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
-    }
-    X509_free(cert);
-    return 1;
-    
- errexit:
-    X509_free(cert);
-    return 0;
-}
-
-void tlsconnect(struct server *server, struct timeval *when, char *text) {
-    struct timeval now;
-    time_t elapsed;
-
-    debug(DBG_DBG, "tlsconnect called from %s", text);
-    pthread_mutex_lock(&server->lock);
-    if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
-       /* already reconnected, nothing to do */
-       debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
-       pthread_mutex_unlock(&server->lock);
-       return;
-    }
-
-    debug(DBG_DBG, "tlsconnect %s", text);
-
-    for (;;) {
-       gettimeofday(&now, NULL);
-       elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
-       if (server->connectionok) {
-           server->connectionok = 0;
-           sleep(10);
-       } else if (elapsed < 5)
-           sleep(10);
-       else if (elapsed < 300) {
-           debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
-           sleep(elapsed);
-       } else if (elapsed < 100000) {
-           debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
-           sleep(600);
-       } else
-           server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
-       debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
-       if (server->sock >= 0)
-           close(server->sock);
-       if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
-           debug(DBG_ERR, "tlsconnect: connecttcp failed");
-           continue;
-       }
-       
-       SSL_free(server->ssl);
-       server->ssl = SSL_new(server->conf->ssl_ctx);
-       SSL_set_fd(server->ssl, server->sock);
-       if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
-           break;
-    }
-    debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
-    gettimeofday(&server->lastconnecttry, NULL);
-    pthread_mutex_unlock(&server->lock);
-}
-
-unsigned char *radtlsget(SSL *ssl) {
-    int cnt, total, len;
-    unsigned char buf[4], *rad;
-
-    for (;;) {
-       for (total = 0; total < 4; total += cnt) {
-           cnt = SSL_read(ssl, buf + total, 4 - total);
-           if (cnt <= 0) {
-               debug(DBG_ERR, "radtlsget: connection lost");
-               if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
-                   /* remote end sent close_notify, send one back */
-                   SSL_shutdown(ssl);
-               }
-               return NULL;
-           }
-       }
-
-       len = RADLEN(buf);
-       rad = malloc(len);
-       if (!rad) {
-           debug(DBG_ERR, "radtlsget: malloc failed");
-           continue;
-       }
-       memcpy(rad, buf, 4);
-
-       for (; total < len; total += cnt) {
-           cnt = SSL_read(ssl, rad + total, len - total);
-           if (cnt <= 0) {
-               debug(DBG_ERR, "radtlsget: connection lost");
-               if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
-                   /* remote end sent close_notify, send one back */
-                   SSL_shutdown(ssl);
-               }
-               free(rad);
-               return NULL;
-           }
-       }
-    
-       if (total >= 20)
-           break;
-       
-       free(rad);
-       debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
-    }
-    
-    debug(DBG_DBG, "radtlsget: got %d bytes", total);
-    return rad;
-}
-
-int clientradput(struct server *server, unsigned char *rad) {
-    int cnt;
-    size_t len;
-    unsigned long error;
-    struct timeval lastconnecttry;
-    struct clsrvconf *conf = server->conf;
-    
-    len = RADLEN(rad);
-    if (conf->type == 'U') {
-       if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
-           debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
-           return 1;
+           debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
+           return 0;
        }
-       debug(DBG_WARN, "clientradput: send failed");
-       return 0;
+       debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
     }
-
-    lastconnecttry = server->lastconnecttry;
-    while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
-       while ((error = ERR_get_error()))
-           debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
-       tlsconnect(server, &lastconnecttry, "clientradput");
-       lastconnecttry = server->lastconnecttry;
-    }
-
-    server->connectionok = 1;
-    debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
     return 1;
 }
 
@@ -1062,10 +1059,9 @@ void sendrq(struct server *to, struct request *rq) {
            if (!to->requests[i].buf)
                break;
        if (i == to->nextid) {
-           debug(DBG_WARN, "No room in queue, dropping request");
+           debug(DBG_WARN, "sendrq: no room in queue, dropping request");
            freerqdata(rq);
-           pthread_mutex_unlock(&to->newrq_mutex);
-           return;
+           goto exit;
        }
     }
     
@@ -1074,8 +1070,15 @@ void sendrq(struct server *to, struct request *rq) {
     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
        freerqdata(rq);
-       pthread_mutex_unlock(&to->newrq_mutex);
-       return;
+       goto exit;
+    }
+    
+    if (*rq->buf == RAD_Accounting_Request) {
+       if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
+           debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
+           freerqdata(rq);
+           goto exit;
+       }
     }
 
     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
@@ -1084,13 +1087,14 @@ void sendrq(struct server *to, struct request *rq) {
 
     if (!to->newrq) {
        to->newrq = 1;
-       debug(DBG_DBG, "signalling client writer");
+       debug(DBG_DBG, "sendrq: signalling client writer");
        pthread_cond_signal(&to->newrq_cond);
     }
+ exit:
     pthread_mutex_unlock(&to->newrq_mutex);
 }
 
-void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
+void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
     struct reply *reply;
     uint8_t first;
     
@@ -1110,12 +1114,13 @@ void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *t
     reply->buf = buf;
     if (tosa)
        reply->tosa = *tosa;
+    reply->toudpsock = toudpsock;
     
     pthread_mutex_lock(&to->replyq->mutex);
 
-    first = list_first(to->replyq->replies) == NULL;
+    first = list_first(to->replyq->entries) == NULL;
     
-    if (!list_push(to->replyq->replies, reply)) {
+    if (!list_push(to->replyq->entries, reply)) {
        pthread_mutex_unlock(&to->replyq->mutex);
        free(reply);
        free(buf);
@@ -1334,30 +1339,83 @@ int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen,
     return 1;
 }
 
-struct realm *id2realm(char *id, uint8_t len) {
+struct realm *id2realm(struct list *realmlist, char *id) {
     struct list_node *entry;
-    struct realm *realm;
-    
-    for (entry = list_first(realms); entry; entry = list_next(entry)) {
+    struct realm *realm, *subrealm = NULL;
+
+    /* need to do locking for subrealms and check subrealm timers */
+    for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
        realm = (struct realm *)entry->data;
        if (!regexec(&realm->regex, id, 0, NULL, 0)) {
-           debug(DBG_DBG, "found matching realm: %s", realm->name);
-           return realm;
+           pthread_mutex_lock(&realm->subrealms_mutex);
+           if (realm->subrealms)
+               subrealm = id2realm(realm->subrealms, id);
+           pthread_mutex_unlock(&realm->subrealms_mutex);
+           return subrealm ? subrealm : realm;
        }
     }
     return NULL;
 }
 
-int rqinqueue(struct server *to, struct client *from, uint8_t id) {
-    int i;
+/* helper function, only used by removeserversubrealms() */
+void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
+    struct list_node *entry;
+    struct realm *realm;
+    
+    for (entry = list_first(realmlist); entry;) {
+       realm = (struct realm *)entry->data;
+       entry = list_next(entry);
+       if (realm->srvconfs) {
+           list_removedata(realm->srvconfs, srv);
+           if (!list_first(realm->srvconfs)) {
+               list_destroy(realm->srvconfs);
+               realm->srvconfs = NULL;
+           }
+       }
+       if (realm->accsrvconfs) {
+           list_removedata(realm->accsrvconfs, srv);
+           if (!list_first(realm->accsrvconfs)) {
+               list_destroy(realm->accsrvconfs);
+               realm->accsrvconfs = NULL;
+           }
+       }
+
+       /* remove subrealm if no servers */
+       if (!realm->srvconfs && !realm->accsrvconfs) {
+           list_removedata(realmlist, realm);
+           freerealm(realm);
+       }
+    }
+}
+
+void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
+    struct list_node *entry;
+    struct realm *realm;
+    
+    for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
+       realm = (struct realm *)entry->data;
+       pthread_mutex_lock(&realm->subrealms_mutex);
+       if (realm->subrealms) {
+           _internal_removeserversubrealms(realm->subrealms, srv);
+           if (!list_first(realm->subrealms)) {
+               list_destroy(realm->subrealms);
+               realm->subrealms = NULL;
+           }
+       }
+       pthread_mutex_unlock(&realm->subrealms_mutex);
+    }
+}
+                       
+int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
+    struct request *rq = to->requests, *end;
     
     pthread_mutex_lock(&to->newrq_mutex);
-    for (i = 0; i < MAX_REQUESTS; i++)
-       if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
+    for (end = rq + MAX_REQUESTS; rq < end; rq++)
+       if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
            break;
     pthread_mutex_unlock(&to->newrq_mutex);
     
-    return i < MAX_REQUESTS;
+    return rq < end;
 }
 
 int attrvalidate(unsigned char *attrs, int length) {
@@ -1594,17 +1652,66 @@ int rewriteusername(struct request *rq, char *in) {
     return 1;
 }
 
+const char *radmsgtype2string(uint8_t code) {
+    static const char *rad_msg_names[] = {
+       "", "Access-Request", "Access-Accept", "Access-Reject",
+       "Accounting-Request", "Accounting-Response", "", "",
+       "", "", "", "Access-Challenge",
+       "Status-Server", "Status-Client"
+    };
+    return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
+}
+
+void char2hex(char *h, unsigned char c) {
+    static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
+                                     '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+    h[0] = hexdigits[c / 16];
+    h[1] = hexdigits[c % 16];
+    return;
+}
+
+char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
+    int i, l;
+    char *s, *d;
+
+    if (!attr || len == 1) {
+       *ascii = '\0';
+       return ascii;
+    }
+
+    l = ATTRVALLEN(attr);
+    s = (char *)ATTRVAL(attr);
+    d = ascii;
+
+    for (i = 0; i < l; i++) {
+       if (s[i] > 31 && s[i] < 127) {
+           *d++ = s[i];
+           if (d - ascii == len - 1)
+               break;
+       } else {
+           if (d - ascii > len - 4)
+               break;
+           *d++ = '%';
+           char2hex(d, s[i]);
+           d += 2;
+           if (d - ascii == len - 1)
+               break;
+       }
+    }
+    *d = '\0';
+    return ascii;
+}
+
 void acclog(unsigned char *attrs, int length, char *host) {
     unsigned char *attr;
-    char username[256];
+    char username[760];
     
     attr = attrget(attrs, length, RAD_Attr_User_Name);
     if (!attr) {
        debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
        return;
     }
-    memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
-    username[ATTRVALLEN(attr)] = '\0';
+    radattr2ascii(username, sizeof(username), attr);
     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
 }
        
@@ -1613,7 +1720,7 @@ void respondaccounting(struct request *rq) {
 
     resp = malloc(20);
     if (!resp) {
-       debug(DBG_ERR, "respondstatusserver: malloc failed");
+       debug(DBG_ERR, "respondaccounting: malloc failed");
        return;
     }
     memcpy(resp, rq->buf, 20);
@@ -1621,7 +1728,7 @@ void respondaccounting(struct request *rq) {
     resp[2] = 0;
     resp[3] = 20;
     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
-    sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
+    sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
 }
 
 void respondstatusserver(struct request *rq) {
@@ -1637,7 +1744,7 @@ void respondstatusserver(struct request *rq) {
     resp[2] = 0;
     resp[3] = 20;
     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
-    sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
+    sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
 }
 
 void respondreject(struct request *rq, char *message) {
@@ -1660,34 +1767,54 @@ void respondreject(struct request *rq, char *message) {
        resp[21] = len - 20;
        memcpy(resp + 22, message, len - 22);
     }
-    sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
+    sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
 }
 
-struct server *realm2server(struct realm *realm) {
+struct clsrvconf *choosesrvconf(struct list *srvconfs) {
     struct list_node *entry;
-    struct server *server, *best = NULL;
-    
-    for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
-       server = ((struct clsrvconf *)entry->data)->servers;
-       if (!server->connectionok)
+    struct clsrvconf *server, *best = NULL, *first = NULL;
+
+    for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
+       server = (struct clsrvconf *)entry->data;
+       if (!server->servers)
+           return server;
+       if (!first)
+           first = server;
+       if (!server->servers->connectionok)
            continue;
-       if (!server->loststatsrv)
+       if (!server->servers->lostrqs)
            return server;
        if (!best) {
            best = server;
            continue;
        }
-       if (server->loststatsrv < best->loststatsrv)
+       if (server->servers->lostrqs < best->servers->lostrqs)
            best = server;
     }
-    return best;
+    return best ? best : first;
 }
 
-void radsrv(struct request *rq) {
+struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
+    struct clsrvconf *srvconf;
+    
+    *realm = id2realm(realms, id);
+    if (!*realm)
+       return NULL;
+    debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
+    srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
+    if (!srvconf)
+       return NULL;
+    if (!acc && !srvconf->servers)
+       adddynamicrealmserver(*realm, srvconf, id);
+    return srvconf->servers;
+}
+
+/* returns 0 if validation/authentication fails, else 1 */
+int radsrv(struct request *rq) {
     uint8_t code, id, *auth, *attrs, *attr;
     uint16_t len;
     struct server *to = NULL;
-    char username[256];
+    char username[254], userascii[760];
     unsigned char newauth[16];
     struct realm *realm = NULL;
     
@@ -1700,8 +1827,7 @@ void radsrv(struct request *rq) {
     
     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
        debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
-       freerqdata(rq);
-       return;
+       goto exit;
     }
 
     len -= 20;
@@ -1709,33 +1835,30 @@ void radsrv(struct request *rq) {
 
     if (!attrvalidate(attrs, len)) {
        debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
-       freerqdata(rq);
-       return;
+       goto errvalauth;
     }
 
     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
        debug(DBG_WARN, "radsrv: message authentication failed");
-       freerqdata(rq);
-       return;
+       goto errvalauth;
     }
 
-    if (code != RAD_Access_Request) {
-       switch (code) {
-       case RAD_Accounting_Request:
-           /* when forwarding accounting, also filter attributes, call removeattrs(rq) */
-           acclog(attrs, len, rq->from->conf->host);
-           respondaccounting(rq);
-           break;
-       case RAD_Status_Server:
-           respondstatusserver(rq);
-           break;
-       }
-       freerqdata(rq);
-       return;
+    if (code == RAD_Status_Server) {
+       respondstatusserver(rq);
+       goto exit;
     }
+    
+    /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
 
-    /* code == RAD_Access_Request */
+    if (code == RAD_Accounting_Request) {
+       memset(newauth, 0, 16);
+       if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
+           debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
+           goto errvalauth;
+       }
+    }
+    
     if (rq->from->conf->rewrite) {
        dorewrite(rq->buf, rq->from->conf->rewrite);
        len = RADLEN(rq->buf) - 20;
@@ -1743,56 +1866,62 @@ void radsrv(struct request *rq) {
     
     attr = attrget(attrs, len, RAD_Attr_User_Name);
     if (!attr) {
-       debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
-       freerqdata(rq);
-       return;
+       if (code == RAD_Accounting_Request) {
+           acclog(attrs, len, rq->from->conf->host);
+           respondaccounting(rq);
+       } else
+           debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
+       goto exit;
     }
     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
     username[ATTRVALLEN(attr)] = '\0';
+    radattr2ascii(userascii, sizeof(userascii), attr);
 
     if (rq->from->conf->rewriteattrregex) {
        if (!rewriteusername(rq, username)) {
            debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
-           freerqdata(rq);
-           return;
+           goto exit;
        }
        len = RADLEN(rq->buf) - 20;
        auth = (uint8_t *)(rq->buf + 4);
        attrs = rq->buf + 20;
     }
 
-    if (rq->origusername)
-       debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
-    else
-       debug(DBG_DBG, "Access Request with username: %s", username);
-       
-    realm = id2realm(username, strlen(username));
+    debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
+    
+    to = findserver(&realm, username, code == RAD_Accounting_Request);
     if (!realm) {
        debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
-       freerqdata(rq);
-       return;
-    }
-       
-    to = realm2server(realm);
-    if (to && rqinqueue(to, rq->from, id)) {
-       debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
-       freerqdata(rq);
-       return;
+       goto exit;
     }
-
     if (!to) {
-       if (realm->message) {
-           debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
+       if (realm->message && code == RAD_Access_Request) {
+           debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
            respondreject(rq, realm->message);
+       } else if (realm->accresp && code == RAD_Accounting_Request) {
+           acclog(attrs, len, rq->from->conf->host);
+           respondaccounting(rq);
        }
-       freerqdata(rq);
-       return;
+       goto exit;
     }
     
-    if (!RAND_bytes(newauth, 16)) {
-       debug(DBG_WARN, "radsrv: failed to generate random auth");
-       freerqdata(rq);
-       return;
+    if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
+       debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
+             rq->from->conf->name, to->conf->name);
+       goto exit;
+    }
+
+    if (rqinqueue(to, rq->from, id, code)) {
+       debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
+             radmsgtype2string(code), rq->from->conf->host, id);
+       goto exit;
+    }
+    
+    if (code != RAD_Accounting_Request) {
+       if (!RAND_bytes(newauth, 16)) {
+           debug(DBG_WARN, "radsrv: failed to generate random auth");
+           goto exit;
+       }
     }
 
 #ifdef DEBUG
@@ -1802,25 +1931,30 @@ void radsrv(struct request *rq) {
     attr = attrget(attrs, len, RAD_Attr_User_Password);
     if (attr) {
        debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
-       if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
-           freerqdata(rq);
-           return;
-       }
+       if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
+           goto exit;
     }
     
     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
     if (attr) {
        debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
-       if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
-           freerqdata(rq);
-           return;
-       }
+       if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
+           goto exit;
     }
 
     rq->origid = id;
     memcpy(rq->origauth, auth, 16);
     memcpy(auth, newauth, 16);
     sendrq(to, rq);
+    return 1;
+    
+ exit:
+    freerqdata(rq);
+    return 1;
+
+ errvalauth:
+    freerqdata(rq);
+    return 0;
 }
 
 int replyh(struct server *server, unsigned char *buf) {
@@ -1829,31 +1963,22 @@ int replyh(struct server *server, unsigned char *buf) {
     int i, len, sublen;
     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
     struct sockaddr_storage fromsa;
-    char tmp[256];
+    char tmp[760], stationid[760];
     
     server->connectionok = 1;
-    server->loststatsrv = 0;
+    server->lostrqs = 0;
        
     i = buf[1]; /* i is the id */
 
-    switch (*buf) {
-    case RAD_Access_Accept:
-       debug(DBG_DBG, "got Access Accept with id %d", i);
-       break;
-    case RAD_Access_Reject:
-       debug(DBG_DBG, "got Access Reject with id %d", i);
-       break;
-    case RAD_Access_Challenge:
-       debug(DBG_DBG, "got Access Challenge with id %d", i);
-       break;
-    default:
-       debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
+    if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
+       && *buf != RAD_Accounting_Response) {
+       debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
        return 0;
     }
+    debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
 
     rq = server->requests + i;
-    from = rq->from;
-       
+
     pthread_mutex_lock(&server->newrq_mutex);
     if (!rq->buf || !rq->tries) {
        pthread_mutex_unlock(&server->newrq_mutex);
@@ -1861,12 +1986,6 @@ int replyh(struct server *server, unsigned char *buf) {
        return 0;
     }
 
-    if (!from) {
-       pthread_mutex_unlock(&server->newrq_mutex);
-       debug(DBG_INFO, "replyh: client gone, ignoring reply");
-       return 0;
-    }
-       
     if (rq->received) {
        pthread_mutex_unlock(&server->newrq_mutex);
        debug(DBG_INFO, "replyh: already received, ignoring reply");
@@ -1906,14 +2025,25 @@ int replyh(struct server *server, unsigned char *buf) {
        memcpy(buf + 4, tmp, 16);
        debug(DBG_DBG, "replyh: message auth ok");
     }
-       
+    
+    gettimeofday(&server->lastrcv, NULL);
+    
     if (*rq->buf == RAD_Status_Server) {
        rq->received = 1;
        pthread_mutex_unlock(&server->newrq_mutex);
-       debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
+       debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
        return 0;
     }
 
+    gettimeofday(&server->lastreply, NULL);
+    
+    from = rq->from;
+    if (!from) {
+       pthread_mutex_unlock(&server->newrq_mutex);
+       debug(DBG_INFO, "replyh: client gone, ignoring reply");
+       return 0;
+    }
+       
     if (server->conf->rewrite) {
        dorewrite(buf, server->conf->rewrite);
        len = RADLEN(buf) - 20;
@@ -1942,24 +2072,17 @@ int replyh(struct server *server, unsigned char *buf) {
        return 0;
     }
        
-    if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
+    if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
        attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
-       /* we know the attribute exists */
-       memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
-       tmp[ATTRVALLEN(attr)] = '\0';
-       switch (*buf) {
-       case RAD_Access_Accept:
-           if (rq->origusername)
-               debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
-           else
-               debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
-           break;
-       case RAD_Access_Reject:
-           if (rq->origusername)
-               debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
-           else
-               debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
-           break;
+       if (attr) {
+           radattr2ascii(tmp, sizeof(tmp), attr);
+           attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
+           if (attr) {
+               radattr2ascii(stationid, sizeof(stationid), attr);
+               debug(DBG_INFO, "%s for user %s stationid %s from %s",
+                     radmsgtype2string(*buf), tmp, stationid, server->conf->host);
+           } else
+               debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
        }
     }
        
@@ -1992,109 +2115,100 @@ int replyh(struct server *server, unsigned char *buf) {
        debug(DBG_DBG, "replyh: computed messageauthattr");
     }
 
-    if (from->conf->type == 'U')
-       fromsa = rq->fromsa;
+    fromsa = rq->fromsa; /* only needed for UDP */
     /* once we set received = 1, rq may be reused */
     rq->received = 1;
 
-    debug(DBG_DBG, "replyh: giving packet back to where it came from");
-    sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
+    debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
+    sendreply(from, buf, &fromsa, rq->fromudpsock);
     pthread_mutex_unlock(&server->newrq_mutex);
     return 1;
 }
 
-void *udpclientrd(void *arg) {
-    struct server *server;
-    unsigned char *buf;
-    int *s = (int *)arg;
-    
-    for (;;) {
-       server = NULL;
-       buf = radudpget(*s, NULL, &server, NULL);
-       if (!replyh(server, buf))
-           free(buf);
-    }
-}
-
-void *tlsclientrd(void *arg) {
-    struct server *server = (struct server *)arg;
-    unsigned char *buf;
-    struct timeval lastconnecttry;
-    
-    for (;;) {
-       /* yes, lastconnecttry is really necessary */
-       lastconnecttry = server->lastconnecttry;
-       buf = radtlsget(server->ssl);
-       if (!buf) {
-           tlsconnect(server, &lastconnecttry, "clientrd");
-           continue;
-       }
-
-       if (!replyh(server, buf))
-           free(buf);
-    }
-}
-
+/* code for removing state not finished */
 void *clientwr(void *arg) {
     struct server *server = (struct server *)arg;
     struct request *rq;
-    pthread_t tlsclientrdth;
-    int i;
+    pthread_t clientrdth;
+    int i, dynconffail = 0;
     uint8_t rnd;
-    struct timeval now, lastsend;
+    struct timeval now;
     struct timespec timeout;
     struct request statsrvrq;
     unsigned char statsrvbuf[38];
+    struct clsrvconf *conf;
+    
+    conf = server->conf;
+    
+    if (server->dynamiclookuparg && !dynamicconfig(server)) {
+       dynconffail = 1;
+       goto errexit;
+    }
+    
+    if (!conf->addrinfo && !resolvepeer(conf, 0)) {
+       debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
+       goto errexit;
+    }
 
     memset(&timeout, 0, sizeof(struct timespec));
     
-    if (server->conf->statusserver) {
+    if (conf->statusserver) {
        memset(&statsrvrq, 0, sizeof(struct request));
        memset(statsrvbuf, 0, sizeof(statsrvbuf));
        statsrvbuf[0] = RAD_Status_Server;
        statsrvbuf[3] = 38;
        statsrvbuf[20] = RAD_Attr_Message_Authenticator;
        statsrvbuf[21] = 18;
-       gettimeofday(&lastsend, NULL);
+       gettimeofday(&server->lastrcv, NULL);
     }
-    
-    if (server->conf->type == 'U') {
+
+    if (conf->pdef->connecter) {
+       if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
+           goto errexit;
        server->connectionok = 1;
-    } else {
-       tlsconnect(server, NULL, "new client");
+       if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
+           debug(DBG_ERR, "clientwr: pthread_create failed");
+           goto errexit;
+       }
+    } else
        server->connectionok = 1;
-       if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
-           debugx(1, DBG_ERR, "clientwr: pthread_create failed");
-    }
     
     for (;;) {
        pthread_mutex_lock(&server->newrq_mutex);
        if (!server->newrq) {
            gettimeofday(&now, NULL);
-           if (server->conf->statusserver) {
-               /* random 0-7 seconds */
-               RAND_bytes(&rnd, 1);
-               rnd /= 32;
-               if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
-                   timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
-           }   
-           if (timeout.tv_sec) {
-               debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
-               pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
-               timeout.tv_sec = 0;
+           /* random 0-7 seconds */
+           RAND_bytes(&rnd, 1);
+           rnd /= 32;
+           if (conf->statusserver) {
+               if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
+                   timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
            } else {
-               debug(DBG_DBG, "clientwr: waiting for new request");
-               pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
+               if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
+                   timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
            }
+#if 0      
+           if (timeout.tv_sec > now.tv_sec)
+               debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
+#endif     
+           pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
+           timeout.tv_sec = 0;
        }
        if (server->newrq) {
            debug(DBG_DBG, "clientwr: got new request");
            server->newrq = 0;
-       } else
+       }
+#if 0  
+       else
            debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
+#endif 
        pthread_mutex_unlock(&server->newrq_mutex);
 
        for (i = 0; i < MAX_REQUESTS; i++) {
+           if (server->clientrdgone) {
+               pthread_join(clientrdth, NULL);
+               goto errexit;
+           }
            pthread_mutex_lock(&server->newrq_mutex);
            while (i < MAX_REQUESTS && !server->requests[i].buf)
                i++;
@@ -2124,13 +2238,18 @@ void *clientwr(void *arg) {
                continue;
            }
 
-           if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
-                             ? 1 : REQUEST_RETRIES)) {
+           if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
                debug(DBG_DBG, "clientwr: removing expired packet from queue");
-               if (*rq->buf == RAD_Status_Server) {
-                   debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
-                   if (server->loststatsrv < 255)
-                       server->loststatsrv++;
+               if (conf->statusserver) {
+                   if (*rq->buf == RAD_Status_Server) {
+                       debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
+                       if (server->lostrqs < 255)
+                           server->lostrqs++;
+                   }
+                } else {
+                   debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
+                   if (server->lostrqs < 255)
+                       server->lostrqs++;
                }
                freerqdata(rq);
                /* setting this to NULL means that it can be reused */
@@ -2140,18 +2259,15 @@ void *clientwr(void *arg) {
            }
             pthread_mutex_unlock(&server->newrq_mutex);
 
-           rq->expiry.tv_sec = now.tv_sec +
-               (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
-                ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
+           rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
            if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
                timeout.tv_sec = rq->expiry.tv_sec;
            rq->tries++;
-           clientradput(server, server->requests[i].buf);
-           gettimeofday(&lastsend, NULL);
+           conf->pdef->clientradput(server, server->requests[i].buf);
        }
-       if (server->conf->statusserver) {
+       if (conf->statusserver) {
            gettimeofday(&now, NULL);
-           if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
+           if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
                if (!RAND_bytes(statsrvbuf + 4, 16)) {
                    debug(DBG_WARN, "clientwr: failed to generate random auth");
                    continue;
@@ -2162,240 +2278,114 @@ void *clientwr(void *arg) {
                    continue;
                }
                memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
-               debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
-               lastsend.tv_sec = now.tv_sec;
+               debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
                sendrq(server, &statsrvrq);
            }
        }
     }
-}
-
-void *udpserverwr(void *arg) {
-    struct replyq *replyq = udp_server_replyq;
-    struct reply *reply;
-    
-    for (;;) {
-       pthread_mutex_lock(&replyq->mutex);
-       while (!(reply = (struct reply *)list_shift(replyq->replies))) {
-           debug(DBG_DBG, "udp server writer, waiting for signal");
-           pthread_cond_wait(&replyq->cond, &replyq->mutex);
-           debug(DBG_DBG, "udp server writer, got signal");
-       }
-       pthread_mutex_unlock(&replyq->mutex);
-
-       if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
-                  (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
-           debug(DBG_WARN, "sendudp: send failed");
-       free(reply->buf);
-       free(reply);
-    }
-}
-
-void *udpserverrd(void *arg) {
-    struct request rq;
-    pthread_t udpserverwrth;
-    struct clsrvconf *listenres;
-
-    listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
-    if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
-       debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
-
-    debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
-         listenres->host ? listenres->host : "*", listenres->port);
-    free(listenres);
-    
-    if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
-       debugx(1, DBG_ERR, "pthread_create failed");
-    
-    for (;;) {
-       memset(&rq, 0, sizeof(struct request));
-       rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
-       radsrv(&rq);
+ errexit:
+    conf->servers = NULL;
+    if (server->dynamiclookuparg) {
+       removeserversubrealms(realms, conf);
+       if (dynconffail)
+           free(conf);
+       else
+           freeclsrvconf(conf);
     }
+    freeserver(server, 1);
+    ERR_remove_state(0);
+    return NULL;
 }
 
-void *udpaccserverrd(void *arg) {
-    struct request rq;
+void createlistener(uint8_t type, char *arg) {
+    pthread_t th;
     struct clsrvconf *listenres;
+    struct addrinfo *res;
+    int s = -1, on = 1, *sp = NULL;
     
-    listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
-    if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
-       debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
-
-    debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
-         listenres->host ? listenres->host : "*", listenres->port);
-    free(listenres);
+    listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
+    if (!listenres)
+       debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
     
-    for (;;) {
-       memset(&rq, 0, sizeof(struct request));
-       rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
-       if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
-           radsrv(&rq);
+    for (res = listenres->addrinfo; res; res = res->ai_next) {
+        s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
+        if (s < 0) {
+            debug(DBG_WARN, "createlistener: socket failed");
+            continue;
+        }
+       setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
+#ifdef IPV6_V6ONLY
+       if (res->ai_family == AF_INET6)
+           setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
+#endif         
+       if (bind(s, res->ai_addr, res->ai_addrlen)) {
+           debug(DBG_WARN, "createlistener: bind failed");
+           close(s);
+           s = -1;
            continue;
        }
-       debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
-       freerqdata(&rq);
-    }
-}
 
-void *tlsserverwr(void *arg) {
-    int cnt;
-    unsigned long error;
-    struct client *client = (struct client *)arg;
-    struct replyq *replyq;
-    struct reply *reply;
-    
-    debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
-    replyq = client->replyq;
-    for (;;) {
-       pthread_mutex_lock(&replyq->mutex);
-       while (!list_first(replyq->replies)) {
-           if (client->ssl) {      
-               debug(DBG_DBG, "tls server writer, waiting for signal");
-               pthread_cond_wait(&replyq->cond, &replyq->mutex);
-               debug(DBG_DBG, "tls server writer, got signal");
-           }
-           if (!client->ssl) {
-               /* ssl might have changed while waiting */
-               pthread_mutex_unlock(&replyq->mutex);
-               debug(DBG_DBG, "tlsserverwr: exiting as requested");
-               pthread_exit(NULL);
-           }
-       }
-       reply = (struct reply *)list_shift(replyq->replies);
-       pthread_mutex_unlock(&replyq->mutex);
-       cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
-       if (cnt > 0)
-           debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
-                 cnt, RADLEN(reply->buf));
-       else
-           while ((error = ERR_get_error()))
-               debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
-       free(reply->buf);
-       free(reply);
+       sp = malloc(sizeof(int));
+        if (!sp)
+            debugx(1, DBG_ERR, "malloc failed");
+       *sp = s;
+       if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
+            debugx(1, DBG_ERR, "pthread_create failed");
+       pthread_detach(th);
     }
+    if (!sp)
+       debugx(1, DBG_ERR, "createlistener: socket/bind failed");
+    
+    debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
+         listenres->host ? listenres->host : "*", listenres->port);
+    freeclsrvres(listenres);
 }
 
-void *tlsserverrd(void *arg) {
-    struct request rq;
-    unsigned long error;
-    int s;
-    struct client *client = (struct client *)arg;
-    pthread_t tlsserverwrth;
-    SSL *ssl;
-    
-    debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
-    ssl = client->ssl;
+void createlisteners(uint8_t type, char **args) {
+    int i;
 
-    if (SSL_accept(ssl) <= 0) {
-        while ((error = ERR_get_error()))
-            debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
-        debug(DBG_ERR, "SSL_accept failed");
-       goto errexit;
-    }
-    if (tlsverifycert(client->ssl, client->conf)) {
-       if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
-           debug(DBG_ERR, "tlsserverrd: pthread_create failed");
-           goto errexit;
-       }
-       for (;;) {
-           memset(&rq, 0, sizeof(struct request));
-           rq.buf = radtlsget(client->ssl);
-           if (!rq.buf)
-               break;
-           debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
-           rq.from = client;
-           radsrv(&rq);
-       }
-       debug(DBG_ERR, "tlsserverrd: connection lost");
-       /* stop writer by setting ssl to NULL and give signal in case waiting for data */
-       client->ssl = NULL;
-       pthread_mutex_lock(&client->replyq->mutex);
-       pthread_cond_signal(&client->replyq->cond);
-       pthread_mutex_unlock(&client->replyq->mutex);
-       debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
-       pthread_join(tlsserverwrth, NULL);
-    }
-    
- errexit:
-    s = SSL_get_fd(ssl);
-    SSL_free(ssl);
-    shutdown(s, SHUT_RDWR);
-    close(s);
-    debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
-    removeclientrqs(client);
-    removeclient(client);
-    pthread_exit(NULL);
-}
-
-int tlslistener() {
-    pthread_t tlsserverth;
-    int s, snew;
-    struct sockaddr_storage from;
-    size_t fromlen = sizeof(from);
-    struct clsrvconf *conf;
-    struct client *client;
-    struct clsrvconf *listenres;
-    
-    listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
-    if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
-        debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
-    
-    listen(s, 0);
-    debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
-    free(listenres);
-    
-    for (;;) {
-       snew = accept(s, (struct sockaddr *)&from, &fromlen);
-       if (snew < 0) {
-           debug(DBG_WARN, "accept failed");
-           continue;
-       }
-       debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
+    if (args)
+       for (i = 0; args[i]; i++)
+           createlistener(type, args[i]);
+    else
+       createlistener(type, NULL);
+}
 
-       conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
-       if (!conf) {
-           debug(DBG_WARN, "ignoring request, not a known TLS client");
-           shutdown(snew, SHUT_RDWR);
-           close(snew);
-           continue;
-       }
+#ifdef DEBUG
+void ssl_info_callback(const SSL *ssl, int where, int ret) {
+    const char *s;
+    int w;
 
-       client = addclient(conf);
+    w = where & ~SSL_ST_MASK;
 
-       if (!client) {
-           debug(DBG_WARN, "Failed to create new client instance");
-           shutdown(snew, SHUT_RDWR);
-           close(snew);
-           continue;
-       }
-       client->ssl = SSL_new(client->conf->ssl_ctx);
-       SSL_set_fd(client->ssl, snew);
-       if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
-           debug(DBG_ERR, "tlslistener: pthread_create failed");
-           SSL_free(client->ssl);
-           removeclient(client);
-           shutdown(snew, SHUT_RDWR);
-           close(snew);
-           continue;
-       }
-       pthread_detach(tlsserverth);
+    if (w & SSL_ST_CONNECT)
+       s = "SSL_connect";
+    else if (w & SSL_ST_ACCEPT)
+       s = "SSL_accept";
+    else
+       s = "undefined";
+
+    if (where & SSL_CB_LOOP)
+       debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
+    else if (where & SSL_CB_ALERT) {
+       s = (where & SSL_CB_READ) ? "read" : "write";
+       debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
+    }
+    else if (where & SSL_CB_EXIT) {
+       if (ret == 0)
+           debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
+       else if (ret < 0)
+           debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
     }
-    return 0;
 }
+#endif
 
-void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
-    struct tls *new;
-    SSL_CTX *ctx;
+SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
+    SSL_CTX *ctx = NULL;
     STACK_OF(X509_NAME) *calist;
+    X509_STORE *x509_s;
     int i;
     unsigned long error;
-    
-    if (!certfile || !certkeyfile)
-       debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
-
-    if (!cacertfile && !cacertpath)
-       debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
 
     if (!ssl_locks) {
        ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
@@ -2417,26 +2407,48 @@ void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, cha
            RAND_seed((unsigned char *)&pid, sizeof(pid));
        }
     }
-    ctx = SSL_CTX_new(TLSv1_method());
-    if (certkeypwd) {
-       SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
+
+    switch (type) {
+    case RAD_TLS:
+       ctx = SSL_CTX_new(TLSv1_method());
+#ifdef DEBUG   
+       SSL_CTX_set_info_callback(ctx, ssl_info_callback);
+#endif 
+       break;
+    case RAD_DTLS:
+       ctx = SSL_CTX_new(DTLSv1_method());
+#ifdef DEBUG   
+       SSL_CTX_set_info_callback(ctx, ssl_info_callback);
+#endif 
+       SSL_CTX_set_read_ahead(ctx, 1);
+       break;
+    }
+    if (!ctx) {
+       debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
+       return NULL;
+    }
+    
+    if (conf->certkeypwd) {
+       SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
        SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
     }
-    if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
-       !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
+    if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
+       !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
        !SSL_CTX_check_private_key(ctx) ||
-       !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
+       !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
        while ((error = ERR_get_error()))
            debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
-       debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
+       debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
+       SSL_CTX_free(ctx);
+       return NULL;
     }
 
-    calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
-    if (!cacertfile || calist) {
-       if (cacertpath) {
+    calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
+    if (!conf->cacertfile || calist) {
+       if (conf->cacertpath) {
            if (!calist)
                calist = sk_X509_NAME_new_null();
-           if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
+           if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
                sk_X509_NAME_free(calist);
                calist = NULL;
            }
@@ -2445,44 +2457,31 @@ void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, cha
     if (!calist) {
        while ((error = ERR_get_error()))
            debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
-       debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
+       debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
+       SSL_CTX_free(ctx);
+       return NULL;
     }
+    ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
     SSL_CTX_set_client_CA_list(ctx, calist);
     
     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
 
-    new = malloc(sizeof(struct tls));
-    if (!new || !list_push(tlsconfs, new))
-       debugx(1, DBG_ERR, "malloc failed");
-
-    memset(new, 0, sizeof(struct tls));
-    new->name = stringcopy(value, 0);
-    if (!new->name)
-       debugx(1, DBG_ERR, "malloc failed");
-    new->ctx = ctx;
-    new->count = 0;
-    debug(DBG_DBG, "tlsadd: added TLS context %s", value);
-}
-
-void tlsfree() {
-    struct list_node *entry;
-    struct tls *t;
-    
-    for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
-       t = (struct tls *)entry->data;
-       if (t->name)
-           free(t->name);
-       if (!t->count)
-           SSL_CTX_free(t->ctx);
+    if (conf->crlcheck) {
+       x509_s = SSL_CTX_get_cert_store(ctx);
+       X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
     }
-    list_destroy(tlsconfs);
-    tlsconfs = NULL;
+
+    debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
+    return ctx;
 }
 
-SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
+SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
     struct list_node *entry;
     struct tls *t, *t1 = NULL, *t2 = NULL;
+    SSL_CTX *ctx = NULL;
+    
+    pthread_mutex_lock(&tlsconfs_lock);
     
     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
        t = (struct tls *)entry->data;
@@ -2496,17 +2495,88 @@ SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
 
     t = (t1 ? t1 : t2);
     if (!t)
+       goto exit;
+
+    switch (type) {
+    case RAD_TLS:
+       if (!t->tlsctx)
+           t->tlsctx = tlscreatectx(RAD_TLS, t);
+       ctx = t->tlsctx;
+       break;
+    case RAD_DTLS:
+       if (!t->dtlsctx)
+           t->dtlsctx = tlscreatectx(RAD_DTLS, t);
+       ctx = t->dtlsctx;
+       break;
+    }
+    
+ exit:
+    pthread_mutex_unlock(&tlsconfs_lock);
+    return ctx;
+}
+
+struct list *addsrvconfs(char *value, char **names) {
+    struct list *conflist;
+    int n;
+    struct list_node *entry;
+    struct clsrvconf *conf = NULL;
+    
+    if (!names || !*names)
        return NULL;
-    t->count++;
-    return t->ctx;
+    
+    conflist = list_create();
+    if (!conflist) {
+       debug(DBG_ERR, "malloc failed");
+       return NULL;
+    }
+
+    for (n = 0; names[n]; n++) {
+       for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
+           conf = (struct clsrvconf *)entry->data;
+           if (!strcasecmp(names[n], conf->name))
+               break;
+       }
+       if (!entry) {
+           debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
+           list_destroy(conflist);
+           return NULL;
+       }
+       if (!list_push(conflist, conf)) {
+           debug(DBG_ERR, "malloc failed");
+           list_destroy(conflist);
+           return NULL;
+       }
+       debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
+    }
+    return conflist;
 }
 
-void addrealm(char *value, char **servers, char *message) {
+void freerealm(struct realm *realm) {
+    if (!realm)
+       return;
+    free(realm->name);
+    free(realm->message);
+    regfree(&realm->regex);
+    pthread_mutex_destroy(&realm->subrealms_mutex);
+    if (realm->subrealms)
+       list_destroy(realm->subrealms);
+    if (realm->srvconfs) {
+       /* emptying list without freeing data */
+       while (list_shift(realm->srvconfs));
+       list_destroy(realm->srvconfs);
+    }
+    if (realm->accsrvconfs) {
+       /* emptying list without freeing data */
+       while (list_shift(realm->accsrvconfs));
+       list_destroy(realm->accsrvconfs);
+    }
+    free(realm);
+}
+
+struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
     int n;
     struct realm *realm;
     char *s, *regex = NULL;
-    struct list_node *entry;
-    struct clsrvconf *conf;
     
     if (*value == '/') {
        /* regexp, remove optional trailing / if present */
@@ -2532,87 +2602,231 @@ void addrealm(char *value, char **servers, char *message) {
                regex[n] = '\0';
            }
        }
-       if (!regex)
-           debugx(1, DBG_ERR, "malloc failed");
+       if (!regex) {
+           debug(DBG_ERR, "malloc failed");
+           realm = NULL;
+           goto exit;
+       }
        debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
     }
 
     realm = malloc(sizeof(struct realm));
-    if (!realm)
-       debugx(1, DBG_ERR, "malloc failed");
-    
+    if (!realm) {
+       debug(DBG_ERR, "malloc failed");
+       goto exit;
+    }
     memset(realm, 0, sizeof(struct realm));
+    
+    if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
+       debug(DBG_ERR, "mutex init failed");
+       free(realm);
+       realm = NULL;
+       goto exit;
+    }
+
     realm->name = stringcopy(value, 0);
-    if (!realm->name)
-       debugx(1, DBG_ERR, "malloc failed");
-    if (message && strlen(message) > 253)
-       debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
+    if (!realm->name) {
+       debug(DBG_ERR, "malloc failed");
+       goto errexit;
+    }
+    if (message && strlen(message) > 253) {
+       debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
+       goto errexit;
+    }
     realm->message = message;
+    realm->accresp = accresp;
     
-    if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
-       debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
-    if (regex)
-       free(regex);
+    if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
+       debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
+       goto errexit;
+    }
     
     if (servers && *servers) {
-       realm->srvconfs = list_create();
+       realm->srvconfs = addsrvconfs(value, servers);
        if (!realm->srvconfs)
-           debugx(1, DBG_ERR, "malloc failed");
-       for (n = 0; servers[n]; n++) {
-           for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
-               conf = (struct clsrvconf *)entry->data;
-               if (!strcasecmp(servers[n], conf->name))
-                   break;
-           }
-           if (!entry)
-               debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
-           if (!list_push(realm->srvconfs, conf))
-               debugx(1, DBG_ERR, "malloc failed");
-           debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
-       }
-    } else
-       realm->srvconfs = NULL;
+           goto errexit;
+    }
+    
+    if (accservers && *accservers) {
+       realm->accsrvconfs = addsrvconfs(value, accservers);
+       if (!realm->accsrvconfs)
+           goto errexit;
+    }
+
+    if (!list_push(realmlist, realm)) {
+       debug(DBG_ERR, "malloc failed");
+       pthread_mutex_destroy(&realm->subrealms_mutex);
+       goto errexit;
+    }
     
-    if (!list_push(realms, realm))
-       debugx(1, DBG_ERR, "malloc failed");
     debug(DBG_DBG, "addrealm: added realm %s", value);
+    goto exit;
+
+ errexit:
+    freerealm(realm);
+    realm = NULL;
+    
+ exit:
+    free(regex);
+    if (servers) {
+       for (n = 0; servers[n]; n++)
+           free(servers[n]);
+       free(servers);
+    }
+    if (accservers) {
+       for (n = 0; accservers[n]; n++)
+           free(accservers[n]);
+       free(accservers);
+    }
+    return realm;
 }
 
-struct gconffile *openconfigfile(const char *filename) {
-    FILE *f;
-    char pathname[100], *base = NULL;
-    struct gconffile *cf = NULL;
+void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
+    struct clsrvconf *srvconf;
+    struct realm *newrealm = NULL;
+    char *realmname, *s;
+    pthread_t clientth;
     
-    f = pushgconffile(&cf, filename);
-    if (f) {
-       debug(DBG_DBG, "reading config file %s", filename);
-       return cf;
+    if (!conf->dynamiclookupcommand)
+       return;
+
+    /* create dynamic for the realm (string after last @, exit if nothing after @ */
+    realmname = strrchr(id, '@');
+    if (!realmname)
+       return;
+    realmname++;
+    if (!*realmname)
+       return;
+    for (s = realmname; *s; s++)
+       if (*s != '.' && *s != '-' && !isalnum((int)*s))
+           return;
+    
+    pthread_mutex_lock(&realm->subrealms_mutex);
+    /* exit if we now already got a matching subrealm */
+    if (id2realm(realm->subrealms, id))
+       goto exit;
+    srvconf = malloc(sizeof(struct clsrvconf));
+    if (!srvconf) {
+       debug(DBG_ERR, "malloc failed");
+       goto exit;
+    }
+    *srvconf = *conf;
+    if (!addserver(srvconf))
+       goto errexit;
+
+    if (!realm->subrealms)
+       realm->subrealms = list_create();
+    if (!realm->subrealms)
+       goto errexit;
+    newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
+    if (!newrealm)
+       goto errexit;
+
+    /* add server and accserver to newrealm */
+    newrealm->srvconfs = list_create();
+    if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
+       debug(DBG_ERR, "malloc failed");
+       goto errexit;
+    }
+    newrealm->accsrvconfs = list_create();
+    if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
+       debug(DBG_ERR, "malloc failed");
+       goto errexit;
     }
 
-    if (strlen(filename) + 1 <= sizeof(pathname)) {
-       /* basename() might modify the string */
-       strcpy(pathname, filename);
-       base = basename(pathname);
-       f = pushgconffile(&cf, base);
+    srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
+
+    if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
+       debug(DBG_ERR, "pthread_create failed");
+       goto errexit;
+    }
+    pthread_detach(clientth);
+    goto exit;
+    
+ errexit:
+    if (newrealm) {
+       list_removedata(realm->subrealms, newrealm);
+       freerealm(newrealm);
+       if (!list_first(realm->subrealms)) {
+           list_destroy(realm->subrealms);
+           realm->subrealms = NULL;
+       }
     }
+    freeserver(srvconf->servers, 1);
+    free(srvconf);
+    debug(DBG_ERR, "failed to create dynamic server");
 
-    if (!f)
-       debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
+ exit:
+    pthread_mutex_unlock(&realm->subrealms_mutex);
+}
+
+int dynamicconfig(struct server *server) {
+    int ok, fd[2], status;
+    pid_t pid;
+    struct clsrvconf *conf = server->conf;
+    struct gconffile *cf = NULL;
+    
+    /* for now we only learn hostname/address */
+    debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
+
+    if (pipe(fd) > 0) {
+       debug(DBG_ERR, "dynamicconfig: pipe error");
+       goto errexit;
+    }
+    pid = fork();
+    if (pid < 0) {
+       debug(DBG_ERR, "dynamicconfig: fork error");
+       close(fd[0]);
+       close(fd[1]);
+       goto errexit;
+    } else if (pid == 0) {
+       /* child */
+       close(fd[0]);
+       if (fd[1] != STDOUT_FILENO) {
+           if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
+               debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
+           close(fd[1]);
+       }
+       if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
+           debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
+    }
+
+    close(fd[1]);
+    pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
+    ok = getgenericconfig(&cf, NULL,
+                         "Server", CONF_CBK, confserver_cb, (void *)conf,
+                         NULL
+                         );
+    freegconf(&cf);
+       
+    if (waitpid(pid, &status, 0) < 0) {
+       debug(DBG_ERR, "dynamicconfig: wait error");
+       goto errexit;
+    }
     
-    debug(DBG_DBG, "reading config file %s", base);
-    return cf;
+    if (status) {
+       debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
+       goto errexit;
+    }
+
+    if (ok)
+       return 1;
+
+ errexit:    
+    debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
+    return 0;
 }
 
-int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
+int addmatchcertattr(struct clsrvconf *conf) {
     char *v;
     regex_t **r;
     
-    if (strncasecmp(matchcertattr, "CN:/", 4)) {
+    if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
        r = &conf->certcnregex;
-       v = matchcertattr + 4;
-    } else if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20)) {
+       v = conf->matchcertattr + 4;
+    } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
        r = &conf->certuriregex;
-       v = matchcertattr + 20;
+       v = conf->matchcertattr + 20;
     } else
        return 0;
     if (!*v)
@@ -2637,11 +2851,11 @@ int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
     return 1;
 }
 
-int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
+int addrewriteattr(struct clsrvconf *conf) {
     char *v, *w;
     
-    v = rewriteattr + 11;
-    if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
+    v = conf->rewriteattr + 11;
+    if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
        return 0;
     /* regexp, remove optional trailing / if present */
     if (v[strlen(v) - 1] == '/')
@@ -2700,21 +2914,6 @@ int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
     return *type >= 0 && *type < 256;
 }
 
-void rewritefree() {
-    struct list_node *entry;
-    struct rewriteconf *r;
-    
-    for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
-       r = (struct rewriteconf *)entry->data;
-       if (r->name)
-           free(r->name);
-       if (!r->count)
-           free(r->rewrite);
-    }
-    list_destroy(rewriteconfs);
-    rewriteconfs = NULL;
-}
-
 struct rewrite *getrewrite(char *alt1, char *alt2) {
     struct list_node *entry;
     struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
@@ -2732,7 +2931,6 @@ struct rewrite *getrewrite(char *alt1, char *alt2) {
     r = (r1 ? r1 : r2);
     if (!r)
        return NULL;
-    r->count++;
     return r->rewrite;
 }
 
@@ -2750,9 +2948,12 @@ void addrewrite(char *value, char **attrs, char **vattrs) {
        if (!a)
            debugx(1, DBG_ERR, "malloc failed");
     
-       for (i = 0; i < n; i++)
+       for (i = 0; i < n; i++) {
            if (!(a[i] = attrname2val(attrs[i])))
                debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
+           free(attrs[i]);
+       }
+       free(attrs);
        a[i] = 0;
     }
     
@@ -2763,9 +2964,12 @@ void addrewrite(char *value, char **attrs, char **vattrs) {
        if (!va)
            debugx(1, DBG_ERR, "malloc failed");
     
-       for (p = va, i = 0; i < n; i++, p += 2)
+       for (p = va, i = 0; i < n; i++, p += 2) {
            if (!vattrname2val(vattrs[i], p, p + 1))
                debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
+           free(vattrs[i]);
+       }
+       free(vattrs);
        *p = 0;
     }
     
@@ -2790,9 +2994,74 @@ void addrewrite(char *value, char **attrs, char **vattrs) {
     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
 }
 
-void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
-    char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
+void freeclsrvconf(struct clsrvconf *conf) {
+    free(conf->name);
+    free(conf->host);
+    free(conf->port);
+    free(conf->secret);
+    free(conf->tls);
+    free(conf->matchcertattr);
+    if (conf->certcnregex)
+       regfree(conf->certcnregex);
+    if (conf->certuriregex)
+       regfree(conf->certuriregex);
+    free(conf->confrewrite);
+    free(conf->rewriteattr);
+    if (conf->rewriteattrregex)
+       regfree(conf->rewriteattrregex);
+    free(conf->rewriteattrreplacement);
+    free(conf->dynamiclookupcommand);
+    free(conf->rewrite);
+    if (conf->addrinfo)
+       freeaddrinfo(conf->addrinfo);
+    /* not touching ssl_ctx, clients and servers */
+    free(conf);
+}
+
+int mergeconfstring(char **dst, char **src) {
+    char *t;
+    
+    if (*src) {
+       *dst = *src;
+       *src = NULL;
+       return 1;
+    }
+    if (*dst) {
+       t = stringcopy(*dst, 0);
+       if (!t) {
+           debug(DBG_ERR, "malloc failed");
+           return 0;
+       }
+       *dst = t;
+    }
+    return 1;
+}
+
+/* assumes dst is a shallow copy */
+int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
+    if (!mergeconfstring(&dst->name, &src->name) ||
+       !mergeconfstring(&dst->host, &src->host) ||
+       !mergeconfstring(&dst->port, &src->port) ||
+       !mergeconfstring(&dst->secret, &src->secret) ||
+       !mergeconfstring(&dst->tls, &src->tls) ||
+       !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
+       !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
+       !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
+       return 0;
+    if (src->pdef)
+       dst->pdef = src->pdef;
+    dst->statusserver = src->statusserver;
+    dst->certnamecheck = src->certnamecheck;
+    if (src->retryinterval != 255)
+       dst->retryinterval = src->retryinterval;
+    if (src->retrycount != 255)
+       dst->retrycount = src->retrycount;
+    return 1;
+}
+
+int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
     struct clsrvconf *conf;
+    char *conftype = NULL;
     
     debug(DBG_DBG, "confclient_cb called for %s", block);
 
@@ -2800,183 +3069,317 @@ void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
     if (!conf || !list_push(clconfs, conf))
        debugx(1, DBG_ERR, "malloc failed");
     memset(conf, 0, sizeof(struct clsrvconf));
+    conf->certnamecheck = 1;
     
-    getgenericconfig(cf, block,
-                    "type", CONF_STR, &type,
+    if (!getgenericconfig(cf, block,
+                    "type", CONF_STR, &conftype,
                     "host", CONF_STR, &conf->host,
                     "secret", CONF_STR, &conf->secret,
-                    "tls", CONF_STR, &tls,
-                    "matchcertificateattribute", CONF_STR, &matchcertattr,
-                    "rewrite", CONF_STR, &rewrite,
-                    "rewriteattribute", CONF_STR, &rewriteattr,
+                    "tls", CONF_STR, &conf->tls,
+                    "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
+                    "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
+                    "rewrite", CONF_STR, &conf->confrewrite,
+                    "rewriteattribute", CONF_STR, &conf->rewriteattr,
                     NULL
-                    );
-
-    /* leave conf->name to be NULL for clients */
+                         ))
+       debugx(1, DBG_ERR, "configuration error");
+    
+    conf->name = stringcopy(val, 0);
     if (!conf->host)
        conf->host = stringcopy(val, 0);
-    
-    if (type && !strcasecmp(type, "udp")) {
-       conf->type = 'U';
-       client_udp_count++;
-    } else if (type && !strcasecmp(type, "tls")) {
-       conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
+    if (!conf->name || !conf->host)
+       debugx(1, DBG_ERR, "malloc failed");
+       
+    if (!conftype)
+       debugx(1, DBG_ERR, "error in block %s, option type missing", block);
+    conf->type = protoname2int(conftype);
+    conf->pdef = &protodefs[conf->type];
+    if (!conf->pdef->name)
+       debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
+    free(conftype);
+    
+    if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
+       conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
        if (!conf->ssl_ctx)
            debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
-       if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
+       if (conf->matchcertattr && !addmatchcertattr(conf))
            debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
-       conf->type = 'T';
-       client_tls_count++;
-    } else
-       debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
-    free(type);
-    if (tls)
-       free(tls);
-    if (matchcertattr)
-       free(matchcertattr);
+    }
     
-    conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
+    conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
     
-    if (rewriteattr) {
-       if (!addrewriteattr(conf, rewriteattr))
+    if (conf->rewriteattr) {
+       if (!addrewriteattr(conf))
            debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
-       free(rewriteattr);
     }
     
     if (!resolvepeer(conf, 0))
        debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
     
     if (!conf->secret) {
-       if (conf->type == 'U')
-           debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
-       conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
+       if (!conf->pdef->secretdefault)
+           debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
+       conf->secret = stringcopy(conf->pdef->secretdefault, 0);
+       if (!conf->secret)
+           debugx(1, DBG_ERR, "malloc failed");
     }
+    return 1;
 }
 
-void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
-    char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL, *rewrite = NULL;
-    struct clsrvconf *conf;
+int compileserverconfig(struct clsrvconf *conf, const char *block) {
+    if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
+       conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
+       if (!conf->ssl_ctx) {
+           debug(DBG_ERR, "error in block %s, no tls context defined", block);
+           return 0;
+       }
+       if (conf->matchcertattr && !addmatchcertattr(conf)) {
+           debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
+           return 0;
+       }
+    }
+
+    if (!conf->port) {
+       conf->port = stringcopy(conf->pdef->portdefault, 0);
+       if (!conf->port) {
+           debug(DBG_ERR, "malloc failed");
+           return 0;
+       }
+    }
+    
+    if (conf->retryinterval == 255)
+       conf->retryinterval = protodefs[conf->type].retryintervaldefault;
+    if (conf->retrycount == 255)
+       conf->retrycount = protodefs[conf->type].retrycountdefault;
+    
+    conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
+
+    if (!conf->secret) {
+       if (!conf->pdef->secretdefault) {
+           debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
+           return 0;
+       }
+       conf->secret = stringcopy(conf->pdef->secretdefault, 0);
+       if (!conf->secret) {
+           debug(DBG_ERR, "malloc failed");
+           return 0;
+       }
+    }
+    
+    if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
+       debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
+       return 0;
+    }
+    return 1;
+}
+                       
+int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
+    struct clsrvconf *conf, *resconf;
+    char *conftype = NULL;
+    long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
     
     debug(DBG_DBG, "confserver_cb called for %s", block);
 
     conf = malloc(sizeof(struct clsrvconf));
-    if (!conf || !list_push(srvconfs, conf))
-       debugx(1, DBG_ERR, "malloc failed");
+    if (!conf) {
+       debug(DBG_ERR, "malloc failed");
+       return 0;
+    }
     memset(conf, 0, sizeof(struct clsrvconf));
+    resconf = (struct clsrvconf *)arg;
+    if (resconf) {
+       conf->statusserver = resconf->statusserver;
+       conf->certnamecheck = resconf->certnamecheck;
+    } else
+       conf->certnamecheck = 1;
+
+    if (!getgenericconfig(cf, block,
+                         "type", CONF_STR, &conftype,
+                         "host", CONF_STR, &conf->host,
+                         "port", CONF_STR, &conf->port,
+                         "secret", CONF_STR, &conf->secret,
+                         "tls", CONF_STR, &conf->tls,
+                         "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
+                         "rewrite", CONF_STR, &conf->confrewrite,
+                         "StatusServer", CONF_BLN, &conf->statusserver,
+                         "RetryInterval", CONF_LINT, &retryinterval,
+                         "RetryCount", CONF_LINT, &retrycount,
+                         "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
+                         "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
+                         NULL
+                         )) {
+       debug(DBG_ERR, "configuration error");
+       goto errexit;
+    }
     
-    getgenericconfig(cf, block,
-                    "type", CONF_STR, &type,
-                    "host", CONF_STR, &conf->host,
-                    "port", CONF_STR, &conf->port,
-                    "secret", CONF_STR, &conf->secret,
-                    "tls", CONF_STR, &tls,
-                    "matchcertificateattribute", CONF_STR, &matchcertattr,
-                    "rewrite", CONF_STR, &rewrite,
-                    "StatusServer", CONF_STR, &statusserver,
-                    NULL
-                    );
-
     conf->name = stringcopy(val, 0);
-    if (!conf->host)
+    if (!conf->name) {
+        debug(DBG_ERR, "malloc failed");
+       goto errexit;
+    }
+    if (!conf->host) {
        conf->host = stringcopy(val, 0);
-    
-    if (type && !strcasecmp(type, "udp")) {
-       conf->type = 'U';
-       server_udp_count++;
-       if (!conf->port)
-           conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
-    } else if (type && !strcasecmp(type, "tls")) {
-       conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
-       if (!conf->ssl_ctx)
-           debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
-       if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
-           debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
-       if (!conf->port)
-           conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
-       conf->type = 'T';
-       server_tls_count++;
+       if (!conf->host) {
+            debug(DBG_ERR, "malloc failed");
+           goto errexit;
+        }
+    }
+
+    if (!conftype)
+       debugx(1, DBG_ERR, "error in block %s, option type missing", block);
+    conf->type = protoname2int(conftype);
+    conf->pdef = &protodefs[conf->type];
+    if (!conf->pdef->name) {
+       debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
+       free(conftype);
+       goto errexit;
+    }
+    free(conftype);
+           
+    if (retryinterval != LONG_MIN) {
+       if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
+           debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
+           goto errexit;
+       }
+       conf->retryinterval = (uint8_t)retryinterval;
     } else
-       debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
-    free(type);
-    if (tls)
-       free(tls);
-    if (matchcertattr)
-       free(matchcertattr);
+       conf->retryinterval = 255;
     
-    conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
-    
-    if (!resolvepeer(conf, 0))
-       debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
+    if (retrycount != LONG_MIN) {
+       if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
+           debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
+           goto errexit;
+       }
+       conf->retrycount = (uint8_t)retrycount;
+    } else
+       conf->retrycount = 255;
     
-    if (!conf->secret) {
-       if (conf->type == 'U')
-           debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
-       conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
+    if (resconf) {
+       if (!mergesrvconf(resconf, conf))
+           goto errexit;
+       free(conf);
+       conf = resconf;
+       if (conf->dynamiclookupcommand) {
+           free(conf->dynamiclookupcommand);
+           conf->dynamiclookupcommand = NULL;
+       }
+    }
+
+    if (resconf || !conf->dynamiclookupcommand) {
+       if (!compileserverconfig(conf, block))
+           goto errexit;
     }
     
-    if (statusserver) {
-       if (!strcasecmp(statusserver, "on"))
-           conf->statusserver = 1;
-       else if (strcasecmp(statusserver, "off"))
-           debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
-       free(statusserver);
+    if (resconf)
+       return 1;
+       
+    if (!list_push(srvconfs, conf)) {
+       debug(DBG_ERR, "malloc failed");
+       goto errexit;
     }
+    return 1;
+
+ errexit:    
+    freeclsrvconf(conf);
+    return 0;
 }
 
-void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
-    char **servers = NULL, *msg = NULL;
+int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
+    char **servers = NULL, **accservers = NULL, *msg = NULL;
+    uint8_t accresp = 0;
     
     debug(DBG_DBG, "confrealm_cb called for %s", block);
     
-    getgenericconfig(cf, block,
+    if (!getgenericconfig(cf, block,
                     "server", CONF_MSTR, &servers,
+                    "accountingServer", CONF_MSTR, &accservers,
                     "ReplyMessage", CONF_STR, &msg,
+                    "AccountingResponse", CONF_BLN, &accresp,
                     NULL
-                    );
+                         ))
+       debugx(1, DBG_ERR, "configuration error");
 
-    addrealm(val, servers, msg);
-    free(servers);
+    addrealm(realms, val, servers, accservers, msg, accresp);
+    return 1;
 }
 
-void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
-    char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
+int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
+    struct tls *conf;
     
     debug(DBG_DBG, "conftls_cb called for %s", block);
     
-    getgenericconfig(cf, block,
-                    "CACertificateFile", CONF_STR, &cacertfile,
-                    "CACertificatePath", CONF_STR, &cacertpath,
-                    "CertificateFile", CONF_STR, &certfile,
-                    "CertificateKeyFile", CONF_STR, &certkeyfile,
-                    "CertificateKeyPassword", CONF_STR, &certkeypwd,
+    conf = malloc(sizeof(struct tls));
+    if (!conf) {
+       debug(DBG_ERR, "conftls_cb: malloc failed");
+       return 0;
+    }
+    memset(conf, 0, sizeof(struct tls));
+    
+    if (!getgenericconfig(cf, block,
+                    "CACertificateFile", CONF_STR, &conf->cacertfile,
+                    "CACertificatePath", CONF_STR, &conf->cacertpath,
+                    "CertificateFile", CONF_STR, &conf->certfile,
+                    "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
+                    "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
+                    "CRLCheck", CONF_BLN, &conf->crlcheck,
                     NULL
-                    );
+                         )) {
+       debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
+       goto errexit;
+    }
+    if (!conf->certfile || !conf->certkeyfile) {
+       debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
+       goto errexit;
+    }
+    if (!conf->cacertfile && !conf->cacertpath) {
+       debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
+       goto errexit;
+    }
+
+    conf->name = stringcopy(val, 0);
+    if (!conf->name) {
+       debug(DBG_ERR, "conftls_cb: malloc failed");
+       goto errexit;
+    }
     
-    tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
-    free(cacertfile);
-    free(cacertpath);
-    free(certfile);
-    free(certkeyfile);
-    free(certkeypwd);
+    pthread_mutex_lock(&tlsconfs_lock);
+    if (!list_push(tlsconfs, conf)) {
+       debug(DBG_ERR, "conftls_cb: malloc failed");
+       pthread_mutex_unlock(&tlsconfs_lock);
+       goto errexit;
+    }
+    pthread_mutex_unlock(&tlsconfs_lock);
+           
+    debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
+    return 1;
+
+ errexit:
+    free(conf->cacertfile);
+    free(conf->cacertpath);
+    free(conf->certfile);
+    free(conf->certkeyfile);
+    free(conf->certkeypwd);
+    free(conf);
+    return 0;
 }
 
-void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
+int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
     char **attrs = NULL, **vattrs = NULL;
     
     debug(DBG_DBG, "confrewrite_cb called for %s", block);
     
-    getgenericconfig(cf, block,
+    if (!getgenericconfig(cf, block,
                     "removeAttribute", CONF_MSTR, &attrs,
                     "removeVendorAttribute", CONF_MSTR, &vattrs,
                     NULL
-                    );
+                         ))
+       debugx(1, DBG_ERR, "configuration error");
     addrewrite(val, attrs, vattrs);
-    free(attrs);
-    free(vattrs);
+    return 1;
 }
 
 void getmainconfig(const char *configfile) {
-    char *loglevel = NULL;
+    long int loglevel = LONG_MIN;
     struct gconffile *cfs;
 
     cfs = openconfigfile(configfile);
@@ -3002,30 +3405,32 @@ void getmainconfig(const char *configfile) {
     if (!rewriteconfs)
        debugx(1, DBG_ERR, "malloc failed");    
  
-    getgenericconfig(&cfs, NULL,
-                    "ListenUDP", CONF_STR, &options.listenudp,
-                    "ListenTCP", CONF_STR, &options.listentcp,
-                    "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
-                    "SourceUDP", CONF_STR, &options.sourceudp,
-                    "SourceTCP", CONF_STR, &options.sourcetcp,
-                    "LogLevel", CONF_STR, &loglevel,
-                    "LogDestination", CONF_STR, &options.logdestination,
-                    "Client", CONF_CBK, confclient_cb,
-                    "Server", CONF_CBK, confserver_cb,
-                    "Realm", CONF_CBK, confrealm_cb,
-                    "TLS", CONF_CBK, conftls_cb,
-                    "Rewrite", CONF_CBK, confrewrite_cb,
-                    NULL
-                    );
-    popgconffile(&cfs);
-    tlsfree();
-    rewritefree();
-    
-    if (loglevel) {
-       if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
-           debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
-       options.loglevel = *loglevel - '0';
-       free(loglevel);
+    if (!getgenericconfig(&cfs, NULL,
+                         "ListenUDP", CONF_MSTR, &options.listenudp,
+                         "ListenTCP", CONF_MSTR, &options.listentcp,
+                         "ListenTLS", CONF_MSTR, &options.listentls,
+                         "ListenDTLS", CONF_MSTR, &options.listendtls,
+                         "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
+                         "SourceUDP", CONF_STR, &options.sourceudp,
+                         "SourceTCP", CONF_STR, &options.sourcetcp,
+                         "SourceTLS", CONF_STR, &options.sourcetls,
+                         "SourceDTLS", CONF_STR, &options.sourcedtls,
+                         "LogLevel", CONF_LINT, &loglevel,
+                         "LogDestination", CONF_STR, &options.logdestination,
+                         "LoopPrevention", CONF_BLN, &options.loopprevention,
+                         "Client", CONF_CBK, confclient_cb, NULL,
+                         "Server", CONF_CBK, confserver_cb, NULL,
+                         "Realm", CONF_CBK, confrealm_cb, NULL,
+                         "TLS", CONF_CBK, conftls_cb, NULL,
+                         "Rewrite", CONF_CBK, confrewrite_cb, NULL,
+                         NULL
+                         ))
+       debugx(1, DBG_ERR, "configuration error");
+    
+    if (loglevel != LONG_MIN) {
+       if (loglevel < 1 || loglevel > 4)
+           debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
+       options.loglevel = (uint8_t)loglevel;
     }
 }
 
@@ -3058,8 +3463,7 @@ void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8
        return;
 
  usage:
-    debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
-    exit(1);
+    debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
 }
 
 #ifdef SYS_SOLARIS9
@@ -3079,14 +3483,40 @@ int daemon(int a, int b) {
 }
 #endif
 
+void *sighandler(void *arg) {
+    sigset_t sigset;
+    int sig;
+
+    for(;;) {
+       sigemptyset(&sigset);
+       sigaddset(&sigset, SIGPIPE);
+       sigwait(&sigset, &sig);
+       /* only get SIGPIPE right now, so could simplify below code */
+        switch (sig) {
+        case 0:
+            /* completely ignoring this */
+            break;
+        case SIGPIPE:
+            debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
+            break;
+        default:
+            debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
+        }
+    }
+}
+
 int main(int argc, char **argv) {
-    pthread_t udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
+    pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth, dtlsclient4rdth, dtlsclient6rdth;
+    sigset_t sigset;
     struct list_node *entry;
     uint8_t foreground = 0, pretend = 0, loglevel = 0;
     char *configfile = NULL;
+    struct clsrvconf *srvconf;
     
     debug_init("radsecproxy");
     debug_set_level(DEBUG_LEVEL);
+    pthread_mutex_init(&tlsconfs_lock, NULL);
+    
     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
     if (loglevel)
        debug_set_level(loglevel);
@@ -3095,58 +3525,76 @@ int main(int argc, char **argv) {
        options.loglevel = loglevel;
     else if (options.loglevel)
        debug_set_level(options.loglevel);
-    if (foreground)
-       options.logdestination = NULL;
-    else {
-       if (!options.logdestination)
-           options.logdestination = "x-syslog:///";
-       debug_set_destination(options.logdestination);
-    }
+    if (!foreground)
+       debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
+    free(options.logdestination);
 
-    if (pretend)
-       debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
-    
     if (!list_first(clconfs))
        debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
-    if (!list_first(srvconfs))
-       debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
     if (!list_first(realms))
        debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
 
+    if (pretend)
+       debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
+
     if (!foreground && (daemon(0, 0) < 0))
        debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
     
     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
 
-    if (client_udp_count) {
-       udp_server_replyq = newreplyq();
-       if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
-           debugx(1, DBG_ERR, "pthread_create failed");
-       if (options.listenaccudp)
-           if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
-               debugx(1, DBG_ERR, "pthread_create failed");
-    }
-    
+    sigemptyset(&sigset);
+    /* exit on all but SIGPIPE, ignore more? */
+    sigaddset(&sigset, SIGPIPE);
+    pthread_sigmask(SIG_BLOCK, &sigset, NULL);
+    pthread_create(&sigth, NULL, sighandler, NULL);
+
     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
-       addserver((struct clsrvconf *)entry->data);
-       if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
-                          (void *)((struct clsrvconf *)entry->data)->servers))
+       srvconf = (struct clsrvconf *)entry->data;
+       if (srvconf->dynamiclookupcommand)
+           continue;
+       if (!addserver(srvconf))
+           debugx(1, DBG_ERR, "failed to add server");
+       if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
+                          (void *)(srvconf->servers)))
            debugx(1, DBG_ERR, "pthread_create failed");
     }
-    /* srcudpres no longer needed, while srctcpres is needed later */
-    if (srcudpres) {
-       free(srcudpres);
-       srcudpres = NULL;
+    /* srcprotores for UDP no longer needed */
+    if (srcprotores[RAD_UDP]) {
+       freeaddrinfo(srcprotores[RAD_UDP]);
+       srcprotores[RAD_UDP] = NULL;
     }
+    
     if (udp_client4_sock >= 0)
-       if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
-           debugx(1, DBG_ERR, "clientwr: pthread_create failed");
+       if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
+           debugx(1, DBG_ERR, "pthread_create failed");
     if (udp_client6_sock >= 0)
-       if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
-           debugx(1, DBG_ERR, "clientwr: pthread_create failed");
+       if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
+           debugx(1, DBG_ERR, "pthread_create failed");
     
-    if (client_tls_count)
-       return tlslistener();
+    if (dtls_client4_sock >= 0)
+       if (pthread_create(&dtlsclient4rdth, NULL, udpdtlsclientrd, (void *)&dtls_client4_sock))
+           debugx(1, DBG_ERR, "pthread_create failed");
+    if (dtls_client6_sock >= 0)
+       if (pthread_create(&dtlsclient6rdth, NULL, udpdtlsclientrd, (void *)&dtls_client6_sock))
+           debugx(1, DBG_ERR, "pthread_create failed");
+    
+    if (find_conf_type(RAD_TCP, clconfs, NULL))
+       createlisteners(RAD_TCP, options.listentcp);
+    
+    if (find_conf_type(RAD_TLS, clconfs, NULL))
+       createlisteners(RAD_TLS, options.listentls);
+    
+    if (find_conf_type(RAD_DTLS, clconfs, NULL))
+       createlisteners(RAD_DTLS, options.listendtls);
+    
+    if (find_conf_type(RAD_UDP, clconfs, NULL)) {
+       udp_server_replyq = newqueue();
+       if (pthread_create(&udpserverwrth, NULL, udpserverwr, (void *)udp_server_replyq))
+           debugx(1, DBG_ERR, "pthread_create failed");
+       createlisteners(RAD_UDP, options.listenudp);
+       if (options.listenaccudp)
+           createlisteners(RAD_UDP, options.listenaccudp);
+    }
     
     /* just hang around doing nothing, anything to do here? */
     for (;;)