separated udp
[radsecproxy.git] / radsecproxy.c
index 7f1ab32..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 "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 addrinfo *srcudpres = NULL;
-static struct addrinfo *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;
@@ -89,6 +94,74 @@ 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();
@@ -152,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) {
@@ -177,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;
        }
@@ -295,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));
@@ -303,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, "*")) {
@@ -324,13 +402,13 @@ void freeclsrvres(struct clsrvconf *res) {
     free(res);
 }
 
-int connecttcp(struct addrinfo *addrinfo) {
+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, res->ai_family, 1, 1);
+       s = bindtoaddr(src, res->ai_family, 1, 1);
         if (s < 0) {
             debug(DBG_WARN, "connecttoserver: socket failed");
             continue;
@@ -356,44 +434,8 @@ int prefixmatch(void *a1, void *a2, uint8_t len) {
     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
 }
 
-/* check if conf has matching address */
-struct clsrvconf *checkconfaddr(char type, struct sockaddr *addr, struct clsrvconf *conf) {
-    struct sockaddr_in6 *sa6 = NULL;
-    struct in_addr *a4 = NULL;
-    struct addrinfo *res;
-    
-    if (addr->sa_family == AF_INET6) {
-        sa6 = (struct sockaddr_in6 *)addr;
-        if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
-            a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
-           sa6 = NULL;
-       }
-    } else
-       a4 = &((struct sockaddr_in *)addr)->sin_addr;
-
-    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;
-       }
-    }
-    return NULL;
-}
-
 /* returns next config with matching address, or NULL */
-struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
+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;
@@ -439,18 +481,64 @@ struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs
     return NULL;
 }
 
-struct replyq *newreplyq() {
-    struct replyq *replyq;
+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);
+}
+
+/* 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;
     
-    replyq = malloc(sizeof(struct replyq));
-    if (!replyq)
+    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 (cur)
+               *cur = entry;
+           return conf;
+       }
+    }    
+    return NULL;
+}
+
+struct queue *newqueue() {
+    struct queue *q;
+    
+    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) {
@@ -470,25 +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_cond_destroy(&client->replyq->cond);
-    pthread_mutex_unlock(&client->replyq->mutex);
-    pthread_mutex_destroy(&client->replyq->mutex);
+    removequeue(client->replyq);
+    if (client->rbios)
+       freebios(client->rbios);
     list_removedata(client->conf->clients, client);
     free(client);
 }
@@ -501,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;
@@ -517,12 +601,14 @@ void freeserver(struct server *server, uint8_t destroymutex) {
     if (!server)
        return;
 
-    if(server->requests) {
+    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);
@@ -534,6 +620,7 @@ void freeserver(struct server *server, uint8_t destroymutex) {
 
 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");
@@ -547,17 +634,23 @@ int addserver(struct clsrvconf *conf) {
     memset(conf->servers, 0, sizeof(struct server));
     conf->servers->conf = conf;
 
-    if (conf->type == 'U') {
-       if (!srcudpres) {
-           res = resolve_hostport('U', options.sourceudp, NULL);
-           srcudpres = res->addrinfo;
-           res->addrinfo = NULL;
-           freeclsrvres(res);
-       }
+    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, 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);
            }
@@ -565,7 +658,7 @@ int addserver(struct clsrvconf *conf) {
            break;
        case AF_INET6:
            if (udp_client6_sock < 0) {
-               udp_client6_sock = bindtoaddr(srcudpres, 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);
            }
@@ -574,14 +667,30 @@ int addserver(struct clsrvconf *conf) {
        default:
            debugx(1, DBG_ERR, "addserver: unsupported address family");
        }
-       
-    } else {
-       if (!srctcpres) {
-           res = resolve_hostport('T', options.sourcetcp, NULL);
-           srctcpres = res->addrinfo;
-           res->addrinfo = NULL;
-           freeclsrvres(res);
+       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;
     }
     
@@ -615,84 +724,6 @@ int addserver(struct clsrvconf *conf) {
     return 0;
 }
 
-/* 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 (cnt < 20) {
-           debug(DBG_WARN, "radudpget: packet too small");
-           continue;
-       }
-    
-       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 = checkconfaddr('U', (struct sockaddr *)&from, (*client)->conf);
-           else
-               p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
-       else
-           if (*server)
-               p = checkconfaddr('U', (struct sockaddr *)&from, (*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 %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
-           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;
-}
-
 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
     int loc, i, l, n, r = 0;
     char *v;
@@ -881,225 +912,6 @@ int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
     return 1;
 }
 
-int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
-    struct timeval now;
-    time_t elapsed;
-    X509 *cert;
-    
-    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 1;
-    }
-
-    debug(DBG_DBG, "tlsconnect %s", text);
-
-    for (;;) {
-       gettimeofday(&now, NULL);
-       elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
-       if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
-           debug(DBG_DBG, "tlsconnect: timeout");
-           if (server->sock >= 0)
-               close(server->sock);
-           SSL_free(server->ssl);
-           server->ssl = NULL;
-           pthread_mutex_unlock(&server->lock);
-           return 0;
-       }
-       if (server->connectionok) {
-           server->connectionok = 0;
-           sleep(2);
-       } else if (elapsed < 1)
-           sleep(2);
-       else if (elapsed < 60) {
-           debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
-           sleep(elapsed);
-       } else if (elapsed < 100000) {
-           debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
-           sleep(60);
-       } 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)
-           continue;
-       cert = verifytlscert(server->ssl);
-       if (!cert)
-           continue;
-       if (verifyconfcert(cert, server->conf)) {
-           X509_free(cert);
-           break;
-       }
-       X509_free(cert);
-    }
-    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);
-    return 1;
-}
-
-/* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
-/* returns 0 on timeout, -1 on error and num if ok */
-int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
-    int s, ndesc, cnt, len;
-    fd_set readfds, writefds;
-    struct timeval timer;
-    
-    s = SSL_get_fd(ssl);
-    if (s < 0)
-       return -1;
-    /* make socket non-blocking? */
-    for (len = 0; len < num; len += cnt) {
-       FD_ZERO(&readfds);
-       FD_SET(s, &readfds);
-       writefds = readfds;
-       if (timeout) {
-           timer.tv_sec = timeout;
-           timer.tv_usec = 0;
-       }
-       ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
-       if (ndesc < 1)
-           return ndesc;
-
-       cnt = SSL_read(ssl, buf + len, num - len);
-       if (cnt <= 0)
-           switch (SSL_get_error(ssl, cnt)) {
-           case SSL_ERROR_WANT_READ:
-           case SSL_ERROR_WANT_WRITE:
-               cnt = 0;
-               continue;
-           case SSL_ERROR_ZERO_RETURN:
-               /* remote end sent close_notify, send one back */
-               SSL_shutdown(ssl);
-               /* fall through */
-           default:
-               return -1;
-           }
-    }
-    return num;
-}
-
-/* timeout in seconds, 0 means no timeout (blocking) */
-unsigned char *radtlsget(SSL *ssl, int timeout) {
-    int cnt, len;
-    unsigned char buf[4], *rad;
-
-    for (;;) {
-       cnt = sslreadtimeout(ssl, buf, 4, timeout);
-       if (cnt < 1) {
-           debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
-           return NULL;
-       }
-
-       len = RADLEN(buf);
-       rad = malloc(len);
-       if (!rad) {
-           debug(DBG_ERR, "radtlsget: malloc failed");
-           continue;
-       }
-       memcpy(rad, buf, 4);
-       
-       cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
-       if (cnt < 1) {
-           debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
-           free(rad);
-           return NULL;
-       }
-       
-       if (len >= 20)
-           break;
-       
-       free(rad);
-       debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
-    }
-    
-    debug(DBG_DBG, "radtlsget: got %d bytes", len);
-    return rad;
-}
-
-int clientradputudp(struct server *server, unsigned char *rad) {
-    size_t len;
-    struct sockaddr_storage sa;
-    struct sockaddr *sap;
-    struct clsrvconf *conf = server->conf;
-    in_port_t *port = NULL;
-    
-    len = RADLEN(rad);
-    
-    if (*rad == RAD_Accounting_Request) {
-       sap = (struct sockaddr *)&sa;
-       memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
-    } else
-       sap = conf->addrinfo->ai_addr;
-    
-    switch (sap->sa_family) {
-    case AF_INET:
-       port = &((struct sockaddr_in *)sap)->sin_port;
-       break;
-    case AF_INET6:
-       port = &((struct sockaddr_in6 *)sap)->sin6_port;
-       break;
-    default:
-       return 0;
-    }
-
-    if (*rad == RAD_Accounting_Request)
-       *port = htons(ntohs(*port) + 1);
-    
-    if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
-       debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
-       return 1;
-    }
-
-    debug(DBG_WARN, "clientradputudp: send failed");
-    return 0;
-}
-
-int clientradputtls(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);
-    lastconnecttry = server->lastconnecttry;
-    while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
-       while ((error = ERR_get_error()))
-           debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
-       if (server->dynamiclookuparg)
-           return 0;
-       tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
-       lastconnecttry = server->lastconnecttry;
-    }
-
-    server->connectionok = 1;
-    debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
-    return 1;
-}
-
-int clientradput(struct server *server, unsigned char *rad) {
-    switch (server->conf->type) {
-    case 'U':
-       return clientradputudp(server, rad);
-    case 'T':
-       return clientradputtls(server, rad);
-    }
-    return 0;
-}
-
 int radsign(unsigned char *rad, unsigned char *sec) {
     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
     static unsigned char first = 1;
@@ -1247,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;
        }
     }
     
@@ -1259,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);
@@ -1269,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;
     
@@ -1295,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);
@@ -1900,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);
@@ -1908,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) {
@@ -1924,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) {
@@ -1947,7 +1767,7 @@ 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 clsrvconf *choosesrvconf(struct list *srvconfs) {
@@ -1988,8 +1808,9 @@ struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
        adddynamicrealmserver(*realm, srvconf, id);
     return srvconf->servers;
 }
-                         
-void radsrv(struct request *rq) {
+
+/* 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;
@@ -2014,13 +1835,13 @@ void radsrv(struct request *rq) {
 
     if (!attrvalidate(attrs, len)) {
        debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
-       goto exit;
+       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");
-       goto exit;
+       goto errvalauth;
     }
 
     if (code == RAD_Status_Server) {
@@ -2034,7 +1855,7 @@ void radsrv(struct request *rq) {
        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 exit;
+           goto errvalauth;
        }
     }
     
@@ -2123,18 +1944,17 @@ void radsrv(struct request *rq) {
 
     rq->origid = id;
     memcpy(rq->origauth, auth, 16);
-    if (code == RAD_Accounting_Request) {
-       if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
-           debug(DBG_WARN, "radsrv: failed to sign Accounting-Request message");
-           goto exit;
-       }
-    } else
-       memcpy(auth, newauth, 16);
+    memcpy(auth, newauth, 16);
     sendrq(to, rq);
-    return;
+    return 1;
     
  exit:
     freerqdata(rq);
+    return 1;
+
+ errvalauth:
+    freerqdata(rq);
+    return 0;
 }
 
 int replyh(struct server *server, unsigned char *buf) {
@@ -2205,7 +2025,9 @@ 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);
@@ -2293,68 +2115,24 @@ 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_INFO, "replyh: passing reply to client %s", from->conf->name);
-    sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
+    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 now, lastconnecttry;
-    
-    for (;;) {
-       /* yes, lastconnecttry is really necessary */
-       lastconnecttry = server->lastconnecttry;
-       buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
-       if (!buf) {
-           if (server->dynamiclookuparg)
-               break;
-           tlsconnect(server, &lastconnecttry, 0, "clientrd");
-           continue;
-       }
-
-       if (!replyh(server, buf))
-           free(buf);
-       if (server->dynamiclookuparg) {
-           gettimeofday(&now, NULL);
-           if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
-               debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
-               break;
-           }
-       }
-    }
-    server->clientrdgone = 1;
-    return NULL;
-}
-
 /* code for removing state not finished */
 void *clientwr(void *arg) {
     struct server *server = (struct server *)arg;
     struct request *rq;
-    pthread_t tlsclientrdth;
+    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];
@@ -2381,21 +2159,20 @@ void *clientwr(void *arg) {
        statsrvbuf[3] = 38;
        statsrvbuf[20] = RAD_Attr_Message_Authenticator;
        statsrvbuf[21] = 18;
-       gettimeofday(&lastsend, NULL);
+       gettimeofday(&server->lastrcv, NULL);
     }
-    
-    if (conf->type == 'U') {
-       server->connectionok = 1;
-    } else {
-       if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
+
+    if (conf->pdef->connecter) {
+       if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
            goto errexit;
        server->connectionok = 1;
-       if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
+       if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
            debug(DBG_ERR, "clientwr: pthread_create failed");
            goto errexit;
        }
-    }
-
+    } else
+       server->connectionok = 1;
+    
     for (;;) {
        pthread_mutex_lock(&server->newrq_mutex);
        if (!server->newrq) {
@@ -2404,8 +2181,8 @@ void *clientwr(void *arg) {
            RAND_bytes(&rnd, 1);
            rnd /= 32;
            if (conf->statusserver) {
-               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 || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
+                   timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
            } else {
                if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
                    timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
@@ -2429,7 +2206,7 @@ void *clientwr(void *arg) {
 
        for (i = 0; i < MAX_REQUESTS; i++) {
            if (server->clientrdgone) {
-               pthread_join(tlsclientrdth, NULL);
+               pthread_join(clientrdth, NULL);
                goto errexit;
            }
            pthread_mutex_lock(&server->newrq_mutex);
@@ -2461,12 +2238,19 @@ void *clientwr(void *arg) {
                continue;
            }
 
-           if (rq->tries == (*rq->buf == RAD_Status_Server || conf->type == 'T'
-                             ? 1 : conf->retrycount + 1)) {
+           if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
                debug(DBG_DBG, "clientwr: removing expired packet from queue");
-               debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
-               if (server->lostrqs < 255)
-                   server->lostrqs++;
+               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 */
                rq->buf = NULL;
@@ -2475,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 || conf->type == 'T'
-                ? conf->retrydelay * (conf->retrycount + 1) : conf->retrydelay);
+           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 (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;
@@ -2498,7 +2279,6 @@ void *clientwr(void *arg) {
                }
                memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
                debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
-               lastsend.tv_sec = now.tv_sec;
                sendrq(server, &statsrvrq);
            }
        }
@@ -2513,253 +2293,99 @@ void *clientwr(void *arg) {
            freeclsrvconf(conf);
     }
     freeserver(server, 1);
+    ERR_remove_state(0);
     return NULL;
 }
 
-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(*(uint8_t *)reply->buf == RAD_Accounting_Response ? udp_accserver_sock : 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);
-    freeclsrvres(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);
-    }
-}
-
-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);
-    freeclsrvres(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);
-    }
-}
-
-void tlsserverrd(struct client *client) {
-    struct request rq;
-    pthread_t tlsserverwrth;
-    
-    debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
-    
-    if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
-       debug(DBG_ERR, "tlsserverrd: pthread_create failed");
-       return;
-    }
-
-    for (;;) {
-       memset(&rq, 0, sizeof(struct request));
-       rq.buf = radtlsget(client->ssl, 0);
-       if (!rq.buf)
-           break;
-       debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
-       rq.from = client;
-       radsrv(&rq);
+       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_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);
-    removeclientrqs(client);
-    debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
+    debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
+         listenres->host ? listenres->host : "*", listenres->port);
+    freeclsrvres(listenres);
 }
 
-void *tlsservernew(void *arg) {
-    int s;
-    struct sockaddr_storage from;
-    size_t fromlen = sizeof(from);
-    struct clsrvconf *conf;
-    struct list_node *cur = NULL;
-    SSL *ssl = NULL;
-    X509 *cert = NULL;
-    unsigned long error;
-    struct client *client;
-
-    s = *(int *)arg;
-    if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
-       debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
-       goto exit;
-    }
-    debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
-
-    conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
-    if (conf) {
-       ssl = SSL_new(conf->ssl_ctx);
-       SSL_set_fd(ssl, s);
-
-       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 exit;
-       }
-       cert = verifytlscert(ssl);
-       if (!cert)
-           goto exit;
-    }
-    
-    while (conf) {
-       if (verifyconfcert(cert, conf)) {
-           X509_free(cert);
-           client = addclient(conf);
-           if (client) {
-               client->ssl = ssl;
-               tlsserverrd(client);
-               removeclient(client);
-           } else
-               debug(DBG_WARN, "Failed to create new client instance");
-           goto exit;
-       }
-       conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
-    }
-    debug(DBG_WARN, "ignoring request, no matching TLS client");
-    if (cert)
-       X509_free(cert);
+void createlisteners(uint8_t type, char **args) {
+    int i;
 
- exit:
-    SSL_free(ssl);
-    shutdown(s, SHUT_RDWR);
-    close(s);
-    pthread_exit(NULL);
+    if (args)
+       for (i = 0; args[i]; i++)
+           createlistener(type, args[i]);
+    else
+       createlistener(type, NULL);
 }
 
-int tlslistener() {
-    pthread_t tlsserverth;
-    int s, snew;
-    struct sockaddr_storage from;
-    size_t fromlen = sizeof(from);
-    struct clsrvconf *listenres;
+#ifdef DEBUG
+void ssl_info_callback(const SSL *ssl, int where, int ret) {
+    const char *s;
+    int w;
 
-    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");
+    w = where & ~SSL_ST_MASK;
 
-    debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
-    freeclsrvres(listenres);
-    listen(s, 0);
+    if (w & SSL_ST_CONNECT)
+       s = "SSL_connect";
+    else if (w & SSL_ST_ACCEPT)
+       s = "SSL_accept";
+    else
+       s = "undefined";
 
-    for (;;) {
-       snew = accept(s, (struct sockaddr *)&from, &fromlen);
-       if (snew < 0) {
-           debug(DBG_WARN, "accept failed");
-           continue;
-       }
-       if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
-           debug(DBG_ERR, "tlslistener: pthread_create failed");
-           shutdown(snew, SHUT_RDWR);
-           close(snew);
-           continue;
-       }
-       pthread_detach(tlsserverth);
+    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, uint8_t crlcheck) {
-    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));
@@ -2781,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;
            }
@@ -2809,33 +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);
 
-    if (crlcheck) {
+    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);
     }
 
-    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;
-    debug(DBG_DBG, "tlsadd: added TLS context %s", value);
+    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;
@@ -2849,8 +2495,24 @@ SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
 
     t = (t1 ? t1 : t2);
     if (!t)
-       return NULL;
-    return t->ctx;
+       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) {
@@ -3334,7 +2996,6 @@ void addrewrite(char *value, char **attrs, char **vattrs) {
 
 void freeclsrvconf(struct clsrvconf *conf) {
     free(conf->name);
-    free(conf->conftype);
     free(conf->host);
     free(conf->port);
     free(conf->secret);
@@ -3379,7 +3040,6 @@ int mergeconfstring(char **dst, char **src) {
 /* assumes dst is a shallow copy */
 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
     if (!mergeconfstring(&dst->name, &src->name) ||
-       !mergeconfstring(&dst->conftype, &src->conftype) ||
        !mergeconfstring(&dst->host, &src->host) ||
        !mergeconfstring(&dst->port, &src->port) ||
        !mergeconfstring(&dst->secret, &src->secret) ||
@@ -3388,17 +3048,20 @@ int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
        !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->retrydelay != 255)
-       dst->retrydelay = src->retrydelay;
+    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);
 
@@ -3409,7 +3072,7 @@ int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
     conf->certnamecheck = 1;
     
     if (!getgenericconfig(cf, block,
-                    "type", CONF_STR, &conf->conftype,
+                    "type", CONF_STR, &conftype,
                     "host", CONF_STR, &conf->host,
                     "secret", CONF_STR, &conf->secret,
                     "tls", CONF_STR, &conf->tls,
@@ -3424,20 +3087,24 @@ int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
     conf->name = stringcopy(val, 0);
     if (!conf->host)
        conf->host = stringcopy(val, 0);
-    
-    if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
-       conf->type = 'U';
-       client_udp_count++;
-    } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
-       conf->ssl_ctx = conf->tls ? tlsgetctx(conf->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 (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);
+    }
     
     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
     
@@ -3450,21 +3117,18 @@ int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
        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;
 }
 
 int compileserverconfig(struct clsrvconf *conf, const char *block) {
-    switch (conf->type) {
-    case 'U':
-       if (!conf->port)
-           conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
-       break;
-    case 'T':
-       conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
+    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;
@@ -3473,22 +3137,29 @@ int compileserverconfig(struct clsrvconf *conf, const char *block) {
            debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
            return 0;
        }
-       if (!conf->port)
-           conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
-       break;
     }
 
-    if (conf->retrydelay == 255)
-       conf->retrydelay = REQUEST_RETRY_DELAY;
+    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 = REQUEST_RETRY_COUNT;
+       conf->retrycount = protodefs[conf->type].retrycountdefault;
     
     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
-    
+
     if (!conf->secret) {
-       if (conf->type == 'U')
-           debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
-       conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
+       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;
@@ -3504,7 +3175,8 @@ int compileserverconfig(struct clsrvconf *conf, const char *block) {
                        
 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
     struct clsrvconf *conf, *resconf;
-    long int retrydelay = LONG_MIN, retrycount = LONG_MIN;
+    char *conftype = NULL;
+    long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
     
     debug(DBG_DBG, "confserver_cb called for %s", block);
 
@@ -3522,7 +3194,7 @@ int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
        conf->certnamecheck = 1;
 
     if (!getgenericconfig(cf, block,
-                         "type", CONF_STR, &conf->conftype,
+                         "type", CONF_STR, &conftype,
                          "host", CONF_STR, &conf->host,
                          "port", CONF_STR, &conf->port,
                          "secret", CONF_STR, &conf->secret,
@@ -3530,7 +3202,7 @@ int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
                          "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
                          "rewrite", CONF_STR, &conf->confrewrite,
                          "StatusServer", CONF_BLN, &conf->statusserver,
-                         "RetryDelay", CONF_LINT, &retrydelay,
+                         "RetryInterval", CONF_LINT, &retryinterval,
                          "RetryCount", CONF_LINT, &retrycount,
                          "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
                          "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
@@ -3552,19 +3224,30 @@ int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
            goto errexit;
         }
     }
-    
-    if (retrydelay != LONG_MIN) {
-       if (retrydelay < 1 || retrydelay > 60) {
-           debug(DBG_ERR, "error in block %s, value of option RetryDelay is %d, must be 1-60", block, retrydelay);
+
+    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->retrydelay = (uint8_t)retrydelay;
+       conf->retryinterval = (uint8_t)retryinterval;
     } else
-       conf->retrydelay = 255;
+       conf->retryinterval = 255;
     
     if (retrycount != LONG_MIN) {
-       if (retrycount < 0 || retrycount > 10) {
-           debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
+       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;
@@ -3582,15 +3265,6 @@ int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
        }
     }
 
-    if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
-       conf->type = 'U';
-    else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
-       conf->type = 'T';
-    else {
-       debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
-       goto errexit;
-    }
-    
     if (resconf || !conf->dynamiclookupcommand) {
        if (!compileserverconfig(conf, block))
            goto errexit;
@@ -3599,17 +3273,6 @@ int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
     if (resconf)
        return 1;
        
-    switch (conf->type) {
-    case 'U':
-       server_udp_count++;
-       break;
-    case 'T':
-       server_tls_count++;
-       break;
-    default:
-       goto errexit;
-    }
-    
     if (!list_push(srvconfs, conf)) {
        debug(DBG_ERR, "malloc failed");
        goto errexit;
@@ -3641,29 +3304,63 @@ int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char
 }
 
 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
-    char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
-    uint8_t crlcheck = 0;
+    struct tls *conf;
     
     debug(DBG_DBG, "conftls_cb called for %s", block);
     
+    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, &cacertfile,
-                    "CACertificatePath", CONF_STR, &cacertpath,
-                    "CertificateFile", CONF_STR, &certfile,
-                    "CertificateKeyFile", CONF_STR, &certkeyfile,
-                    "CertificateKeyPassword", CONF_STR, &certkeypwd,
-                    "CRLCheck", CONF_BLN, &crlcheck,
+                    "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
-                         ))
-       debugx(1, DBG_ERR, "configuration error");
+                         )) {
+       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, crlcheck);
-    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;
 }
 
 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
@@ -3709,11 +3406,15 @@ void getmainconfig(const char *configfile) {
        debugx(1, DBG_ERR, "malloc failed");    
  
     if (!getgenericconfig(&cfs, NULL,
-                         "ListenUDP", CONF_STR, &options.listenudp,
-                         "ListenTCP", CONF_STR, &options.listentcp,
-                         "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
+                         "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,
@@ -3805,7 +3506,7 @@ void *sighandler(void *arg) {
 }
 
 int main(int argc, char **argv) {
-    pthread_t sigth, 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;
@@ -3814,6 +3515,8 @@ int main(int argc, char **argv) {
     
     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);
@@ -3828,8 +3531,6 @@ int main(int argc, char **argv) {
 
     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");
 
@@ -3846,16 +3547,7 @@ int main(int argc, char **argv) {
     sigaddset(&sigset, SIGPIPE);
     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
     pthread_create(&sigth, NULL, sighandler, NULL);
-    
-    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");
-    }
-    
+
     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
        srvconf = (struct clsrvconf *)entry->data;
        if (srvconf->dynamiclookupcommand)
@@ -3866,20 +3558,43 @@ int main(int argc, char **argv) {
                           (void *)(srvconf->servers)))
            debugx(1, DBG_ERR, "pthread_create failed");
     }
-    /* srcudpres no longer needed, while srctcpres is needed later */
-    if (srcudpres) {
-       freeaddrinfo(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))
+       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))
+       if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
+           debugx(1, DBG_ERR, "pthread_create failed");
+    
+    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 (client_tls_count)
-       return tlslistener();
+    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 (;;)