separated dtls into a separate file
[libradsec.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10  *              rd is responsible for init and launching wr
11  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12  *          each tlsserverrd launches tlsserverwr
13  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14  *          for init and launching rd
15  *
16  * serverrd will receive a request, processes it and puts it in the requestq of
17  *          the appropriate clientwr
18  * clientwr monitors its requestq and sends requests
19  * clientrd looks for responses, processes them and puts them in the replyq of
20  *          the peer the request came from
21  * serverwr monitors its reply and sends replies
22  *
23  * In addition to the main thread, we have:
24  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26  * For each TLS peer connecting to us there will be 2 more TLS threads
27  *       This is only for connected peers
28  * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
30 */
31
32 /* Bugs:
33  * TCP accounting not yet supported
34  * We are not removing client requests from dynamic servers, see removeclientrqs()
35  */
36
37 #include <signal.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <netdb.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <limits.h>
44 #ifdef SYS_SOLARIS9
45 #include <fcntl.h>
46 #endif
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
50 #include <ctype.h>
51 #include <sys/wait.h>
52 #include <arpa/inet.h>
53 #include <regex.h>
54 #include <libgen.h>
55 #include <pthread.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
62 #include "debug.h"
63 #include "list.h"
64 #include "util.h"
65 #include "gconfig.h"
66 #include "radsecproxy.h"
67 #include "dtls.h"
68
69 static struct options options;
70 static struct list *clconfs, *srvconfs;
71 struct list *realms, *tlsconfs, *rewriteconfs;
72
73 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
74
75 static struct queue *udp_server_replyq = NULL;
76 static int udp_client4_sock = -1;
77 static int udp_client6_sock = -1;
78 static int dtls_client4_sock = -1;
79 static int dtls_client6_sock = -1;
80 static pthread_mutex_t tlsconfs_lock;
81 static pthread_mutex_t *ssl_locks = NULL;
82 static long *ssl_lock_count;
83 extern int optind;
84 extern char *optarg;
85
86 /* minimum required declarations to avoid reordering code */
87 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
88 int dynamicconfig(struct server *server);
89 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
90 void freerealm(struct realm *realm);
91 void freeclsrvconf(struct clsrvconf *conf);
92 void freerqdata(struct request *rq);
93 void *udpserverrd(void *arg);
94 void *tlslistener(void *arg);
95 void *tcplistener(void *arg);
96 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
97 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
98 void *udpclientrd(void *arg);
99 void *tlsclientrd(void *arg);
100 void *tcpclientrd(void *arg);
101 int clientradputudp(struct server *server, unsigned char *rad);
102 int clientradputtls(struct server *server, unsigned char *rad);
103 int clientradputtcp(struct server *server, unsigned char *rad);
104 X509 *verifytlscert(SSL *ssl);
105 int radsrv(struct request *rq);
106
107 static const struct protodefs protodefs[] = {
108     {   "udp", /* UDP, assuming RAD_UDP defined as 0 */
109         NULL, /* secretdefault */
110         SOCK_DGRAM, /* socktype */
111         "1812", /* portdefault */
112         REQUEST_RETRY_COUNT, /* retrycountdefault */
113         10, /* retrycountmax */
114         REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
115         60, /* retryintervalmax */
116         udpserverrd, /* listener */
117         &options.sourceudp, /* srcaddrport */
118         NULL, /* connecter */
119         udpclientrd, /* clientreader */
120         clientradputudp /* clientradput */
121     },
122     {   "tls", /* TLS, assuming RAD_TLS defined as 1 */
123         "mysecret", /* secretdefault */
124         SOCK_STREAM, /* socktype */
125         "2083", /* portdefault */
126         0, /* retrycountdefault */
127         0, /* retrycountmax */
128         REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
129         60, /* retryintervalmax */
130         tlslistener, /* listener */
131         &options.sourcetls, /* srcaddrport */
132         tlsconnect, /* connecter */
133         tlsclientrd, /* clientreader */
134         clientradputtls /* clientradput */
135     },
136     {   "tcp", /* TCP, assuming RAD_TCP defined as 2 */
137         NULL, /* secretdefault */
138         SOCK_STREAM, /* socktype */
139         "1812", /* portdefault */
140         0, /* retrycountdefault */
141         0, /* retrycountmax */
142         REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
143         60, /* retryintervalmax */
144         tcplistener, /* listener */
145         &options.sourcetcp, /* srcaddrport */
146         tcpconnect, /* connecter */
147         tcpclientrd, /* clientreader */
148         clientradputtcp /* clientradput */
149     },
150     {   "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
151         "mysecret", /* secretdefault */
152         SOCK_DGRAM, /* socktype */
153         "2083", /* portdefault */
154         REQUEST_RETRY_COUNT, /* retrycountdefault */
155         10, /* retrycountmax */
156         REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
157         60, /* retryintervalmax */
158         udpdtlsserverrd, /* listener */
159         &options.sourcedtls, /* srcaddrport */
160         dtlsconnect, /* connecter */
161         dtlsclientrd, /* clientreader */
162         clientradputdtls /* clientradput */
163     },
164     {   NULL
165     }
166 };
167
168 uint8_t protoname2int(const char *name) {
169     int i;
170
171     for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
172     return i;
173 }
174     
175 /* callbacks for making OpenSSL thread safe */
176 unsigned long ssl_thread_id() {
177         return (unsigned long)pthread_self();
178 }
179
180 void ssl_locking_callback(int mode, int type, const char *file, int line) {
181     if (mode & CRYPTO_LOCK) {
182         pthread_mutex_lock(&ssl_locks[type]);
183         ssl_lock_count[type]++;
184     } else
185         pthread_mutex_unlock(&ssl_locks[type]);
186 }
187
188 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
189     int pwdlen = strlen(userdata);
190     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
191         return 0;
192     memcpy(buf, userdata, pwdlen);
193     return pwdlen;
194 }
195
196 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
197   char buf[256];
198   X509 *err_cert;
199   int err, depth;
200
201   err_cert = X509_STORE_CTX_get_current_cert(ctx);
202   err = X509_STORE_CTX_get_error(ctx);
203   depth = X509_STORE_CTX_get_error_depth(ctx);
204
205   if (depth > MAX_CERT_DEPTH) {
206       ok = 0;
207       err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
208       X509_STORE_CTX_set_error(ctx, err);
209   }
210
211   if (!ok) {
212       X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
213       debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
214
215       switch (err) {
216       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
217           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
218           debug(DBG_WARN, "\tIssuer=%s", buf);
219           break;
220       case X509_V_ERR_CERT_NOT_YET_VALID:
221       case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
222           debug(DBG_WARN, "\tCertificate not yet valid");
223           break;
224       case X509_V_ERR_CERT_HAS_EXPIRED:
225           debug(DBG_WARN, "Certificate has expired");
226           break;
227       case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
228           debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
229           break;
230       }
231   }
232 #ifdef DEBUG  
233   printf("certificate verify returns %d\n", ok);
234 #endif  
235   return ok;
236 }
237
238 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
239     struct addrinfo hints, *addrinfo, *res;
240     char *slash, *s;
241     int plen = 0;
242
243     slash = conf->host ? strchr(conf->host, '/') : NULL;
244     if (slash) {
245         s = slash + 1;
246         if (!*s) {
247             debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
248             return 0;
249         }
250         for (; *s; s++)
251             if (*s < '0' || *s > '9') {
252                 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
253                 return 0;
254             }
255         plen = atoi(slash + 1);
256         if (plen < 0 || plen > 128) {
257             debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
258             return 0;
259         }
260         *slash = '\0';
261     }
262     memset(&hints, 0, sizeof(hints));
263     hints.ai_socktype = conf->pdef->socktype;
264     hints.ai_family = AF_UNSPEC;
265     hints.ai_flags = ai_flags;
266     if (!conf->host && !conf->port) {
267         /* getaddrinfo() doesn't like host and port to be NULL */
268         if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
269             debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
270             return 0;
271         }
272         for (res = addrinfo; res; res = res->ai_next) {
273             switch (res->ai_family) {
274             case AF_INET:
275                 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
276                 break;
277             case AF_INET6:
278                 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
279                 break;
280             }
281         }
282     } else {
283         if (slash)
284             hints.ai_flags |= AI_NUMERICHOST;
285         if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
286             debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
287             return 0;
288         }
289         if (slash) {
290             *slash = '/';
291             switch (addrinfo->ai_family) {
292             case AF_INET:
293                 if (plen > 32) {
294                     debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
295                     freeaddrinfo(addrinfo);
296                     return 0;
297                 }
298                 break;
299             case AF_INET6:
300                 break;
301             default:
302                 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
303                 freeaddrinfo(addrinfo);
304                 return 0;
305             }
306             conf->prefixlen = plen;
307         } else
308             conf->prefixlen = 255;
309     }
310     if (conf->addrinfo)
311         freeaddrinfo(conf->addrinfo);
312     conf->addrinfo = addrinfo;
313     return 1;
314 }         
315
316 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
317     int s, on = 1;
318     struct addrinfo *res;
319     
320     for (res = addrinfo; res; res = res->ai_next) {
321         if (family != AF_UNSPEC && family != res->ai_family)
322             continue;
323         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
324         if (s < 0) {
325             debug(DBG_WARN, "bindtoaddr: socket failed");
326             continue;
327         }
328         if (reuse)
329             setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
330 #ifdef IPV6_V6ONLY
331         if (v6only)
332             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
333 #endif          
334
335         if (!bind(s, res->ai_addr, res->ai_addrlen))
336             return s;
337         debug(DBG_WARN, "bindtoaddr: bind failed");
338         close(s);
339     }
340     return -1;
341 }         
342
343 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
344     char *p, *field;
345     int ipv6 = 0;
346
347     p = s;
348     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
349     if (*p == '[') {
350         p++;
351         field = p;
352         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
353         if (*p != ']')
354             debugx(1, DBG_ERR, "no ] matching initial [");
355         ipv6 = 1;
356     } else {
357         field = p;
358         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
359     }
360     if (field == p)
361         debugx(1, DBG_ERR, "missing host/address");
362
363     conf->host = stringcopy(field, p - field);
364     if (ipv6) {
365         p++;
366         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
367             debugx(1, DBG_ERR, "unexpected character after ]");
368     }
369     if (*p == ':') {
370             /* port number or service name is specified */;
371             field = ++p;
372             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
373             if (field == p)
374                 debugx(1, DBG_ERR, "syntax error, : but no following port");
375             conf->port = stringcopy(field, p - field);
376     } else
377         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
378     return p;
379 }
380
381 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
382     struct clsrvconf *conf;
383
384     conf = malloc(sizeof(struct clsrvconf));
385     if (!conf)
386         debugx(1, DBG_ERR, "malloc failed");
387     memset(conf, 0, sizeof(struct clsrvconf));
388     conf->type = type;
389     conf->pdef = &protodefs[conf->type];
390     if (lconf) {
391         parsehostport(lconf, conf, default_port);
392         if (!strcmp(conf->host, "*")) {
393             free(conf->host);
394             conf->host = NULL;
395         }
396     } else
397         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
398     if (!resolvepeer(conf, AI_PASSIVE))
399         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
400     return conf;
401 }
402
403 void freeclsrvres(struct clsrvconf *res) {
404     free(res->host);
405     free(res->port);
406     if (res->addrinfo)
407         freeaddrinfo(res->addrinfo);
408     free(res);
409 }
410
411 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
412     int s;
413     struct addrinfo *res;
414
415     s = -1;
416     for (res = addrinfo; res; res = res->ai_next) {
417         s = bindtoaddr(src, res->ai_family, 1, 1);
418         if (s < 0) {
419             debug(DBG_WARN, "connecttoserver: socket failed");
420             continue;
421         }
422         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
423             break;
424         debug(DBG_WARN, "connecttoserver: connect failed");
425         close(s);
426         s = -1;
427     }
428     return s;
429 }         
430
431 /* returns 1 if the len first bits are equal, else 0 */
432 int prefixmatch(void *a1, void *a2, uint8_t len) {
433     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
434     int r, l = len / 8;
435     if (l && memcmp(a1, a2, l))
436         return 0;
437     r = len % 8;
438     if (!r)
439         return 1;
440     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
441 }
442
443 /* returns next config with matching address, or NULL */
444 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
445     struct sockaddr_in6 *sa6 = NULL;
446     struct in_addr *a4 = NULL;
447     struct addrinfo *res;
448     struct list_node *entry;
449     struct clsrvconf *conf;
450     
451     if (addr->sa_family == AF_INET6) {
452         sa6 = (struct sockaddr_in6 *)addr;
453         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
454             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
455             sa6 = NULL;
456         }
457     } else
458         a4 = &((struct sockaddr_in *)addr)->sin_addr;
459
460     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
461         conf = (struct clsrvconf *)entry->data;
462         if (conf->type == type) {
463             if (conf->prefixlen == 255) {
464                 for (res = conf->addrinfo; res; res = res->ai_next)
465                     if ((a4 && res->ai_family == AF_INET &&
466                          !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
467                         (sa6 && res->ai_family == AF_INET6 &&
468                          !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
469                         if (cur)
470                             *cur = entry;
471                         return conf;
472                     }
473             } else {
474                 res = conf->addrinfo;
475                 if (res &&
476                     ((a4 && res->ai_family == AF_INET &&
477                       prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
478                      (sa6 && res->ai_family == AF_INET6 &&
479                       prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
480                     if (cur)
481                         *cur = entry;
482                     return conf;
483                 }
484             }
485         }
486     }    
487     return NULL;
488 }
489
490 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
491     return find_conf(type, addr, clconfs, cur);
492 }
493
494 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
495     return find_conf(type, addr, srvconfs, cur);
496 }
497
498 /* returns next config of given type, or NULL */
499 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
500     struct list_node *entry;
501     struct clsrvconf *conf;
502     
503     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
504         conf = (struct clsrvconf *)entry->data;
505         if (conf->type == type) {
506             if (cur)
507                 *cur = entry;
508             return conf;
509         }
510     }    
511     return NULL;
512 }
513
514 struct queue *newqueue() {
515     struct queue *q;
516     
517     q = malloc(sizeof(struct queue));
518     if (!q)
519         debugx(1, DBG_ERR, "malloc failed");
520     q->entries = list_create();
521     if (!q->entries)
522         debugx(1, DBG_ERR, "malloc failed");
523     pthread_mutex_init(&q->mutex, NULL);
524     pthread_cond_init(&q->cond, NULL);
525     return q;
526 }
527
528 void removequeue(struct queue *q) {
529     struct list_node *entry;
530     
531     pthread_mutex_lock(&q->mutex);
532     for (entry = list_first(q->entries); entry; entry = list_next(entry))
533         free(((struct reply *)entry)->buf);
534     list_destroy(q->entries);
535     pthread_cond_destroy(&q->cond);
536     pthread_mutex_unlock(&q->mutex);
537     pthread_mutex_destroy(&q->mutex);
538 }
539
540 void freebios(struct queue *q) {
541     BIO *bio;
542     
543     pthread_mutex_lock(&q->mutex);
544     while ((bio = (BIO *)list_shift(q->entries)))
545         BIO_free(bio);
546     pthread_mutex_unlock(&q->mutex);
547     removequeue(q);
548 }
549
550 struct client *addclient(struct clsrvconf *conf) {
551     struct client *new = malloc(sizeof(struct client));
552     
553     if (!new) {
554         debug(DBG_ERR, "malloc failed");
555         return NULL;
556     }
557     if (!conf->clients) {
558         conf->clients = list_create();
559         if (!conf->clients) {
560             debug(DBG_ERR, "malloc failed");
561             return NULL;
562         }
563     }
564     
565     memset(new, 0, sizeof(struct client));
566     new->conf = conf;
567     new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newqueue();
568     if (conf->type == RAD_DTLS)
569         new->rbios = newqueue();
570     list_push(conf->clients, new);
571     return new;
572 }
573
574 void removeclient(struct client *client) {
575     if (!client || !client->conf->clients)
576         return;
577     removequeue(client->replyq);
578     if (client->rbios)
579         freebios(client->rbios);
580     list_removedata(client->conf->clients, client);
581     free(client);
582 }
583
584 void removeclientrqs(struct client *client) {
585     struct list_node *entry;
586     struct server *server;
587     struct request *rq;
588     int i;
589     
590     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
591         server = ((struct clsrvconf *)entry->data)->servers;
592         if (!server)
593             continue;
594         pthread_mutex_lock(&server->newrq_mutex);
595         for (i = 0; i < MAX_REQUESTS; i++) {
596             rq = server->requests + i;
597             if (rq->from == client)
598                 rq->from = NULL;
599         }
600         pthread_mutex_unlock(&server->newrq_mutex);
601     }
602 }
603
604 void freeserver(struct server *server, uint8_t destroymutex) {
605     struct request *rq, *end;
606
607     if (!server)
608         return;
609
610     if (server->requests) {
611         rq = server->requests;
612         for (end = rq + MAX_REQUESTS; rq < end; rq++)
613             freerqdata(rq);
614         free(server->requests);
615     }
616     if (server->rbios)
617         freebios(server->rbios);
618     free(server->dynamiclookuparg);
619     if (destroymutex) {
620         pthread_mutex_destroy(&server->lock);
621         pthread_cond_destroy(&server->newrq_cond);
622         pthread_mutex_destroy(&server->newrq_mutex);
623     }
624     free(server);
625 }
626
627 int addserver(struct clsrvconf *conf) {
628     struct clsrvconf *res;
629     uint8_t type;
630     
631     if (conf->servers) {
632         debug(DBG_ERR, "addserver: currently works with just one server per conf");
633         return 0;
634     }
635     conf->servers = malloc(sizeof(struct server));
636     if (!conf->servers) {
637         debug(DBG_ERR, "malloc failed");
638         return 0;
639     }
640     memset(conf->servers, 0, sizeof(struct server));
641     conf->servers->conf = conf;
642
643     type = conf->type;
644     if (type == RAD_DTLS)
645         conf->servers->rbios = newqueue();
646     
647     if (!srcprotores[type]) {
648         res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
649         srcprotores[type] = res->addrinfo;
650         res->addrinfo = NULL;
651         freeclsrvres(res);
652     }
653
654     switch (type) {
655     case RAD_UDP:
656         switch (conf->addrinfo->ai_family) {
657         case AF_INET:
658             if (udp_client4_sock < 0) {
659                 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
660                 if (udp_client4_sock < 0)
661                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
662             }
663             conf->servers->sock = udp_client4_sock;
664             break;
665         case AF_INET6:
666             if (udp_client6_sock < 0) {
667                 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
668                 if (udp_client6_sock < 0)
669                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
670             }
671             conf->servers->sock = udp_client6_sock;
672             break;
673         default:
674             debugx(1, DBG_ERR, "addserver: unsupported address family");
675         }
676         break;
677     case RAD_DTLS:
678         switch (conf->addrinfo->ai_family) {
679         case AF_INET:
680             if (dtls_client4_sock < 0) {
681                 dtls_client4_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET, 0, 1);
682                 if (dtls_client4_sock < 0)
683                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
684             }
685             conf->servers->sock = dtls_client4_sock;
686             break;
687         case AF_INET6:
688             if (dtls_client6_sock < 0) {
689                 dtls_client6_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET6, 0, 1);
690                 if (dtls_client6_sock < 0)
691                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
692             }
693             conf->servers->sock = dtls_client6_sock;
694             break;
695         default:
696             debugx(1, DBG_ERR, "addserver: unsupported address family");
697         }
698         break;
699     default:
700         conf->servers->sock = -1;
701     }
702     
703     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
704     if (!conf->servers->requests) {
705         debug(DBG_ERR, "malloc failed");
706         goto errexit;
707     }
708     if (pthread_mutex_init(&conf->servers->lock, NULL)) {
709         debug(DBG_ERR, "mutex init failed");
710         goto errexit;
711     }
712     conf->servers->newrq = 0;
713     if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
714         debug(DBG_ERR, "mutex init failed");
715         pthread_mutex_destroy(&conf->servers->lock);
716         goto errexit;
717     }
718     if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
719         debug(DBG_ERR, "mutex init failed");
720         pthread_mutex_destroy(&conf->servers->newrq_mutex);
721         pthread_mutex_destroy(&conf->servers->lock);
722         goto errexit;
723     }
724
725     return 1;
726     
727  errexit:
728     freeserver(conf->servers, 0);
729     conf->servers = NULL;
730     return 0;
731 }
732
733 /* exactly one of client and server must be non-NULL */
734 /* return who we received from in *client or *server */
735 /* return from in sa if not NULL */
736 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
737     int cnt, len;
738     unsigned char buf[4], *rad = NULL;
739     struct sockaddr_storage from;
740     socklen_t fromlen = sizeof(from);
741     struct clsrvconf *p;
742     struct list_node *node;
743     fd_set readfds;
744     
745     for (;;) {
746         if (rad) {
747             free(rad);
748             rad = NULL;
749         }
750         FD_ZERO(&readfds);
751         FD_SET(s, &readfds);
752         if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
753             continue;
754         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
755         if (cnt == -1) {
756             debug(DBG_WARN, "radudpget: recv failed");
757             continue;
758         }
759         if (cnt < 20) {
760             debug(DBG_WARN, "radudpget: length too small");
761             recv(s, buf, 4, 0);
762             continue;
763         }
764         
765         p = find_conf(RAD_UDP, (struct sockaddr *)&from, client ? clconfs : srvconfs, NULL);
766         if (!p) {
767             debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
768             recv(s, buf, 4, 0);
769             continue;
770         }
771         
772         len = RADLEN(buf);
773         if (len < 20) {
774             debug(DBG_WARN, "radudpget: length too small");
775             recv(s, buf, 4, 0);
776             continue;
777         }
778             
779         rad = malloc(len);
780         if (!rad) {
781             debug(DBG_ERR, "radudpget: malloc failed");
782             recv(s, buf, 4, 0);
783             continue;
784         }
785         
786         cnt = recv(s, rad, len, MSG_TRUNC);
787         debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
788
789         if (cnt < len) {
790             debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
791             continue;
792         }
793         if (cnt > len)
794             debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
795
796         if (client) {
797             node = list_first(p->clients);
798             *client = node ? (struct client *)node->data : addclient(p);
799             if (!*client)
800                 continue;
801         } else if (server)
802             *server = p->servers;
803         break;
804     }
805     if (sa)
806         *sa = from;
807     return rad;
808 }
809
810 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
811     int loc, i, l, n, r = 0;
812     char *v;
813     X509_EXTENSION *ex;
814     STACK_OF(GENERAL_NAME) *alt;
815     GENERAL_NAME *gn;
816     
817     debug(DBG_DBG, "subjectaltnameaddr");
818     
819     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
820     if (loc < 0)
821         return r;
822     
823     ex = X509_get_ext(cert, loc);
824     alt = X509V3_EXT_d2i(ex);
825     if (!alt)
826         return r;
827     
828     n = sk_GENERAL_NAME_num(alt);
829     for (i = 0; i < n; i++) {
830         gn = sk_GENERAL_NAME_value(alt, i);
831         if (gn->type != GEN_IPADD)
832             continue;
833         r = -1;
834         v = (char *)ASN1_STRING_data(gn->d.ia5);
835         l = ASN1_STRING_length(gn->d.ia5);
836         if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
837             && !memcmp(v, &addr, l)) {
838             r = 1;
839             break;
840         }
841     }
842     GENERAL_NAMES_free(alt);
843     return r;
844 }
845
846 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
847     int loc, l;
848     char *v, *s;
849     X509_NAME *nm;
850     X509_NAME_ENTRY *e;
851     ASN1_STRING *t;
852
853     nm = X509_get_subject_name(cert);
854     loc = -1;
855     for (;;) {
856         loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
857         if (loc == -1)
858             break;
859         e = X509_NAME_get_entry(nm, loc);
860         t = X509_NAME_ENTRY_get_data(e);
861         v = (char *) ASN1_STRING_data(t);
862         l = ASN1_STRING_length(t);
863         if (l < 0)
864             continue;
865         if (exact) {
866             if (l == strlen(exact) && !strncasecmp(exact, v, l))
867                 return 1;
868         } else {
869             s = stringcopy((char *)v, l);
870             if (!s) {
871                 debug(DBG_ERR, "malloc failed");
872                 continue;
873             }
874             if (regexec(regex, s, 0, NULL, 0)) {
875                 free(s);
876                 continue;
877             }
878             free(s);
879             return 1;
880         }
881     }
882     return 0;
883 }
884
885 int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
886     int loc, i, l, n, r = 0;
887     char *s, *v;
888     X509_EXTENSION *ex;
889     STACK_OF(GENERAL_NAME) *alt;
890     GENERAL_NAME *gn;
891     
892     debug(DBG_DBG, "subjectaltnameregexp");
893     
894     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
895     if (loc < 0)
896         return r;
897     
898     ex = X509_get_ext(cert, loc);
899     alt = X509V3_EXT_d2i(ex);
900     if (!alt)
901         return r;
902     
903     n = sk_GENERAL_NAME_num(alt);
904     for (i = 0; i < n; i++) {
905         gn = sk_GENERAL_NAME_value(alt, i);
906         if (gn->type != type)
907             continue;
908         r = -1;
909         v = (char *)ASN1_STRING_data(gn->d.ia5);
910         l = ASN1_STRING_length(gn->d.ia5);
911         if (l <= 0)
912             continue;
913 #ifdef DEBUG
914         printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
915 #endif  
916         if (exact) {
917             if (memcmp(v, exact, l))
918                 continue;
919         } else {
920             s = stringcopy((char *)v, l);
921             if (!s) {
922                 debug(DBG_ERR, "malloc failed");
923                 continue;
924             }
925             if (regexec(regex, s, 0, NULL, 0)) {
926                 free(s);
927                 continue;
928             }
929             free(s);
930         }
931         r = 1;
932         break;
933     }
934     GENERAL_NAMES_free(alt);
935     return r;
936 }
937
938 X509 *verifytlscert(SSL *ssl) {
939     X509 *cert;
940     unsigned long error;
941     
942     if (SSL_get_verify_result(ssl) != X509_V_OK) {
943         debug(DBG_ERR, "verifytlscert: basic validation failed");
944         while ((error = ERR_get_error()))
945             debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
946         return NULL;
947     }
948
949     cert = SSL_get_peer_certificate(ssl);
950     if (!cert)
951         debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
952     return cert;
953 }
954     
955 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
956     int r;
957     uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
958     struct in6_addr addr;
959     
960     if (conf->certnamecheck && conf->prefixlen == 255) {
961         if (inet_pton(AF_INET, conf->host, &addr))
962             type = AF_INET;
963         else if (inet_pton(AF_INET6, conf->host, &addr))
964             type = AF_INET6;
965
966         r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
967         if (r) {
968             if (r < 0) {
969                 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
970                 return 0;
971             }
972             debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
973         } else {
974             if (!cnregexp(cert, conf->host, NULL)) {
975                 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
976                 return 0;
977             }           
978             debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
979         }
980     }
981     if (conf->certcnregex) {
982         if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
983             debug(DBG_WARN, "verifyconfcert: CN not matching regex");
984             return 0;
985         }
986         debug(DBG_DBG, "verifyconfcert: CN matching regex");
987     }
988     if (conf->certuriregex) {
989         if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
990             debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
991             return 0;
992         }
993         debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
994     }
995     return 1;
996 }
997
998 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
999     struct timeval now;
1000     time_t elapsed;
1001     X509 *cert;
1002     unsigned long error;
1003     
1004     debug(DBG_DBG, "tlsconnect: called from %s", text);
1005     pthread_mutex_lock(&server->lock);
1006     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1007         /* already reconnected, nothing to do */
1008         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
1009         pthread_mutex_unlock(&server->lock);
1010         return 1;
1011     }
1012
1013     for (;;) {
1014         gettimeofday(&now, NULL);
1015         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1016         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1017             debug(DBG_DBG, "tlsconnect: timeout");
1018             if (server->sock >= 0)
1019                 close(server->sock);
1020             SSL_free(server->ssl);
1021             server->ssl = NULL;
1022             pthread_mutex_unlock(&server->lock);
1023             return 0;
1024         }
1025         if (server->connectionok) {
1026             server->connectionok = 0;
1027             sleep(2);
1028         } else if (elapsed < 1)
1029             sleep(2);
1030         else if (elapsed < 60) {
1031             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
1032             sleep(elapsed);
1033         } else if (elapsed < 100000) {
1034             debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
1035             sleep(60);
1036         } else
1037             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
1038         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
1039         if (server->sock >= 0)
1040             close(server->sock);
1041         if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1042             debug(DBG_ERR, "tlsconnect: connecttcp failed");
1043             continue;
1044         }
1045         
1046         SSL_free(server->ssl);
1047         server->ssl = SSL_new(server->conf->ssl_ctx);
1048         SSL_set_fd(server->ssl, server->sock);
1049         if (SSL_connect(server->ssl) <= 0) {
1050             while ((error = ERR_get_error()))
1051                 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
1052             continue;
1053         }
1054         cert = verifytlscert(server->ssl);
1055         if (!cert)
1056             continue;
1057         if (verifyconfcert(cert, server->conf)) {
1058             X509_free(cert);
1059             break;
1060         }
1061         X509_free(cert);
1062     }
1063     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1064     gettimeofday(&server->lastconnecttry, NULL);
1065     pthread_mutex_unlock(&server->lock);
1066     return 1;
1067 }
1068
1069 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1070     struct timeval now;
1071     time_t elapsed;
1072     
1073     debug(DBG_DBG, "tcpconnect: called from %s", text);
1074     pthread_mutex_lock(&server->lock);
1075     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1076         /* already reconnected, nothing to do */
1077         debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1078         pthread_mutex_unlock(&server->lock);
1079         return 1;
1080     }
1081
1082     for (;;) {
1083         gettimeofday(&now, NULL);
1084         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1085         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1086             debug(DBG_DBG, "tcpconnect: timeout");
1087             if (server->sock >= 0)
1088                 close(server->sock);
1089             pthread_mutex_unlock(&server->lock);
1090             return 0;
1091         }
1092         if (server->connectionok) {
1093             server->connectionok = 0;
1094             sleep(2);
1095         } else if (elapsed < 1)
1096             sleep(2);
1097         else if (elapsed < 60) {
1098             debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1099             sleep(elapsed);
1100         } else if (elapsed < 100000) {
1101             debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1102             sleep(60);
1103         } else
1104             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
1105         debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1106         if (server->sock >= 0)
1107             close(server->sock);
1108         if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1109             break;
1110         debug(DBG_ERR, "tcpconnect: connecttcp failed");
1111     }
1112     debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1113     gettimeofday(&server->lastconnecttry, NULL);
1114     pthread_mutex_unlock(&server->lock);
1115     return 1;
1116 }
1117
1118 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1119 /* returns 0 on timeout, -1 on error and num if ok */
1120 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1121     int s, ndesc, cnt, len;
1122     fd_set readfds, writefds;
1123     struct timeval timer;
1124     
1125     s = SSL_get_fd(ssl);
1126     if (s < 0)
1127         return -1;
1128     /* make socket non-blocking? */
1129     for (len = 0; len < num; len += cnt) {
1130         FD_ZERO(&readfds);
1131         FD_SET(s, &readfds);
1132         writefds = readfds;
1133         if (timeout) {
1134             timer.tv_sec = timeout;
1135             timer.tv_usec = 0;
1136         }
1137         ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1138         if (ndesc < 1)
1139             return ndesc;
1140
1141         cnt = SSL_read(ssl, buf + len, num - len);
1142         if (cnt <= 0)
1143             switch (SSL_get_error(ssl, cnt)) {
1144             case SSL_ERROR_WANT_READ:
1145             case SSL_ERROR_WANT_WRITE:
1146                 cnt = 0;
1147                 continue;
1148             case SSL_ERROR_ZERO_RETURN:
1149                 /* remote end sent close_notify, send one back */
1150                 SSL_shutdown(ssl);
1151                 return -1;
1152             default:
1153                 return -1;
1154             }
1155     }
1156     return num;
1157 }
1158
1159 /* timeout in seconds, 0 means no timeout (blocking) */
1160 unsigned char *radtlsget(SSL *ssl, int timeout) {
1161     int cnt, len;
1162     unsigned char buf[4], *rad;
1163
1164     for (;;) {
1165         cnt = sslreadtimeout(ssl, buf, 4, timeout);
1166         if (cnt < 1) {
1167             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1168             return NULL;
1169         }
1170
1171         len = RADLEN(buf);
1172         rad = malloc(len);
1173         if (!rad) {
1174             debug(DBG_ERR, "radtlsget: malloc failed");
1175             continue;
1176         }
1177         memcpy(rad, buf, 4);
1178         
1179         cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1180         if (cnt < 1) {
1181             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1182             free(rad);
1183             return NULL;
1184         }
1185         
1186         if (len >= 20)
1187             break;
1188         
1189         free(rad);
1190         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1191     }
1192     
1193     debug(DBG_DBG, "radtlsget: got %d bytes", len);
1194     return rad;
1195 }
1196
1197 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1198 /* returns 0 on timeout, -1 on error and num if ok */
1199 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1200     int ndesc, cnt, len;
1201     fd_set readfds, writefds;
1202     struct timeval timer;
1203     
1204     if (s < 0)
1205         return -1;
1206     /* make socket non-blocking? */
1207     for (len = 0; len < num; len += cnt) {
1208         FD_ZERO(&readfds);
1209         FD_SET(s, &readfds);
1210         writefds = readfds;
1211         if (timeout) {
1212             timer.tv_sec = timeout;
1213             timer.tv_usec = 0;
1214         }
1215         ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1216         if (ndesc < 1)
1217             return ndesc;
1218
1219         cnt = read(s, buf + len, num - len);
1220         if (cnt <= 0)
1221             return -1;
1222     }
1223     return num;
1224 }
1225
1226 /* timeout in seconds, 0 means no timeout (blocking) */
1227 unsigned char *radtcpget(int s, int timeout) {
1228     int cnt, len;
1229     unsigned char buf[4], *rad;
1230
1231     for (;;) {
1232         cnt = tcpreadtimeout(s, buf, 4, timeout);
1233         if (cnt < 1) {
1234             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1235             return NULL;
1236         }
1237
1238         len = RADLEN(buf);
1239         rad = malloc(len);
1240         if (!rad) {
1241             debug(DBG_ERR, "radtcpget: malloc failed");
1242             continue;
1243         }
1244         memcpy(rad, buf, 4);
1245         
1246         cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1247         if (cnt < 1) {
1248             debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1249             free(rad);
1250             return NULL;
1251         }
1252         
1253         if (len >= 20)
1254             break;
1255         
1256         free(rad);
1257         debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1258     }
1259     
1260     debug(DBG_DBG, "radtcpget: got %d bytes", len);
1261     return rad;
1262 }
1263
1264 int clientradputudp(struct server *server, unsigned char *rad) {
1265     size_t len;
1266     struct sockaddr_storage sa;
1267     struct sockaddr *sap;
1268     struct clsrvconf *conf = server->conf;
1269     in_port_t *port = NULL;
1270     
1271     len = RADLEN(rad);
1272     
1273     if (*rad == RAD_Accounting_Request) {
1274         sap = (struct sockaddr *)&sa;
1275         memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1276     } else
1277         sap = conf->addrinfo->ai_addr;
1278     
1279     switch (sap->sa_family) {
1280     case AF_INET:
1281         port = &((struct sockaddr_in *)sap)->sin_port;
1282         break;
1283     case AF_INET6:
1284         port = &((struct sockaddr_in6 *)sap)->sin6_port;
1285         break;
1286     default:
1287         return 0;
1288     }
1289
1290     if (*rad == RAD_Accounting_Request)
1291         *port = htons(ntohs(*port) + 1);
1292     
1293     if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1294         debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1295         return 1;
1296     }
1297
1298     debug(DBG_WARN, "clientradputudp: send failed");
1299     return 0;
1300 }
1301
1302 int clientradputtls(struct server *server, unsigned char *rad) {
1303     int cnt;
1304     size_t len;
1305     unsigned long error;
1306     struct timeval lastconnecttry;
1307     struct clsrvconf *conf = server->conf;
1308     
1309     len = RADLEN(rad);
1310     lastconnecttry = server->lastconnecttry;
1311     while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1312         while ((error = ERR_get_error()))
1313             debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1314         if (server->dynamiclookuparg)
1315             return 0;
1316         tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1317         lastconnecttry = server->lastconnecttry;
1318     }
1319
1320     server->connectionok = 1;
1321     debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1322     return 1;
1323 }
1324
1325 int clientradputtcp(struct server *server, unsigned char *rad) {
1326     int cnt;
1327     size_t len;
1328     struct timeval lastconnecttry;
1329     struct clsrvconf *conf = server->conf;
1330     
1331     len = RADLEN(rad);
1332     lastconnecttry = server->lastconnecttry;
1333     while ((cnt = write(server->sock, rad, len)) <= 0) {
1334         debug(DBG_ERR, "clientradputtcp: write error");
1335         tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1336         lastconnecttry = server->lastconnecttry;
1337     }
1338
1339     server->connectionok = 1;
1340     debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1341     return 1;
1342 }
1343
1344 int radsign(unsigned char *rad, unsigned char *sec) {
1345     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1346     static unsigned char first = 1;
1347     static EVP_MD_CTX mdctx;
1348     unsigned int md_len;
1349     int result;
1350     
1351     pthread_mutex_lock(&lock);
1352     if (first) {
1353         EVP_MD_CTX_init(&mdctx);
1354         first = 0;
1355     }
1356
1357     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1358         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1359         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1360         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1361         md_len == 16);
1362     pthread_mutex_unlock(&lock);
1363     return result;
1364 }
1365
1366 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1367     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1368     static unsigned char first = 1;
1369     static EVP_MD_CTX mdctx;
1370     unsigned char hash[EVP_MAX_MD_SIZE];
1371     unsigned int len;
1372     int result;
1373     
1374     pthread_mutex_lock(&lock);
1375     if (first) {
1376         EVP_MD_CTX_init(&mdctx);
1377         first = 0;
1378     }
1379
1380     len = RADLEN(rad);
1381     
1382     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1383               EVP_DigestUpdate(&mdctx, rad, 4) &&
1384               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1385               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1386               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1387               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1388               len == 16 &&
1389               !memcmp(hash, rad + 4, 16));
1390     pthread_mutex_unlock(&lock);
1391     return result;
1392 }
1393               
1394 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1395     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1396     static unsigned char first = 1;
1397     static HMAC_CTX hmacctx;
1398     unsigned int md_len;
1399     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1400     
1401     pthread_mutex_lock(&lock);
1402     if (first) {
1403         HMAC_CTX_init(&hmacctx);
1404         first = 0;
1405     }
1406
1407     memcpy(auth, authattr, 16);
1408     memset(authattr, 0, 16);
1409     md_len = 0;
1410     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1411     HMAC_Update(&hmacctx, rad, RADLEN(rad));
1412     HMAC_Final(&hmacctx, hash, &md_len);
1413     memcpy(authattr, auth, 16);
1414     if (md_len != 16) {
1415         debug(DBG_WARN, "message auth computation failed");
1416         pthread_mutex_unlock(&lock);
1417         return 0;
1418     }
1419
1420     if (memcmp(auth, hash, 16)) {
1421         debug(DBG_WARN, "message authenticator, wrong value");
1422         pthread_mutex_unlock(&lock);
1423         return 0;
1424     }   
1425         
1426     pthread_mutex_unlock(&lock);
1427     return 1;
1428 }
1429
1430 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1431     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1432     static unsigned char first = 1;
1433     static HMAC_CTX hmacctx;
1434     unsigned int md_len;
1435
1436     if (!authattrval)
1437         return 1;
1438     
1439     pthread_mutex_lock(&lock);
1440     if (first) {
1441         HMAC_CTX_init(&hmacctx);
1442         first = 0;
1443     }
1444
1445     memset(authattrval, 0, 16);
1446     md_len = 0;
1447     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1448     HMAC_Update(&hmacctx, rad, RADLEN(rad));
1449     HMAC_Final(&hmacctx, authattrval, &md_len);
1450     if (md_len != 16) {
1451         debug(DBG_WARN, "message auth computation failed");
1452         pthread_mutex_unlock(&lock);
1453         return 0;
1454     }
1455
1456     pthread_mutex_unlock(&lock);
1457     return 1;
1458 }
1459
1460 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1461     while (length > 1) {
1462         if (ATTRTYPE(attrs) == type)
1463             return attrs;
1464         length -= ATTRLEN(attrs);
1465         attrs += ATTRLEN(attrs);
1466     }
1467     return NULL;
1468 }
1469
1470 void freerqdata(struct request *rq) {
1471     if (rq->origusername)
1472         free(rq->origusername);
1473     if (rq->buf)
1474         free(rq->buf);
1475 }
1476
1477 void sendrq(struct server *to, struct request *rq) {
1478     int i;
1479     uint8_t *attr;
1480
1481     pthread_mutex_lock(&to->newrq_mutex);
1482     /* might simplify if only try nextid, might be ok */
1483     for (i = to->nextid; i < MAX_REQUESTS; i++)
1484         if (!to->requests[i].buf)
1485             break;
1486     if (i == MAX_REQUESTS) {
1487         for (i = 0; i < to->nextid; i++)
1488             if (!to->requests[i].buf)
1489                 break;
1490         if (i == to->nextid) {
1491             debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1492             freerqdata(rq);
1493             goto exit;
1494         }
1495     }
1496     
1497     rq->buf[1] = (char)i;
1498
1499     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1500     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1501         freerqdata(rq);
1502         goto exit;
1503     }
1504     
1505     if (*rq->buf == RAD_Accounting_Request) {
1506         if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1507             debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1508             freerqdata(rq);
1509             goto exit;
1510         }
1511     }
1512
1513     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1514     to->requests[i] = *rq;
1515     to->nextid = i + 1;
1516
1517     if (!to->newrq) {
1518         to->newrq = 1;
1519         debug(DBG_DBG, "sendrq: signalling client writer");
1520         pthread_cond_signal(&to->newrq_cond);
1521     }
1522  exit:
1523     pthread_mutex_unlock(&to->newrq_mutex);
1524 }
1525
1526 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1527     struct reply *reply;
1528     uint8_t first;
1529     
1530     if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1531         free(buf);
1532         debug(DBG_WARN, "sendreply: failed to sign message");
1533         return;
1534     }
1535
1536     reply = malloc(sizeof(struct reply));
1537     if (!reply) {
1538         free(buf);
1539         debug(DBG_ERR, "sendreply: malloc failed");
1540         return;
1541     }
1542     memset(reply, 0, sizeof(struct reply));
1543     reply->buf = buf;
1544     if (tosa)
1545         reply->tosa = *tosa;
1546     reply->toudpsock = toudpsock;
1547     
1548     pthread_mutex_lock(&to->replyq->mutex);
1549
1550     first = list_first(to->replyq->entries) == NULL;
1551     
1552     if (!list_push(to->replyq->entries, reply)) {
1553         pthread_mutex_unlock(&to->replyq->mutex);
1554         free(reply);
1555         free(buf);
1556         debug(DBG_ERR, "sendreply: malloc failed");
1557         return;
1558     }
1559     
1560     if (first) {
1561         debug(DBG_DBG, "signalling server writer");
1562         pthread_cond_signal(&to->replyq->cond);
1563     }
1564     pthread_mutex_unlock(&to->replyq->mutex);
1565 }
1566
1567 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1568     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1569     static unsigned char first = 1;
1570     static EVP_MD_CTX mdctx;
1571     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1572     unsigned int md_len;
1573     uint8_t i, offset = 0, out[128];
1574     
1575     pthread_mutex_lock(&lock);
1576     if (first) {
1577         EVP_MD_CTX_init(&mdctx);
1578         first = 0;
1579     }
1580
1581     input = auth;
1582     for (;;) {
1583         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1584             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1585             !EVP_DigestUpdate(&mdctx, input, 16) ||
1586             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1587             md_len != 16) {
1588             pthread_mutex_unlock(&lock);
1589             return 0;
1590         }
1591         for (i = 0; i < 16; i++)
1592             out[offset + i] = hash[i] ^ in[offset + i];
1593         input = out + offset - 16;
1594         offset += 16;
1595         if (offset == len)
1596             break;
1597     }
1598     memcpy(in, out, len);
1599     pthread_mutex_unlock(&lock);
1600     return 1;
1601 }
1602
1603 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1604     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1605     static unsigned char first = 1;
1606     static EVP_MD_CTX mdctx;
1607     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1608     unsigned int md_len;
1609     uint8_t i, offset = 0, out[128];
1610     
1611     pthread_mutex_lock(&lock);
1612     if (first) {
1613         EVP_MD_CTX_init(&mdctx);
1614         first = 0;
1615     }
1616
1617     input = auth;
1618     for (;;) {
1619         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1620             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1621             !EVP_DigestUpdate(&mdctx, input, 16) ||
1622             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1623             md_len != 16) {
1624             pthread_mutex_unlock(&lock);
1625             return 0;
1626         }
1627         for (i = 0; i < 16; i++)
1628             out[offset + i] = hash[i] ^ in[offset + i];
1629         input = in + offset;
1630         offset += 16;
1631         if (offset == len)
1632             break;
1633     }
1634     memcpy(in, out, len);
1635     pthread_mutex_unlock(&lock);
1636     return 1;
1637 }
1638
1639 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1640     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1641     static unsigned char first = 1;
1642     static EVP_MD_CTX mdctx;
1643     unsigned char hash[EVP_MAX_MD_SIZE];
1644     unsigned int md_len;
1645     uint8_t i, offset;
1646     
1647     pthread_mutex_lock(&lock);
1648     if (first) {
1649         EVP_MD_CTX_init(&mdctx);
1650         first = 0;
1651     }
1652
1653 #if 0
1654     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1655     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1656     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1657 #endif
1658     
1659     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1660         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1661         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1662         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1663         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1664         pthread_mutex_unlock(&lock);
1665         return 0;
1666     }
1667
1668 #if 0    
1669     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1670 #endif
1671     
1672     for (i = 0; i < 16; i++)
1673         text[i] ^= hash[i];
1674     
1675     for (offset = 16; offset < len; offset += 16) {
1676 #if 0   
1677         printf("text + offset - 16 c(%d): ", offset / 16);
1678         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1679 #endif
1680         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1681             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1682             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1683             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1684             md_len != 16) {
1685             pthread_mutex_unlock(&lock);
1686             return 0;
1687         }
1688 #if 0
1689         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1690 #endif    
1691         
1692         for (i = 0; i < 16; i++)
1693             text[offset + i] ^= hash[i];
1694     }
1695     
1696 #if 0
1697     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1698 #endif
1699
1700     pthread_mutex_unlock(&lock);
1701     return 1;
1702 }
1703
1704 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1705     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1706     static unsigned char first = 1;
1707     static EVP_MD_CTX mdctx;
1708     unsigned char hash[EVP_MAX_MD_SIZE];
1709     unsigned int md_len;
1710     uint8_t i, offset;
1711     char plain[255];
1712     
1713     pthread_mutex_lock(&lock);
1714     if (first) {
1715         EVP_MD_CTX_init(&mdctx);
1716         first = 0;
1717     }
1718
1719 #if 0
1720     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1721     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1722     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1723 #endif
1724     
1725     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1726         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1727         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1728         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1729         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1730         pthread_mutex_unlock(&lock);
1731         return 0;
1732     }
1733
1734 #if 0    
1735     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1736 #endif
1737     
1738     for (i = 0; i < 16; i++)
1739         plain[i] = text[i] ^ hash[i];
1740     
1741     for (offset = 16; offset < len; offset += 16) {
1742 #if 0   
1743         printf("text + offset - 16 c(%d): ", offset / 16);
1744         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1745 #endif
1746         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1747             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1748             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1749             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1750             md_len != 16) {
1751             pthread_mutex_unlock(&lock);
1752             return 0;
1753         }
1754 #if 0
1755         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1756 #endif    
1757
1758         for (i = 0; i < 16; i++)
1759             plain[offset + i] = text[offset + i] ^ hash[i];
1760     }
1761
1762     memcpy(text, plain, len);
1763 #if 0
1764     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1765 #endif
1766
1767     pthread_mutex_unlock(&lock);
1768     return 1;
1769 }
1770
1771 struct realm *id2realm(struct list *realmlist, char *id) {
1772     struct list_node *entry;
1773     struct realm *realm, *subrealm = NULL;
1774
1775     /* need to do locking for subrealms and check subrealm timers */
1776     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1777         realm = (struct realm *)entry->data;
1778         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1779             pthread_mutex_lock(&realm->subrealms_mutex);
1780             if (realm->subrealms)
1781                 subrealm = id2realm(realm->subrealms, id);
1782             pthread_mutex_unlock(&realm->subrealms_mutex);
1783             return subrealm ? subrealm : realm;
1784         }
1785     }
1786     return NULL;
1787 }
1788
1789 /* helper function, only used by removeserversubrealms() */
1790 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1791     struct list_node *entry;
1792     struct realm *realm;
1793     
1794     for (entry = list_first(realmlist); entry;) {
1795         realm = (struct realm *)entry->data;
1796         entry = list_next(entry);
1797         if (realm->srvconfs) {
1798             list_removedata(realm->srvconfs, srv);
1799             if (!list_first(realm->srvconfs)) {
1800                 list_destroy(realm->srvconfs);
1801                 realm->srvconfs = NULL;
1802             }
1803         }
1804         if (realm->accsrvconfs) {
1805             list_removedata(realm->accsrvconfs, srv);
1806             if (!list_first(realm->accsrvconfs)) {
1807                 list_destroy(realm->accsrvconfs);
1808                 realm->accsrvconfs = NULL;
1809             }
1810         }
1811
1812         /* remove subrealm if no servers */
1813         if (!realm->srvconfs && !realm->accsrvconfs) {
1814             list_removedata(realmlist, realm);
1815             freerealm(realm);
1816         }
1817     }
1818 }
1819
1820 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1821     struct list_node *entry;
1822     struct realm *realm;
1823     
1824     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1825         realm = (struct realm *)entry->data;
1826         pthread_mutex_lock(&realm->subrealms_mutex);
1827         if (realm->subrealms) {
1828             _internal_removeserversubrealms(realm->subrealms, srv);
1829             if (!list_first(realm->subrealms)) {
1830                 list_destroy(realm->subrealms);
1831                 realm->subrealms = NULL;
1832             }
1833         }
1834         pthread_mutex_unlock(&realm->subrealms_mutex);
1835     }
1836 }
1837                         
1838 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1839     struct request *rq = to->requests, *end;
1840     
1841     pthread_mutex_lock(&to->newrq_mutex);
1842     for (end = rq + MAX_REQUESTS; rq < end; rq++)
1843         if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1844             break;
1845     pthread_mutex_unlock(&to->newrq_mutex);
1846     
1847     return rq < end;
1848 }
1849
1850 int attrvalidate(unsigned char *attrs, int length) {
1851     while (length > 1) {
1852         if (ATTRLEN(attrs) < 2) {
1853             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1854             return 0;
1855         }
1856         length -= ATTRLEN(attrs);
1857         if (length < 0) {
1858             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1859             return 0;
1860         }
1861         attrs += ATTRLEN(attrs);
1862     }
1863     if (length)
1864         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1865     return 1;
1866 }
1867
1868 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1869     if (len < 16 || len > 128 || len % 16) {
1870         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1871         return 0;
1872     }
1873         
1874     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1875         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1876         return 0;
1877     }
1878 #ifdef DEBUG
1879     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1880 #endif  
1881     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1882         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1883         return 0;
1884     }
1885     return 1;
1886 }
1887
1888 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1889     if (len < 18)
1890         return 0;
1891     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1892         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1893         return 0;
1894     }
1895     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1896         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1897         return 0;
1898     }
1899     return 1;
1900 }
1901
1902 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1903            char *oldsecret, char *newsecret) {
1904     unsigned char *attr;
1905     
1906     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1907         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1908         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1909             return 0;
1910     }
1911     return 1;
1912 }
1913
1914 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1915     if (!attrs)
1916         return 0;
1917     
1918     for (; attrs[0]; attrs += 2)
1919         if (attrs[0] == vendor && attrs[1] == subattr)
1920             return 1;
1921     return 0;
1922 }
1923
1924 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1925     uint8_t alen, sublen, rmlen = 0;
1926     uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1927     uint8_t *subattrs;
1928     
1929     if (!removevendorattrs)
1930         return 0;
1931
1932     while (*removevendorattrs && *removevendorattrs != vendor)
1933         removevendorattrs += 2;
1934     if (!*removevendorattrs)
1935         return 0;
1936     
1937     alen = ATTRLEN(attrs);
1938
1939     if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1940         /* remove entire vendor attribute */
1941         memmove(attrs, attrs + alen, length - alen);
1942         return alen;
1943     }
1944
1945     sublen = alen - 4;
1946     subattrs = ATTRVAL(attrs) + 4;
1947     
1948     if (!attrvalidate(subattrs, sublen)) {
1949         debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1950         return 0;
1951     }
1952
1953     length -= 6;
1954     while (sublen > 1) {
1955         alen = ATTRLEN(subattrs);
1956         sublen -= alen;
1957         length -= alen;
1958         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1959             memmove(subattrs, subattrs + alen, length);
1960             rmlen += alen;
1961         } else
1962             subattrs += alen;
1963     }
1964
1965     ATTRLEN(attrs) -= rmlen;
1966     return rmlen;
1967 }
1968
1969 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1970     uint8_t *attrs, alen;
1971     uint16_t len, rmlen = 0;
1972     
1973     if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1974         return;
1975
1976     len = RADLEN(buf) - 20;
1977     attrs = buf + 20;
1978     while (len > 1) {
1979         alen = ATTRLEN(attrs);
1980         len -= alen;
1981         if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1982             memmove(attrs, attrs + alen, len);
1983             rmlen += alen;
1984         } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1985             rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1986         else
1987             attrs += alen;
1988     }
1989     if (rmlen)
1990         ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1991 }
1992
1993 /* returns a pointer to the resized attribute value */
1994 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1995     uint8_t *attrs, *attr, vallen;
1996     uint16_t len;
1997     unsigned char *new;
1998     
1999     len = RADLEN(*buf) - 20;
2000     attrs = *buf + 20;
2001
2002     attr = attrget(attrs, len, type);
2003     if (!attr)
2004         return NULL;
2005     
2006     vallen = ATTRVALLEN(attr);
2007     if (vallen == newvallen)
2008         return attr + 2;
2009
2010     len += newvallen - vallen;
2011     if (newvallen > vallen) {
2012         new = realloc(*buf, len + 20);
2013         if (!new) {
2014             debug(DBG_ERR, "resizeattr: malloc failed");
2015             return NULL;
2016         }
2017         if (new != *buf) {
2018             attr += new - *buf;
2019             attrs = new + 20;
2020             *buf = new;
2021         }
2022     }
2023     memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
2024     attr[1] = newvallen + 2;
2025     ((uint16_t *)*buf)[1] = htons(len + 20);
2026     return attr + 2;
2027 }
2028                 
2029 int rewriteusername(struct request *rq, char *in) {
2030     size_t nmatch = 10, reslen = 0, start = 0;
2031     regmatch_t pmatch[10], *pfield;
2032     int i;
2033     unsigned char *result;
2034     char *out = rq->from->conf->rewriteattrreplacement;
2035     
2036     if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
2037         debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
2038         return 1;
2039     }
2040     
2041     rq->origusername = stringcopy(in, 0);
2042     if (!rq->origusername)
2043         return 0;
2044     
2045     for (i = start; out[i]; i++) {
2046         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2047             pfield = &pmatch[out[i + 1] - '0'];
2048             if (pfield->rm_so >= 0) {
2049                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2050                 start = i + 2;
2051             }
2052             i++;
2053         }
2054     }
2055     reslen += i - start;
2056
2057     result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2058     if (!result)
2059         return 0;
2060     
2061     start = 0;
2062     reslen = 0;
2063     for (i = start; out[i]; i++) {
2064         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2065             pfield = &pmatch[out[i + 1] - '0'];
2066             if (pfield->rm_so >= 0) {
2067                 memcpy(result + reslen, out + start, i - start);
2068                 reslen += i - start;
2069                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2070                 reslen += pfield->rm_eo - pfield->rm_so;
2071                 start = i + 2;
2072             }
2073             i++;
2074         }
2075     }
2076
2077     memcpy(result + reslen, out + start, i - start);
2078     reslen += i - start;
2079     memcpy(in, result, reslen);
2080     in[reslen] = '\0';
2081     return 1;
2082 }
2083
2084 const char *radmsgtype2string(uint8_t code) {
2085     static const char *rad_msg_names[] = {
2086         "", "Access-Request", "Access-Accept", "Access-Reject",
2087         "Accounting-Request", "Accounting-Response", "", "",
2088         "", "", "", "Access-Challenge",
2089         "Status-Server", "Status-Client"
2090     };
2091     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2092 }
2093
2094 void char2hex(char *h, unsigned char c) {
2095     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2096                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2097     h[0] = hexdigits[c / 16];
2098     h[1] = hexdigits[c % 16];
2099     return;
2100 }
2101
2102 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2103     int i, l;
2104     char *s, *d;
2105
2106     if (!attr || len == 1) {
2107         *ascii = '\0';
2108         return ascii;
2109     }
2110
2111     l = ATTRVALLEN(attr);
2112     s = (char *)ATTRVAL(attr);
2113     d = ascii;
2114
2115     for (i = 0; i < l; i++) {
2116         if (s[i] > 31 && s[i] < 127) {
2117             *d++ = s[i];
2118             if (d - ascii == len - 1)
2119                 break;
2120         } else {
2121             if (d - ascii > len - 4)
2122                 break;
2123             *d++ = '%';
2124             char2hex(d, s[i]);
2125             d += 2;
2126             if (d - ascii == len - 1)
2127                 break;
2128         }
2129     }
2130     *d = '\0';
2131     return ascii;
2132 }
2133
2134 void acclog(unsigned char *attrs, int length, char *host) {
2135     unsigned char *attr;
2136     char username[760];
2137     
2138     attr = attrget(attrs, length, RAD_Attr_User_Name);
2139     if (!attr) {
2140         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2141         return;
2142     }
2143     radattr2ascii(username, sizeof(username), attr);
2144     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2145 }
2146         
2147 void respondaccounting(struct request *rq) {
2148     unsigned char *resp;
2149
2150     resp = malloc(20);
2151     if (!resp) {
2152         debug(DBG_ERR, "respondaccounting: malloc failed");
2153         return;
2154     }
2155     memcpy(resp, rq->buf, 20);
2156     resp[0] = RAD_Accounting_Response;
2157     resp[2] = 0;
2158     resp[3] = 20;
2159     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2160     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2161 }
2162
2163 void respondstatusserver(struct request *rq) {
2164     unsigned char *resp;
2165
2166     resp = malloc(20);
2167     if (!resp) {
2168         debug(DBG_ERR, "respondstatusserver: malloc failed");
2169         return;
2170     }
2171     memcpy(resp, rq->buf, 20);
2172     resp[0] = RAD_Access_Accept;
2173     resp[2] = 0;
2174     resp[3] = 20;
2175     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2176     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2177 }
2178
2179 void respondreject(struct request *rq, char *message) {
2180     unsigned char *resp;
2181     int len = 20;
2182
2183     if (message && *message)
2184         len += 2 + strlen(message);
2185     
2186     resp = malloc(len);
2187     if (!resp) {
2188         debug(DBG_ERR, "respondreject: malloc failed");
2189         return;
2190     }
2191     memcpy(resp, rq->buf, 20);
2192     resp[0] = RAD_Access_Reject;
2193     *(uint16_t *)(resp + 2) = htons(len);
2194     if (message && *message) {
2195         resp[20] = RAD_Attr_Reply_Message;
2196         resp[21] = len - 20;
2197         memcpy(resp + 22, message, len - 22);
2198     }
2199     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2200 }
2201
2202 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2203     struct list_node *entry;
2204     struct clsrvconf *server, *best = NULL, *first = NULL;
2205
2206     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2207         server = (struct clsrvconf *)entry->data;
2208         if (!server->servers)
2209             return server;
2210         if (!first)
2211             first = server;
2212         if (!server->servers->connectionok)
2213             continue;
2214         if (!server->servers->lostrqs)
2215             return server;
2216         if (!best) {
2217             best = server;
2218             continue;
2219         }
2220         if (server->servers->lostrqs < best->servers->lostrqs)
2221             best = server;
2222     }
2223     return best ? best : first;
2224 }
2225
2226 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2227     struct clsrvconf *srvconf;
2228     
2229     *realm = id2realm(realms, id);
2230     if (!*realm)
2231         return NULL;
2232     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2233     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2234     if (!srvconf)
2235         return NULL;
2236     if (!acc && !srvconf->servers)
2237         adddynamicrealmserver(*realm, srvconf, id);
2238     return srvconf->servers;
2239 }
2240
2241 /* returns 0 if validation/authentication fails, else 1 */
2242 int radsrv(struct request *rq) {
2243     uint8_t code, id, *auth, *attrs, *attr;
2244     uint16_t len;
2245     struct server *to = NULL;
2246     char username[254], userascii[760];
2247     unsigned char newauth[16];
2248     struct realm *realm = NULL;
2249     
2250     code = *(uint8_t *)rq->buf;
2251     id = *(uint8_t *)(rq->buf + 1);
2252     len = RADLEN(rq->buf);
2253     auth = (uint8_t *)(rq->buf + 4);
2254
2255     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2256     
2257     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2258         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2259         goto exit;
2260     }
2261
2262     len -= 20;
2263     attrs = rq->buf + 20;
2264
2265     if (!attrvalidate(attrs, len)) {
2266         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2267         goto errvalauth;
2268     }
2269
2270     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2271     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2272         debug(DBG_WARN, "radsrv: message authentication failed");
2273         goto errvalauth;
2274     }
2275
2276     if (code == RAD_Status_Server) {
2277         respondstatusserver(rq);
2278         goto exit;
2279     }
2280     
2281     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2282
2283     if (code == RAD_Accounting_Request) {
2284         memset(newauth, 0, 16);
2285         if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2286             debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2287             goto errvalauth;
2288         }
2289     }
2290     
2291     if (rq->from->conf->rewrite) {
2292         dorewrite(rq->buf, rq->from->conf->rewrite);
2293         len = RADLEN(rq->buf) - 20;
2294     }
2295     
2296     attr = attrget(attrs, len, RAD_Attr_User_Name);
2297     if (!attr) {
2298         if (code == RAD_Accounting_Request) {
2299             acclog(attrs, len, rq->from->conf->host);
2300             respondaccounting(rq);
2301         } else
2302             debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2303         goto exit;
2304     }
2305     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2306     username[ATTRVALLEN(attr)] = '\0';
2307     radattr2ascii(userascii, sizeof(userascii), attr);
2308
2309     if (rq->from->conf->rewriteattrregex) {
2310         if (!rewriteusername(rq, username)) {
2311             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2312             goto exit;
2313         }
2314         len = RADLEN(rq->buf) - 20;
2315         auth = (uint8_t *)(rq->buf + 4);
2316         attrs = rq->buf + 20;
2317     }
2318
2319     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2320     
2321     to = findserver(&realm, username, code == RAD_Accounting_Request);
2322     if (!realm) {
2323         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2324         goto exit;
2325     }
2326     if (!to) {
2327         if (realm->message && code == RAD_Access_Request) {
2328             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2329             respondreject(rq, realm->message);
2330         } else if (realm->accresp && code == RAD_Accounting_Request) {
2331             acclog(attrs, len, rq->from->conf->host);
2332             respondaccounting(rq);
2333         }
2334         goto exit;
2335     }
2336     
2337     if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2338         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2339               rq->from->conf->name, to->conf->name);
2340         goto exit;
2341     }
2342
2343     if (rqinqueue(to, rq->from, id, code)) {
2344         debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2345               radmsgtype2string(code), rq->from->conf->host, id);
2346         goto exit;
2347     }
2348     
2349     if (code != RAD_Accounting_Request) {
2350         if (!RAND_bytes(newauth, 16)) {
2351             debug(DBG_WARN, "radsrv: failed to generate random auth");
2352             goto exit;
2353         }
2354     }
2355
2356 #ifdef DEBUG
2357     printfchars(NULL, "auth", "%02x ", auth, 16);
2358 #endif
2359
2360     attr = attrget(attrs, len, RAD_Attr_User_Password);
2361     if (attr) {
2362         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2363         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2364             goto exit;
2365     }
2366     
2367     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2368     if (attr) {
2369         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2370         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2371             goto exit;
2372     }
2373
2374     rq->origid = id;
2375     memcpy(rq->origauth, auth, 16);
2376     memcpy(auth, newauth, 16);
2377     sendrq(to, rq);
2378     return 1;
2379     
2380  exit:
2381     freerqdata(rq);
2382     return 1;
2383
2384  errvalauth:
2385     freerqdata(rq);
2386     return 0;
2387 }
2388
2389 int replyh(struct server *server, unsigned char *buf) {
2390     struct client *from;
2391     struct request *rq;
2392     int i, len, sublen;
2393     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2394     struct sockaddr_storage fromsa;
2395     char tmp[760], stationid[760];
2396     
2397     server->connectionok = 1;
2398     server->lostrqs = 0;
2399         
2400     i = buf[1]; /* i is the id */
2401
2402     if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2403         && *buf != RAD_Accounting_Response) {
2404         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2405         return 0;
2406     }
2407     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2408
2409     rq = server->requests + i;
2410
2411     pthread_mutex_lock(&server->newrq_mutex);
2412     if (!rq->buf || !rq->tries) {
2413         pthread_mutex_unlock(&server->newrq_mutex);
2414         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2415         return 0;
2416     }
2417
2418     if (rq->received) {
2419         pthread_mutex_unlock(&server->newrq_mutex);
2420         debug(DBG_INFO, "replyh: already received, ignoring reply");
2421         return 0;
2422     }
2423         
2424     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2425         pthread_mutex_unlock(&server->newrq_mutex);
2426         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2427         return 0;
2428     }
2429         
2430     len = RADLEN(buf) - 20;
2431     attrs = buf + 20;
2432
2433     if (!attrvalidate(attrs, len)) {
2434         pthread_mutex_unlock(&server->newrq_mutex);
2435         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2436         return 0;
2437     }
2438         
2439     /* Message Authenticator */
2440     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2441     if (messageauth) {
2442         if (ATTRVALLEN(messageauth) != 16) {
2443             pthread_mutex_unlock(&server->newrq_mutex);
2444             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2445             return 0;
2446         }
2447         memcpy(tmp, buf + 4, 16);
2448         memcpy(buf + 4, rq->buf + 4, 16);
2449         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2450             pthread_mutex_unlock(&server->newrq_mutex);
2451             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2452             return 0;
2453         }
2454         memcpy(buf + 4, tmp, 16);
2455         debug(DBG_DBG, "replyh: message auth ok");
2456     }
2457     
2458     gettimeofday(&server->lastrcv, NULL);
2459     
2460     if (*rq->buf == RAD_Status_Server) {
2461         rq->received = 1;
2462         pthread_mutex_unlock(&server->newrq_mutex);
2463         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2464         return 0;
2465     }
2466
2467     gettimeofday(&server->lastreply, NULL);
2468     
2469     from = rq->from;
2470     if (!from) {
2471         pthread_mutex_unlock(&server->newrq_mutex);
2472         debug(DBG_INFO, "replyh: client gone, ignoring reply");
2473         return 0;
2474     }
2475         
2476     if (server->conf->rewrite) {
2477         dorewrite(buf, server->conf->rewrite);
2478         len = RADLEN(buf) - 20;
2479     }
2480     
2481     /* MS MPPE */
2482     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2483         if (ATTRVALLEN(attr) <= 4)
2484             break;
2485             
2486         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
2487             continue;
2488             
2489         sublen = ATTRVALLEN(attr) - 4;
2490         subattrs = ATTRVAL(attr) + 4;  
2491         if (!attrvalidate(subattrs, sublen) ||
2492             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2493                     rq, server->conf->secret, from->conf->secret) ||
2494             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2495                     rq, server->conf->secret, from->conf->secret))
2496             break;
2497     }
2498     if (attr) {
2499         pthread_mutex_unlock(&server->newrq_mutex);
2500         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2501         return 0;
2502     }
2503         
2504     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2505         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2506         if (attr) {
2507             radattr2ascii(tmp, sizeof(tmp), attr);
2508             attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2509             if (attr) {
2510                 radattr2ascii(stationid, sizeof(stationid), attr);
2511                 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2512                       radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2513             } else
2514                 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2515         }
2516     }
2517         
2518     buf[1] = (char)rq->origid;
2519     memcpy(buf + 4, rq->origauth, 16);
2520 #ifdef DEBUG    
2521     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2522 #endif
2523
2524     if (rq->origusername) {
2525         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2526         if (!username) {
2527             pthread_mutex_unlock(&server->newrq_mutex);
2528             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2529             return 0;
2530         }
2531         memcpy(username, rq->origusername, strlen(rq->origusername));
2532         len = RADLEN(buf) - 20;
2533         attrs = buf + 20;
2534         if (messageauth)
2535             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2536     }
2537         
2538     if (messageauth) {
2539         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2540             pthread_mutex_unlock(&server->newrq_mutex);
2541             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2542             return 0;
2543         }
2544         debug(DBG_DBG, "replyh: computed messageauthattr");
2545     }
2546
2547     fromsa = rq->fromsa; /* only needed for UDP */
2548     /* once we set received = 1, rq may be reused */
2549     rq->received = 1;
2550
2551     debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2552     sendreply(from, buf, &fromsa, rq->fromudpsock);
2553     pthread_mutex_unlock(&server->newrq_mutex);
2554     return 1;
2555 }
2556
2557 void *udpclientrd(void *arg) {
2558     struct server *server;
2559     unsigned char *buf;
2560     int *s = (int *)arg;
2561     
2562     for (;;) {
2563         server = NULL;
2564         buf = radudpget(*s, NULL, &server, NULL);
2565         if (!replyh(server, buf))
2566             free(buf);
2567     }
2568 }
2569
2570 void *tlsclientrd(void *arg) {
2571     struct server *server = (struct server *)arg;
2572     unsigned char *buf;
2573     struct timeval now, lastconnecttry;
2574     
2575     for (;;) {
2576         /* yes, lastconnecttry is really necessary */
2577         lastconnecttry = server->lastconnecttry;
2578         buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2579         if (!buf) {
2580             if (server->dynamiclookuparg)
2581                 break;
2582             tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2583             continue;
2584         }
2585
2586         if (!replyh(server, buf))
2587             free(buf);
2588         if (server->dynamiclookuparg) {
2589             gettimeofday(&now, NULL);
2590             if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2591                 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2592                 break;
2593             }
2594         }
2595     }
2596     ERR_remove_state(0);
2597     server->clientrdgone = 1;
2598     return NULL;
2599 }
2600
2601 void *tcpclientrd(void *arg) {
2602     struct server *server = (struct server *)arg;
2603     unsigned char *buf;
2604     struct timeval lastconnecttry;
2605     
2606     for (;;) {
2607         /* yes, lastconnecttry is really necessary */
2608         lastconnecttry = server->lastconnecttry;
2609         buf = radtcpget(server->sock, 0);
2610         if (!buf) {
2611             tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
2612             continue;
2613         }
2614
2615         if (!replyh(server, buf))
2616             free(buf);
2617     }
2618     server->clientrdgone = 1;
2619     return NULL;
2620 }
2621
2622 /* code for removing state not finished */
2623 void *clientwr(void *arg) {
2624     struct server *server = (struct server *)arg;
2625     struct request *rq;
2626     pthread_t clientrdth;
2627     int i, dynconffail = 0;
2628     uint8_t rnd;
2629     struct timeval now;
2630     struct timespec timeout;
2631     struct request statsrvrq;
2632     unsigned char statsrvbuf[38];
2633     struct clsrvconf *conf;
2634     
2635     conf = server->conf;
2636     
2637     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2638         dynconffail = 1;
2639         goto errexit;
2640     }
2641     
2642     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2643         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2644         goto errexit;
2645     }
2646
2647     memset(&timeout, 0, sizeof(struct timespec));
2648     
2649     if (conf->statusserver) {
2650         memset(&statsrvrq, 0, sizeof(struct request));
2651         memset(statsrvbuf, 0, sizeof(statsrvbuf));
2652         statsrvbuf[0] = RAD_Status_Server;
2653         statsrvbuf[3] = 38;
2654         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2655         statsrvbuf[21] = 18;
2656         gettimeofday(&server->lastrcv, NULL);
2657     }
2658
2659     if (conf->pdef->connecter) {
2660         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2661             goto errexit;
2662         server->connectionok = 1;
2663         if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2664             debug(DBG_ERR, "clientwr: pthread_create failed");
2665             goto errexit;
2666         }
2667     } else
2668         server->connectionok = 1;
2669     
2670     for (;;) {
2671         pthread_mutex_lock(&server->newrq_mutex);
2672         if (!server->newrq) {
2673             gettimeofday(&now, NULL);
2674             /* random 0-7 seconds */
2675             RAND_bytes(&rnd, 1);
2676             rnd /= 32;
2677             if (conf->statusserver) {
2678                 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2679                     timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2680             } else {
2681                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2682                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2683             }
2684 #if 0       
2685             if (timeout.tv_sec > now.tv_sec)
2686                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2687 #endif      
2688             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2689             timeout.tv_sec = 0;
2690         }
2691         if (server->newrq) {
2692             debug(DBG_DBG, "clientwr: got new request");
2693             server->newrq = 0;
2694         }
2695 #if 0   
2696         else
2697             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2698 #endif  
2699         pthread_mutex_unlock(&server->newrq_mutex);
2700
2701         for (i = 0; i < MAX_REQUESTS; i++) {
2702             if (server->clientrdgone) {
2703                 pthread_join(clientrdth, NULL);
2704                 goto errexit;
2705             }
2706             pthread_mutex_lock(&server->newrq_mutex);
2707             while (i < MAX_REQUESTS && !server->requests[i].buf)
2708                 i++;
2709             if (i == MAX_REQUESTS) {
2710                 pthread_mutex_unlock(&server->newrq_mutex);
2711                 break;
2712             }
2713             rq = server->requests + i;
2714
2715             if (rq->received) {
2716                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2717                 if (rq->buf) {
2718                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2719                     freerqdata(rq);
2720                     /* setting this to NULL means that it can be reused */
2721                     rq->buf = NULL;
2722                 }
2723                 pthread_mutex_unlock(&server->newrq_mutex);
2724                 continue;
2725             }
2726             
2727             gettimeofday(&now, NULL);
2728             if (now.tv_sec < rq->expiry.tv_sec) {
2729                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2730                     timeout.tv_sec = rq->expiry.tv_sec;
2731                 pthread_mutex_unlock(&server->newrq_mutex);
2732                 continue;
2733             }
2734
2735             if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2736                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2737                 if (conf->statusserver) {
2738                     if (*rq->buf == RAD_Status_Server) {
2739                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2740                         if (server->lostrqs < 255)
2741                             server->lostrqs++;
2742                     }
2743                 } else {
2744                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2745                     if (server->lostrqs < 255)
2746                         server->lostrqs++;
2747                 }
2748                 freerqdata(rq);
2749                 /* setting this to NULL means that it can be reused */
2750                 rq->buf = NULL;
2751                 pthread_mutex_unlock(&server->newrq_mutex);
2752                 continue;
2753             }
2754             pthread_mutex_unlock(&server->newrq_mutex);
2755
2756             rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2757             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2758                 timeout.tv_sec = rq->expiry.tv_sec;
2759             rq->tries++;
2760             conf->pdef->clientradput(server, server->requests[i].buf);
2761         }
2762         if (conf->statusserver) {
2763             gettimeofday(&now, NULL);
2764             if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2765                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2766                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2767                     continue;
2768                 }
2769                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2770                 if (!statsrvrq.buf) {
2771                     debug(DBG_ERR, "clientwr: malloc failed");
2772                     continue;
2773                 }
2774                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2775                 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2776                 sendrq(server, &statsrvrq);
2777             }
2778         }
2779     }
2780  errexit:
2781     conf->servers = NULL;
2782     if (server->dynamiclookuparg) {
2783         removeserversubrealms(realms, conf);
2784         if (dynconffail)
2785             free(conf);
2786         else
2787             freeclsrvconf(conf);
2788     }
2789     freeserver(server, 1);
2790     ERR_remove_state(0);
2791     return NULL;
2792 }
2793
2794 void *udpserverwr(void *arg) {
2795     struct queue *replyq = udp_server_replyq;
2796     struct reply *reply;
2797     
2798     for (;;) {
2799         pthread_mutex_lock(&replyq->mutex);
2800         while (!(reply = (struct reply *)list_shift(replyq->entries))) {
2801             debug(DBG_DBG, "udp server writer, waiting for signal");
2802             pthread_cond_wait(&replyq->cond, &replyq->mutex);
2803             debug(DBG_DBG, "udp server writer, got signal");
2804         }
2805         pthread_mutex_unlock(&replyq->mutex);
2806
2807         if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2808                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2809             debug(DBG_WARN, "sendudp: send failed");
2810         free(reply->buf);
2811         free(reply);
2812     }
2813 }
2814
2815 void *udpserverrd(void *arg) {
2816     struct request rq;
2817     int *sp = (int *)arg;
2818     
2819     for (;;) {
2820         memset(&rq, 0, sizeof(struct request));
2821         rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
2822         rq.fromudpsock = *sp;
2823         radsrv(&rq);
2824     }
2825     free(sp);
2826 }
2827
2828 void *tlsserverwr(void *arg) {
2829     int cnt;
2830     unsigned long error;
2831     struct client *client = (struct client *)arg;
2832     struct queue *replyq;
2833     struct reply *reply;
2834     
2835     debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2836     replyq = client->replyq;
2837     for (;;) {
2838         pthread_mutex_lock(&replyq->mutex);
2839         while (!list_first(replyq->entries)) {
2840             if (client->ssl) {      
2841                 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2842                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2843                 debug(DBG_DBG, "tlsserverwr: got signal");
2844             }
2845             if (!client->ssl) {
2846                 /* ssl might have changed while waiting */
2847                 pthread_mutex_unlock(&replyq->mutex);
2848                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2849                 ERR_remove_state(0);
2850                 pthread_exit(NULL);
2851             }
2852         }
2853         reply = (struct reply *)list_shift(replyq->entries);
2854         pthread_mutex_unlock(&replyq->mutex);
2855         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2856         if (cnt > 0)
2857             debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2858                   cnt, RADLEN(reply->buf));
2859         else
2860             while ((error = ERR_get_error()))
2861                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2862         free(reply->buf);
2863         free(reply);
2864     }
2865 }
2866
2867 void tlsserverrd(struct client *client) {
2868     struct request rq;
2869     pthread_t tlsserverwrth;
2870     
2871     debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2872     
2873     if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2874         debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2875         return;
2876     }
2877
2878     for (;;) {
2879         memset(&rq, 0, sizeof(struct request));
2880         rq.buf = radtlsget(client->ssl, 0);
2881         if (!rq.buf) {
2882             debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
2883             break;
2884         }
2885         debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2886         rq.from = client;
2887         if (!radsrv(&rq)) {
2888             debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
2889             break;
2890         }
2891     }
2892     
2893     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2894     client->ssl = NULL;
2895     pthread_mutex_lock(&client->replyq->mutex);
2896     pthread_cond_signal(&client->replyq->cond);
2897     pthread_mutex_unlock(&client->replyq->mutex);
2898     debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2899     pthread_join(tlsserverwrth, NULL);
2900     removeclientrqs(client);
2901     debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2902 }
2903
2904 void *tlsservernew(void *arg) {
2905     int s;
2906     struct sockaddr_storage from;
2907     size_t fromlen = sizeof(from);
2908     struct clsrvconf *conf;
2909     struct list_node *cur = NULL;
2910     SSL *ssl = NULL;
2911     X509 *cert = NULL;
2912     unsigned long error;
2913     struct client *client;
2914
2915     s = *(int *)arg;
2916     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2917         debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2918         goto exit;
2919     }
2920     debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2921
2922     conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2923     if (conf) {
2924         ssl = SSL_new(conf->ssl_ctx);
2925         SSL_set_fd(ssl, s);
2926
2927         if (SSL_accept(ssl) <= 0) {
2928             while ((error = ERR_get_error()))
2929                 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2930             debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2931             goto exit;
2932         }
2933         cert = verifytlscert(ssl);
2934         if (!cert)
2935             goto exit;
2936     }
2937     
2938     while (conf) {
2939         if (verifyconfcert(cert, conf)) {
2940             X509_free(cert);
2941             client = addclient(conf);
2942             if (client) {
2943                 client->ssl = ssl;
2944                 tlsserverrd(client);
2945                 removeclient(client);
2946             } else
2947                 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2948             goto exit;
2949         }
2950         conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2951     }
2952     debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2953     if (cert)
2954         X509_free(cert);
2955
2956  exit:
2957     SSL_free(ssl);
2958     ERR_remove_state(0);
2959     shutdown(s, SHUT_RDWR);
2960     close(s);
2961     pthread_exit(NULL);
2962 }
2963
2964 void *tlslistener(void *arg) {
2965     pthread_t tlsserverth;
2966     int s, *sp = (int *)arg;
2967     struct sockaddr_storage from;
2968     size_t fromlen = sizeof(from);
2969
2970     listen(*sp, 0);
2971
2972     for (;;) {
2973         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
2974         if (s < 0) {
2975             debug(DBG_WARN, "accept failed");
2976             continue;
2977         }
2978         if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2979             debug(DBG_ERR, "tlslistener: pthread_create failed");
2980             shutdown(s, SHUT_RDWR);
2981             close(s);
2982             continue;
2983         }
2984         pthread_detach(tlsserverth);
2985     }
2986     free(sp);
2987     return NULL;
2988 }
2989
2990 void *tcpserverwr(void *arg) {
2991     int cnt;
2992     struct client *client = (struct client *)arg;
2993     struct queue *replyq;
2994     struct reply *reply;
2995     
2996     debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
2997     replyq = client->replyq;
2998     for (;;) {
2999         pthread_mutex_lock(&replyq->mutex);
3000         while (!list_first(replyq->entries)) {
3001             if (client->sock >= 0) {        
3002                 debug(DBG_DBG, "tcpserverwr: waiting for signal");
3003                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
3004                 debug(DBG_DBG, "tcpserverwr: got signal");
3005             }
3006             if (client->sock < 0) {
3007                 /* s might have changed while waiting */
3008                 pthread_mutex_unlock(&replyq->mutex);
3009                 debug(DBG_DBG, "tcpserverwr: exiting as requested");
3010                 pthread_exit(NULL);
3011             }
3012         }
3013         reply = (struct reply *)list_shift(replyq->entries);
3014         pthread_mutex_unlock(&replyq->mutex);
3015         cnt = write(client->sock, reply->buf, RADLEN(reply->buf));
3016         if (cnt > 0)
3017             debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
3018                   cnt, RADLEN(reply->buf));
3019         else
3020             debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
3021         free(reply->buf);
3022         free(reply);
3023     }
3024 }
3025
3026 void tcpserverrd(struct client *client) {
3027     struct request rq;
3028     pthread_t tcpserverwrth;
3029     
3030     debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
3031     
3032     if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
3033         debug(DBG_ERR, "tcpserverrd: pthread_create failed");
3034         return;
3035     }
3036
3037     for (;;) {
3038         memset(&rq, 0, sizeof(struct request));
3039         rq.buf = radtcpget(client->sock, 0);
3040         if (!rq.buf) {
3041             debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
3042             break;
3043         }
3044         debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
3045         rq.from = client;
3046         if (!radsrv(&rq)) {
3047             debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3048             break;
3049         }
3050     }
3051
3052     /* stop writer by setting s to -1 and give signal in case waiting for data */
3053     client->sock = -1;
3054     pthread_mutex_lock(&client->replyq->mutex);
3055     pthread_cond_signal(&client->replyq->cond);
3056     pthread_mutex_unlock(&client->replyq->mutex);
3057     debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3058     pthread_join(tcpserverwrth, NULL);
3059     removeclientrqs(client);
3060     debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3061 }
3062
3063 void *tcpservernew(void *arg) {
3064     int s;
3065     struct sockaddr_storage from;
3066     size_t fromlen = sizeof(from);
3067     struct clsrvconf *conf;
3068     struct client *client;
3069
3070     s = *(int *)arg;
3071     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3072         debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3073         goto exit;
3074     }
3075     debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3076
3077     conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3078     if (conf) {
3079         client = addclient(conf);
3080         if (client) {
3081             client->sock = s;
3082             tcpserverrd(client);
3083             removeclient(client);
3084         } else
3085             debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3086     } else
3087         debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3088
3089  exit:
3090     shutdown(s, SHUT_RDWR);
3091     close(s);
3092     pthread_exit(NULL);
3093 }
3094
3095 void *tcplistener(void *arg) {
3096     pthread_t tcpserverth;
3097     int s, *sp = (int *)arg;
3098     struct sockaddr_storage from;
3099     size_t fromlen = sizeof(from);
3100
3101     listen(*sp, 0);
3102
3103     for (;;) {
3104         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3105         if (s < 0) {
3106             debug(DBG_WARN, "accept failed");
3107             continue;
3108         }
3109         if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3110             debug(DBG_ERR, "tcplistener: pthread_create failed");
3111             shutdown(s, SHUT_RDWR);
3112             close(s);
3113             continue;
3114         }
3115         pthread_detach(tcpserverth);
3116     }
3117     free(sp);
3118     return NULL;
3119 }
3120
3121 void createlistener(uint8_t type, char *arg) {
3122     pthread_t th;
3123     struct clsrvconf *listenres;
3124     struct addrinfo *res;
3125     int s = -1, on = 1, *sp = NULL;
3126     
3127     listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3128     if (!listenres)
3129         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3130     
3131     for (res = listenres->addrinfo; res; res = res->ai_next) {
3132         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3133         if (s < 0) {
3134             debug(DBG_WARN, "createlistener: socket failed");
3135             continue;
3136         }
3137         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3138 #ifdef IPV6_V6ONLY
3139         if (res->ai_family == AF_INET6)
3140             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3141 #endif          
3142         if (bind(s, res->ai_addr, res->ai_addrlen)) {
3143             debug(DBG_WARN, "createlistener: bind failed");
3144             close(s);
3145             s = -1;
3146             continue;
3147         }
3148
3149         sp = malloc(sizeof(int));
3150         if (!sp)
3151             debugx(1, DBG_ERR, "malloc failed");
3152         *sp = s;
3153         if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
3154             debugx(1, DBG_ERR, "pthread_create failed");
3155         pthread_detach(th);
3156     }
3157     if (!sp)
3158         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3159     
3160     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
3161           listenres->host ? listenres->host : "*", listenres->port);
3162     freeclsrvres(listenres);
3163 }
3164
3165 void createlisteners(uint8_t type, char **args) {
3166     int i;
3167
3168     if (args)
3169         for (i = 0; args[i]; i++)
3170             createlistener(type, args[i]);
3171     else
3172         createlistener(type, NULL);
3173 }
3174
3175 #ifdef DEBUG
3176 void ssl_info_callback(const SSL *ssl, int where, int ret) {
3177     const char *s;
3178     int w;
3179
3180     w = where & ~SSL_ST_MASK;
3181
3182     if (w & SSL_ST_CONNECT)
3183         s = "SSL_connect";
3184     else if (w & SSL_ST_ACCEPT)
3185         s = "SSL_accept";
3186     else
3187         s = "undefined";
3188
3189     if (where & SSL_CB_LOOP)
3190         debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
3191     else if (where & SSL_CB_ALERT) {
3192         s = (where & SSL_CB_READ) ? "read" : "write";
3193         debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
3194     }
3195     else if (where & SSL_CB_EXIT) {
3196         if (ret == 0)
3197             debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
3198         else if (ret < 0)
3199             debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
3200     }
3201 }
3202 #endif
3203
3204 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
3205     SSL_CTX *ctx = NULL;
3206     STACK_OF(X509_NAME) *calist;
3207     X509_STORE *x509_s;
3208     int i;
3209     unsigned long error;
3210
3211     if (!ssl_locks) {
3212         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3213         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3214         for (i = 0; i < CRYPTO_num_locks(); i++) {
3215             ssl_lock_count[i] = 0;
3216             pthread_mutex_init(&ssl_locks[i], NULL);
3217         }
3218         CRYPTO_set_id_callback(ssl_thread_id);
3219         CRYPTO_set_locking_callback(ssl_locking_callback);
3220
3221         SSL_load_error_strings();
3222         SSL_library_init();
3223
3224         while (!RAND_status()) {
3225             time_t t = time(NULL);
3226             pid_t pid = getpid();
3227             RAND_seed((unsigned char *)&t, sizeof(time_t));
3228             RAND_seed((unsigned char *)&pid, sizeof(pid));
3229         }
3230     }
3231
3232     switch (type) {
3233     case RAD_TLS:
3234         ctx = SSL_CTX_new(TLSv1_method());
3235 #ifdef DEBUG    
3236         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
3237 #endif  
3238         break;
3239     case RAD_DTLS:
3240         ctx = SSL_CTX_new(DTLSv1_method());
3241 #ifdef DEBUG    
3242         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
3243 #endif  
3244         SSL_CTX_set_read_ahead(ctx, 1);
3245         break;
3246     }
3247     if (!ctx) {
3248         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3249         return NULL;
3250     }
3251     
3252     if (conf->certkeypwd) {
3253         SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
3254         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3255     }
3256     if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
3257         !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
3258         !SSL_CTX_check_private_key(ctx) ||
3259         !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
3260         while ((error = ERR_get_error()))
3261             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3262         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3263         SSL_CTX_free(ctx);
3264         return NULL;
3265     }
3266
3267     calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
3268     if (!conf->cacertfile || calist) {
3269         if (conf->cacertpath) {
3270             if (!calist)
3271                 calist = sk_X509_NAME_new_null();
3272             if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
3273                 sk_X509_NAME_free(calist);
3274                 calist = NULL;
3275             }
3276         }
3277     }
3278     if (!calist) {
3279         while ((error = ERR_get_error()))
3280             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3281         debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
3282         SSL_CTX_free(ctx);
3283         return NULL;
3284     }
3285     ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
3286     SSL_CTX_set_client_CA_list(ctx, calist);
3287     
3288     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3289     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3290
3291     if (conf->crlcheck) {
3292         x509_s = SSL_CTX_get_cert_store(ctx);
3293         X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3294     }
3295
3296     debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
3297     return ctx;
3298 }
3299
3300 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
3301     struct list_node *entry;
3302     struct tls *t, *t1 = NULL, *t2 = NULL;
3303     SSL_CTX *ctx = NULL;
3304     
3305     pthread_mutex_lock(&tlsconfs_lock);
3306     
3307     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3308         t = (struct tls *)entry->data;
3309         if (!strcasecmp(t->name, alt1)) {
3310             t1 = t;
3311             break;
3312         }
3313         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3314             t2 = t;
3315     }
3316
3317     t = (t1 ? t1 : t2);
3318     if (!t)
3319         goto exit;
3320
3321     switch (type) {
3322     case RAD_TLS:
3323         if (!t->tlsctx)
3324             t->tlsctx = tlscreatectx(RAD_TLS, t);
3325         ctx = t->tlsctx;
3326         break;
3327     case RAD_DTLS:
3328         if (!t->dtlsctx)
3329             t->dtlsctx = tlscreatectx(RAD_DTLS, t);
3330         ctx = t->dtlsctx;
3331         break;
3332     }
3333     
3334  exit:
3335     pthread_mutex_unlock(&tlsconfs_lock);
3336     return ctx;
3337 }
3338
3339 struct list *addsrvconfs(char *value, char **names) {
3340     struct list *conflist;
3341     int n;
3342     struct list_node *entry;
3343     struct clsrvconf *conf = NULL;
3344     
3345     if (!names || !*names)
3346         return NULL;
3347     
3348     conflist = list_create();
3349     if (!conflist) {
3350         debug(DBG_ERR, "malloc failed");
3351         return NULL;
3352     }
3353
3354     for (n = 0; names[n]; n++) {
3355         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3356             conf = (struct clsrvconf *)entry->data;
3357             if (!strcasecmp(names[n], conf->name))
3358                 break;
3359         }
3360         if (!entry) {
3361             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3362             list_destroy(conflist);
3363             return NULL;
3364         }
3365         if (!list_push(conflist, conf)) {
3366             debug(DBG_ERR, "malloc failed");
3367             list_destroy(conflist);
3368             return NULL;
3369         }
3370         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3371     }
3372     return conflist;
3373 }
3374
3375 void freerealm(struct realm *realm) {
3376     if (!realm)
3377         return;
3378     free(realm->name);
3379     free(realm->message);
3380     regfree(&realm->regex);
3381     pthread_mutex_destroy(&realm->subrealms_mutex);
3382     if (realm->subrealms)
3383         list_destroy(realm->subrealms);
3384     if (realm->srvconfs) {
3385         /* emptying list without freeing data */
3386         while (list_shift(realm->srvconfs));
3387         list_destroy(realm->srvconfs);
3388     }
3389     if (realm->accsrvconfs) {
3390         /* emptying list without freeing data */
3391         while (list_shift(realm->accsrvconfs));
3392         list_destroy(realm->accsrvconfs);
3393     }
3394     free(realm);
3395 }
3396
3397 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3398     int n;
3399     struct realm *realm;
3400     char *s, *regex = NULL;
3401     
3402     if (*value == '/') {
3403         /* regexp, remove optional trailing / if present */
3404         if (value[strlen(value) - 1] == '/')
3405             value[strlen(value) - 1] = '\0';
3406     } else {
3407         /* not a regexp, let us make it one */
3408         if (*value == '*' && !value[1])
3409             regex = stringcopy(".*", 0);
3410         else {
3411             for (n = 0, s = value; *s;)
3412                 if (*s++ == '.')
3413                     n++;
3414             regex = malloc(strlen(value) + n + 3);
3415             if (regex) {
3416                 regex[0] = '@';
3417                 for (n = 1, s = value; *s; s++) {
3418                     if (*s == '.')
3419                         regex[n++] = '\\';
3420                     regex[n++] = *s;
3421                 }
3422                 regex[n++] = '$';
3423                 regex[n] = '\0';
3424             }
3425         }
3426         if (!regex) {
3427             debug(DBG_ERR, "malloc failed");
3428             realm = NULL;
3429             goto exit;
3430         }
3431         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3432     }
3433
3434     realm = malloc(sizeof(struct realm));
3435     if (!realm) {
3436         debug(DBG_ERR, "malloc failed");
3437         goto exit;
3438     }
3439     memset(realm, 0, sizeof(struct realm));
3440     
3441     if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3442         debug(DBG_ERR, "mutex init failed");
3443         free(realm);
3444         realm = NULL;
3445         goto exit;
3446     }
3447
3448     realm->name = stringcopy(value, 0);
3449     if (!realm->name) {
3450         debug(DBG_ERR, "malloc failed");
3451         goto errexit;
3452     }
3453     if (message && strlen(message) > 253) {
3454         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3455         goto errexit;
3456     }
3457     realm->message = message;
3458     realm->accresp = accresp;
3459     
3460     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3461         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3462         goto errexit;
3463     }
3464     
3465     if (servers && *servers) {
3466         realm->srvconfs = addsrvconfs(value, servers);
3467         if (!realm->srvconfs)
3468             goto errexit;
3469     }
3470     
3471     if (accservers && *accservers) {
3472         realm->accsrvconfs = addsrvconfs(value, accservers);
3473         if (!realm->accsrvconfs)
3474             goto errexit;
3475     }
3476
3477     if (!list_push(realmlist, realm)) {
3478         debug(DBG_ERR, "malloc failed");
3479         pthread_mutex_destroy(&realm->subrealms_mutex);
3480         goto errexit;
3481     }
3482     
3483     debug(DBG_DBG, "addrealm: added realm %s", value);
3484     goto exit;
3485
3486  errexit:
3487     freerealm(realm);
3488     realm = NULL;
3489     
3490  exit:
3491     free(regex);
3492     if (servers) {
3493         for (n = 0; servers[n]; n++)
3494             free(servers[n]);
3495         free(servers);
3496     }
3497     if (accservers) {
3498         for (n = 0; accservers[n]; n++)
3499             free(accservers[n]);
3500         free(accservers);
3501     }
3502     return realm;
3503 }
3504
3505 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3506     struct clsrvconf *srvconf;
3507     struct realm *newrealm = NULL;
3508     char *realmname, *s;
3509     pthread_t clientth;
3510     
3511     if (!conf->dynamiclookupcommand)
3512         return;
3513
3514     /* create dynamic for the realm (string after last @, exit if nothing after @ */
3515     realmname = strrchr(id, '@');
3516     if (!realmname)
3517         return;
3518     realmname++;
3519     if (!*realmname)
3520         return;
3521     for (s = realmname; *s; s++)
3522         if (*s != '.' && *s != '-' && !isalnum((int)*s))
3523             return;
3524     
3525     pthread_mutex_lock(&realm->subrealms_mutex);
3526     /* exit if we now already got a matching subrealm */
3527     if (id2realm(realm->subrealms, id))
3528         goto exit;
3529     srvconf = malloc(sizeof(struct clsrvconf));
3530     if (!srvconf) {
3531         debug(DBG_ERR, "malloc failed");
3532         goto exit;
3533     }
3534     *srvconf = *conf;
3535     if (!addserver(srvconf))
3536         goto errexit;
3537
3538     if (!realm->subrealms)
3539         realm->subrealms = list_create();
3540     if (!realm->subrealms)
3541         goto errexit;
3542     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3543     if (!newrealm)
3544         goto errexit;
3545
3546     /* add server and accserver to newrealm */
3547     newrealm->srvconfs = list_create();
3548     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3549         debug(DBG_ERR, "malloc failed");
3550         goto errexit;
3551     }
3552     newrealm->accsrvconfs = list_create();
3553     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3554         debug(DBG_ERR, "malloc failed");
3555         goto errexit;
3556     }
3557
3558     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3559
3560     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3561         debug(DBG_ERR, "pthread_create failed");
3562         goto errexit;
3563     }
3564     pthread_detach(clientth);
3565     goto exit;
3566     
3567  errexit:
3568     if (newrealm) {
3569         list_removedata(realm->subrealms, newrealm);
3570         freerealm(newrealm);
3571         if (!list_first(realm->subrealms)) {
3572             list_destroy(realm->subrealms);
3573             realm->subrealms = NULL;
3574         }
3575     }
3576     freeserver(srvconf->servers, 1);
3577     free(srvconf);
3578     debug(DBG_ERR, "failed to create dynamic server");
3579
3580  exit:
3581     pthread_mutex_unlock(&realm->subrealms_mutex);
3582 }
3583
3584 int dynamicconfig(struct server *server) {
3585     int ok, fd[2], status;
3586     pid_t pid;
3587     struct clsrvconf *conf = server->conf;
3588     struct gconffile *cf = NULL;
3589     
3590     /* for now we only learn hostname/address */
3591     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3592
3593     if (pipe(fd) > 0) {
3594         debug(DBG_ERR, "dynamicconfig: pipe error");
3595         goto errexit;
3596     }
3597     pid = fork();
3598     if (pid < 0) {
3599         debug(DBG_ERR, "dynamicconfig: fork error");
3600         close(fd[0]);
3601         close(fd[1]);
3602         goto errexit;
3603     } else if (pid == 0) {
3604         /* child */
3605         close(fd[0]);
3606         if (fd[1] != STDOUT_FILENO) {
3607             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3608                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3609             close(fd[1]);
3610         }
3611         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3612             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3613     }
3614
3615     close(fd[1]);
3616     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3617     ok = getgenericconfig(&cf, NULL,
3618                           "Server", CONF_CBK, confserver_cb, (void *)conf,
3619                           NULL
3620                           );
3621     freegconf(&cf);
3622         
3623     if (waitpid(pid, &status, 0) < 0) {
3624         debug(DBG_ERR, "dynamicconfig: wait error");
3625         goto errexit;
3626     }
3627     
3628     if (status) {
3629         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3630         goto errexit;
3631     }
3632
3633     if (ok)
3634         return 1;
3635
3636  errexit:    
3637     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3638     return 0;
3639 }
3640
3641 int addmatchcertattr(struct clsrvconf *conf) {
3642     char *v;
3643     regex_t **r;
3644     
3645     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3646         r = &conf->certcnregex;
3647         v = conf->matchcertattr + 4;
3648     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3649         r = &conf->certuriregex;
3650         v = conf->matchcertattr + 20;
3651     } else
3652         return 0;
3653     if (!*v)
3654         return 0;
3655     /* regexp, remove optional trailing / if present */
3656     if (v[strlen(v) - 1] == '/')
3657         v[strlen(v) - 1] = '\0';
3658     if (!*v)
3659         return 0;
3660
3661     *r = malloc(sizeof(regex_t));
3662     if (!*r) {
3663         debug(DBG_ERR, "malloc failed");
3664         return 0;
3665     }
3666     if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3667         free(*r);
3668         *r = NULL;
3669         debug(DBG_ERR, "failed to compile regular expression %s", v);
3670         return 0;
3671     }
3672     return 1;
3673 }
3674
3675 int addrewriteattr(struct clsrvconf *conf) {
3676     char *v, *w;
3677     
3678     v = conf->rewriteattr + 11;
3679     if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3680         return 0;
3681     /* regexp, remove optional trailing / if present */
3682     if (v[strlen(v) - 1] == '/')
3683         v[strlen(v) - 1] = '\0';
3684
3685     w = strchr(v, '/');
3686     if (!*w)
3687         return 0;
3688     *w = '\0';
3689     w++;
3690     
3691     conf->rewriteattrregex = malloc(sizeof(regex_t));
3692     if (!conf->rewriteattrregex) {
3693         debug(DBG_ERR, "malloc failed");
3694         return 0;
3695     }
3696
3697     conf->rewriteattrreplacement = stringcopy(w, 0);
3698     if (!conf->rewriteattrreplacement) {
3699         free(conf->rewriteattrregex);
3700         conf->rewriteattrregex = NULL;
3701         return 0;
3702     }
3703     
3704     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3705         free(conf->rewriteattrregex);
3706         conf->rewriteattrregex = NULL;
3707         free(conf->rewriteattrreplacement);
3708         conf->rewriteattrreplacement = NULL;
3709         debug(DBG_ERR, "failed to compile regular expression %s", v);
3710         return 0;
3711     }
3712
3713     return 1;
3714 }
3715
3716 /* should accept both names and numeric values, only numeric right now */
3717 uint8_t attrname2val(char *attrname) {
3718     int val = 0;
3719     
3720     val = atoi(attrname);
3721     return val > 0 && val < 256 ? val : 0;
3722 }
3723
3724 /* should accept both names and numeric values, only numeric right now */
3725 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3726     char *s;
3727     
3728     *vendor = atoi(attrname);
3729     s = strchr(attrname, ':');
3730     if (!s) {
3731         *type = -1;
3732         return 1;
3733     }
3734     *type = atoi(s + 1);
3735     return *type >= 0 && *type < 256;
3736 }
3737
3738 struct rewrite *getrewrite(char *alt1, char *alt2) {
3739     struct list_node *entry;
3740     struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3741     
3742     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3743         r = (struct rewriteconf *)entry->data;
3744         if (!strcasecmp(r->name, alt1)) {
3745             r1 = r;
3746             break;
3747         }
3748         if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3749             r2 = r;
3750     }
3751
3752     r = (r1 ? r1 : r2);
3753     if (!r)
3754         return NULL;
3755     return r->rewrite;
3756 }
3757
3758 void addrewrite(char *value, char **attrs, char **vattrs) {
3759     struct rewriteconf *new;
3760     struct rewrite *rewrite = NULL;
3761     int i, n;
3762     uint8_t *a = NULL;
3763     uint32_t *p, *va = NULL;
3764
3765     if (attrs) {
3766         n = 0;
3767         for (; attrs[n]; n++);
3768         a = malloc((n + 1) * sizeof(uint8_t));
3769         if (!a)
3770             debugx(1, DBG_ERR, "malloc failed");
3771     
3772         for (i = 0; i < n; i++) {
3773             if (!(a[i] = attrname2val(attrs[i])))
3774                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3775             free(attrs[i]);
3776         }
3777         free(attrs);
3778         a[i] = 0;
3779     }
3780     
3781     if (vattrs) {
3782         n = 0;
3783         for (; vattrs[n]; n++);
3784         va = malloc((2 * n + 1) * sizeof(uint32_t));
3785         if (!va)
3786             debugx(1, DBG_ERR, "malloc failed");
3787     
3788         for (p = va, i = 0; i < n; i++, p += 2) {
3789             if (!vattrname2val(vattrs[i], p, p + 1))
3790                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3791             free(vattrs[i]);
3792         }
3793         free(vattrs);
3794         *p = 0;
3795     }
3796     
3797     if (a || va) {
3798         rewrite = malloc(sizeof(struct rewrite));
3799         if (!rewrite)
3800             debugx(1, DBG_ERR, "malloc failed");
3801         rewrite->removeattrs = a;
3802         rewrite->removevendorattrs = va;
3803     }
3804     
3805     new = malloc(sizeof(struct rewriteconf));
3806     if (!new || !list_push(rewriteconfs, new))
3807         debugx(1, DBG_ERR, "malloc failed");
3808
3809     memset(new, 0, sizeof(struct rewriteconf));
3810     new->name = stringcopy(value, 0);
3811     if (!new->name)
3812         debugx(1, DBG_ERR, "malloc failed");
3813         
3814     new->rewrite = rewrite;
3815     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3816 }
3817
3818 void freeclsrvconf(struct clsrvconf *conf) {
3819     free(conf->name);
3820     free(conf->host);
3821     free(conf->port);
3822     free(conf->secret);
3823     free(conf->tls);
3824     free(conf->matchcertattr);
3825     if (conf->certcnregex)
3826         regfree(conf->certcnregex);
3827     if (conf->certuriregex)
3828         regfree(conf->certuriregex);
3829     free(conf->confrewrite);
3830     free(conf->rewriteattr);
3831     if (conf->rewriteattrregex)
3832         regfree(conf->rewriteattrregex);
3833     free(conf->rewriteattrreplacement);
3834     free(conf->dynamiclookupcommand);
3835     free(conf->rewrite);
3836     if (conf->addrinfo)
3837         freeaddrinfo(conf->addrinfo);
3838     /* not touching ssl_ctx, clients and servers */
3839     free(conf);
3840 }
3841
3842 int mergeconfstring(char **dst, char **src) {
3843     char *t;
3844     
3845     if (*src) {
3846         *dst = *src;
3847         *src = NULL;
3848         return 1;
3849     }
3850     if (*dst) {
3851         t = stringcopy(*dst, 0);
3852         if (!t) {
3853             debug(DBG_ERR, "malloc failed");
3854             return 0;
3855         }
3856         *dst = t;
3857     }
3858     return 1;
3859 }
3860
3861 /* assumes dst is a shallow copy */
3862 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3863     if (!mergeconfstring(&dst->name, &src->name) ||
3864         !mergeconfstring(&dst->host, &src->host) ||
3865         !mergeconfstring(&dst->port, &src->port) ||
3866         !mergeconfstring(&dst->secret, &src->secret) ||
3867         !mergeconfstring(&dst->tls, &src->tls) ||
3868         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3869         !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3870         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3871         return 0;
3872     if (src->pdef)
3873         dst->pdef = src->pdef;
3874     dst->statusserver = src->statusserver;
3875     dst->certnamecheck = src->certnamecheck;
3876     if (src->retryinterval != 255)
3877         dst->retryinterval = src->retryinterval;
3878     if (src->retrycount != 255)
3879         dst->retrycount = src->retrycount;
3880     return 1;
3881 }
3882
3883 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3884     struct clsrvconf *conf;
3885     char *conftype = NULL;
3886     
3887     debug(DBG_DBG, "confclient_cb called for %s", block);
3888
3889     conf = malloc(sizeof(struct clsrvconf));
3890     if (!conf || !list_push(clconfs, conf))
3891         debugx(1, DBG_ERR, "malloc failed");
3892     memset(conf, 0, sizeof(struct clsrvconf));
3893     conf->certnamecheck = 1;
3894     
3895     if (!getgenericconfig(cf, block,
3896                      "type", CONF_STR, &conftype,
3897                      "host", CONF_STR, &conf->host,
3898                      "secret", CONF_STR, &conf->secret,
3899                      "tls", CONF_STR, &conf->tls,
3900                      "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3901                      "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3902                      "rewrite", CONF_STR, &conf->confrewrite,
3903                      "rewriteattribute", CONF_STR, &conf->rewriteattr,
3904                      NULL
3905                           ))
3906         debugx(1, DBG_ERR, "configuration error");
3907     
3908     conf->name = stringcopy(val, 0);
3909     if (!conf->host)
3910         conf->host = stringcopy(val, 0);
3911     if (!conf->name || !conf->host)
3912         debugx(1, DBG_ERR, "malloc failed");
3913         
3914     if (!conftype)
3915         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3916     conf->type = protoname2int(conftype);
3917     conf->pdef = &protodefs[conf->type];
3918     if (!conf->pdef->name)
3919         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3920     free(conftype);
3921     
3922     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3923         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3924         if (!conf->ssl_ctx)
3925             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3926         if (conf->matchcertattr && !addmatchcertattr(conf))
3927             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3928     }
3929     
3930     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3931     
3932     if (conf->rewriteattr) {
3933         if (!addrewriteattr(conf))
3934             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3935     }
3936     
3937     if (!resolvepeer(conf, 0))
3938         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3939     
3940     if (!conf->secret) {
3941         if (!conf->pdef->secretdefault)
3942             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3943         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3944         if (!conf->secret)
3945             debugx(1, DBG_ERR, "malloc failed");
3946     }
3947     return 1;
3948 }
3949
3950 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3951     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3952         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3953         if (!conf->ssl_ctx) {
3954             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3955             return 0;
3956         }
3957         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3958             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3959             return 0;
3960         }
3961     }
3962
3963     if (!conf->port) {
3964         conf->port = stringcopy(conf->pdef->portdefault, 0);
3965         if (!conf->port) {
3966             debug(DBG_ERR, "malloc failed");
3967             return 0;
3968         }
3969     }
3970     
3971     if (conf->retryinterval == 255)
3972         conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3973     if (conf->retrycount == 255)
3974         conf->retrycount = protodefs[conf->type].retrycountdefault;
3975     
3976     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3977
3978     if (!conf->secret) {
3979         if (!conf->pdef->secretdefault) {
3980             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3981             return 0;
3982         }
3983         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3984         if (!conf->secret) {
3985             debug(DBG_ERR, "malloc failed");
3986             return 0;
3987         }
3988     }
3989     
3990     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3991         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3992         return 0;
3993     }
3994     return 1;
3995 }
3996                         
3997 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3998     struct clsrvconf *conf, *resconf;
3999     char *conftype = NULL;
4000     long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
4001     
4002     debug(DBG_DBG, "confserver_cb called for %s", block);
4003
4004     conf = malloc(sizeof(struct clsrvconf));
4005     if (!conf) {
4006         debug(DBG_ERR, "malloc failed");
4007         return 0;
4008     }
4009     memset(conf, 0, sizeof(struct clsrvconf));
4010     resconf = (struct clsrvconf *)arg;
4011     if (resconf) {
4012         conf->statusserver = resconf->statusserver;
4013         conf->certnamecheck = resconf->certnamecheck;
4014     } else
4015         conf->certnamecheck = 1;
4016
4017     if (!getgenericconfig(cf, block,
4018                           "type", CONF_STR, &conftype,
4019                           "host", CONF_STR, &conf->host,
4020                           "port", CONF_STR, &conf->port,
4021                           "secret", CONF_STR, &conf->secret,
4022                           "tls", CONF_STR, &conf->tls,
4023                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
4024                           "rewrite", CONF_STR, &conf->confrewrite,
4025                           "StatusServer", CONF_BLN, &conf->statusserver,
4026                           "RetryInterval", CONF_LINT, &retryinterval,
4027                           "RetryCount", CONF_LINT, &retrycount,
4028                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
4029                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
4030                           NULL
4031                           )) {
4032         debug(DBG_ERR, "configuration error");
4033         goto errexit;
4034     }
4035     
4036     conf->name = stringcopy(val, 0);
4037     if (!conf->name) {
4038         debug(DBG_ERR, "malloc failed");
4039         goto errexit;
4040     }
4041     if (!conf->host) {
4042         conf->host = stringcopy(val, 0);
4043         if (!conf->host) {
4044             debug(DBG_ERR, "malloc failed");
4045             goto errexit;
4046         }
4047     }
4048
4049     if (!conftype)
4050         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
4051     conf->type = protoname2int(conftype);
4052     conf->pdef = &protodefs[conf->type];
4053     if (!conf->pdef->name) {
4054         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
4055         free(conftype);
4056         goto errexit;
4057     }
4058     free(conftype);
4059             
4060     if (retryinterval != LONG_MIN) {
4061         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
4062             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
4063             goto errexit;
4064         }
4065         conf->retryinterval = (uint8_t)retryinterval;
4066     } else
4067         conf->retryinterval = 255;
4068     
4069     if (retrycount != LONG_MIN) {
4070         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
4071             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
4072             goto errexit;
4073         }
4074         conf->retrycount = (uint8_t)retrycount;
4075     } else
4076         conf->retrycount = 255;
4077     
4078     if (resconf) {
4079         if (!mergesrvconf(resconf, conf))
4080             goto errexit;
4081         free(conf);
4082         conf = resconf;
4083         if (conf->dynamiclookupcommand) {
4084             free(conf->dynamiclookupcommand);
4085             conf->dynamiclookupcommand = NULL;
4086         }
4087     }
4088
4089     if (resconf || !conf->dynamiclookupcommand) {
4090         if (!compileserverconfig(conf, block))
4091             goto errexit;
4092     }
4093     
4094     if (resconf)
4095         return 1;
4096         
4097     if (!list_push(srvconfs, conf)) {
4098         debug(DBG_ERR, "malloc failed");
4099         goto errexit;
4100     }
4101     return 1;
4102
4103  errexit:    
4104     freeclsrvconf(conf);
4105     return 0;
4106 }
4107
4108 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4109     char **servers = NULL, **accservers = NULL, *msg = NULL;
4110     uint8_t accresp = 0;
4111     
4112     debug(DBG_DBG, "confrealm_cb called for %s", block);
4113     
4114     if (!getgenericconfig(cf, block,
4115                      "server", CONF_MSTR, &servers,
4116                      "accountingServer", CONF_MSTR, &accservers,
4117                      "ReplyMessage", CONF_STR, &msg,
4118                      "AccountingResponse", CONF_BLN, &accresp,
4119                      NULL
4120                           ))
4121         debugx(1, DBG_ERR, "configuration error");
4122
4123     addrealm(realms, val, servers, accservers, msg, accresp);
4124     return 1;
4125 }
4126
4127 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4128     struct tls *conf;
4129     
4130     debug(DBG_DBG, "conftls_cb called for %s", block);
4131     
4132     conf = malloc(sizeof(struct tls));
4133     if (!conf) {
4134         debug(DBG_ERR, "conftls_cb: malloc failed");
4135         return 0;
4136     }
4137     memset(conf, 0, sizeof(struct tls));
4138     
4139     if (!getgenericconfig(cf, block,
4140                      "CACertificateFile", CONF_STR, &conf->cacertfile,
4141                      "CACertificatePath", CONF_STR, &conf->cacertpath,
4142                      "CertificateFile", CONF_STR, &conf->certfile,
4143                      "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
4144                      "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
4145                      "CRLCheck", CONF_BLN, &conf->crlcheck,
4146                      NULL
4147                           )) {
4148         debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
4149         goto errexit;
4150     }
4151     if (!conf->certfile || !conf->certkeyfile) {
4152         debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
4153         goto errexit;
4154     }
4155     if (!conf->cacertfile && !conf->cacertpath) {
4156         debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
4157         goto errexit;
4158     }
4159
4160     conf->name = stringcopy(val, 0);
4161     if (!conf->name) {
4162         debug(DBG_ERR, "conftls_cb: malloc failed");
4163         goto errexit;
4164     }
4165     
4166     pthread_mutex_lock(&tlsconfs_lock);
4167     if (!list_push(tlsconfs, conf)) {
4168         debug(DBG_ERR, "conftls_cb: malloc failed");
4169         pthread_mutex_unlock(&tlsconfs_lock);
4170         goto errexit;
4171     }
4172     pthread_mutex_unlock(&tlsconfs_lock);
4173             
4174     debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
4175     return 1;
4176
4177  errexit:
4178     free(conf->cacertfile);
4179     free(conf->cacertpath);
4180     free(conf->certfile);
4181     free(conf->certkeyfile);
4182     free(conf->certkeypwd);
4183     free(conf);
4184     return 0;
4185 }
4186
4187 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4188     char **attrs = NULL, **vattrs = NULL;
4189     
4190     debug(DBG_DBG, "confrewrite_cb called for %s", block);
4191     
4192     if (!getgenericconfig(cf, block,
4193                      "removeAttribute", CONF_MSTR, &attrs,
4194                      "removeVendorAttribute", CONF_MSTR, &vattrs,
4195                      NULL
4196                           ))
4197         debugx(1, DBG_ERR, "configuration error");
4198     addrewrite(val, attrs, vattrs);
4199     return 1;
4200 }
4201
4202 void getmainconfig(const char *configfile) {
4203     long int loglevel = LONG_MIN;
4204     struct gconffile *cfs;
4205
4206     cfs = openconfigfile(configfile);
4207     memset(&options, 0, sizeof(options));
4208     
4209     clconfs = list_create();
4210     if (!clconfs)
4211         debugx(1, DBG_ERR, "malloc failed");
4212     
4213     srvconfs = list_create();
4214     if (!srvconfs)
4215         debugx(1, DBG_ERR, "malloc failed");
4216     
4217     realms = list_create();
4218     if (!realms)
4219         debugx(1, DBG_ERR, "malloc failed");    
4220  
4221     tlsconfs = list_create();
4222     if (!tlsconfs)
4223         debugx(1, DBG_ERR, "malloc failed");
4224     
4225     rewriteconfs = list_create();
4226     if (!rewriteconfs)
4227         debugx(1, DBG_ERR, "malloc failed");    
4228  
4229     if (!getgenericconfig(&cfs, NULL,
4230                           "ListenUDP", CONF_MSTR, &options.listenudp,
4231                           "ListenTCP", CONF_MSTR, &options.listentcp,
4232                           "ListenTLS", CONF_MSTR, &options.listentls,
4233                           "ListenDTLS", CONF_MSTR, &options.listendtls,
4234                           "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4235                           "SourceUDP", CONF_STR, &options.sourceudp,
4236                           "SourceTCP", CONF_STR, &options.sourcetcp,
4237                           "SourceTLS", CONF_STR, &options.sourcetls,
4238                           "SourceDTLS", CONF_STR, &options.sourcedtls,
4239                           "LogLevel", CONF_LINT, &loglevel,
4240                           "LogDestination", CONF_STR, &options.logdestination,
4241                           "LoopPrevention", CONF_BLN, &options.loopprevention,
4242                           "Client", CONF_CBK, confclient_cb, NULL,
4243                           "Server", CONF_CBK, confserver_cb, NULL,
4244                           "Realm", CONF_CBK, confrealm_cb, NULL,
4245                           "TLS", CONF_CBK, conftls_cb, NULL,
4246                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4247                           NULL
4248                           ))
4249         debugx(1, DBG_ERR, "configuration error");
4250     
4251     if (loglevel != LONG_MIN) {
4252         if (loglevel < 1 || loglevel > 4)
4253             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4254         options.loglevel = (uint8_t)loglevel;
4255     }
4256 }
4257
4258 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4259     int c;
4260
4261     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4262         switch (c) {
4263         case 'c':
4264             *configfile = optarg;
4265             break;
4266         case 'd':
4267             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4268                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4269             *loglevel = *optarg - '0';
4270             break;
4271         case 'f':
4272             *foreground = 1;
4273             break;
4274         case 'p':
4275             *pretend = 1;
4276             break;
4277         case 'v':
4278                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4279         default:
4280             goto usage;
4281         }
4282     }
4283     if (!(argc - optind))
4284         return;
4285
4286  usage:
4287     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4288 }
4289
4290 #ifdef SYS_SOLARIS9
4291 int daemon(int a, int b) {
4292     int i;
4293
4294     if (fork())
4295         exit(0);
4296
4297     setsid();
4298
4299     for (i = 0; i < 3; i++) {
4300         close(i);
4301         open("/dev/null", O_RDWR);
4302     }
4303     return 1;
4304 }
4305 #endif
4306
4307 void *sighandler(void *arg) {
4308     sigset_t sigset;
4309     int sig;
4310
4311     for(;;) {
4312         sigemptyset(&sigset);
4313         sigaddset(&sigset, SIGPIPE);
4314         sigwait(&sigset, &sig);
4315         /* only get SIGPIPE right now, so could simplify below code */
4316         switch (sig) {
4317         case 0:
4318             /* completely ignoring this */
4319             break;
4320         case SIGPIPE:
4321             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4322             break;
4323         default:
4324             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4325         }
4326     }
4327 }
4328
4329 int main(int argc, char **argv) {
4330     pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth, dtlsclient4rdth, dtlsclient6rdth;
4331     sigset_t sigset;
4332     struct list_node *entry;
4333     uint8_t foreground = 0, pretend = 0, loglevel = 0;
4334     char *configfile = NULL;
4335     struct clsrvconf *srvconf;
4336     
4337     debug_init("radsecproxy");
4338     debug_set_level(DEBUG_LEVEL);
4339     pthread_mutex_init(&tlsconfs_lock, NULL);
4340     
4341     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4342     if (loglevel)
4343         debug_set_level(loglevel);
4344     getmainconfig(configfile ? configfile : CONFIG_MAIN);
4345     if (loglevel)
4346         options.loglevel = loglevel;
4347     else if (options.loglevel)
4348         debug_set_level(options.loglevel);
4349     if (!foreground)
4350         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4351     free(options.logdestination);
4352
4353     if (!list_first(clconfs))
4354         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4355     if (!list_first(realms))
4356         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4357
4358     if (pretend)
4359         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4360
4361     if (!foreground && (daemon(0, 0) < 0))
4362         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4363     
4364     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4365
4366     sigemptyset(&sigset);
4367     /* exit on all but SIGPIPE, ignore more? */
4368     sigaddset(&sigset, SIGPIPE);
4369     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4370     pthread_create(&sigth, NULL, sighandler, NULL);
4371
4372     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4373         srvconf = (struct clsrvconf *)entry->data;
4374         if (srvconf->dynamiclookupcommand)
4375             continue;
4376         if (!addserver(srvconf))
4377             debugx(1, DBG_ERR, "failed to add server");
4378         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4379                            (void *)(srvconf->servers)))
4380             debugx(1, DBG_ERR, "pthread_create failed");
4381     }
4382     /* srcprotores for UDP no longer needed */
4383     if (srcprotores[RAD_UDP]) {
4384         freeaddrinfo(srcprotores[RAD_UDP]);
4385         srcprotores[RAD_UDP] = NULL;
4386     }
4387     
4388     if (udp_client4_sock >= 0)
4389         if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4390             debugx(1, DBG_ERR, "pthread_create failed");
4391     if (udp_client6_sock >= 0)
4392         if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4393             debugx(1, DBG_ERR, "pthread_create failed");
4394     
4395     if (dtls_client4_sock >= 0)
4396         if (pthread_create(&dtlsclient4rdth, NULL, udpdtlsclientrd, (void *)&dtls_client4_sock))
4397             debugx(1, DBG_ERR, "pthread_create failed");
4398     if (dtls_client6_sock >= 0)
4399         if (pthread_create(&dtlsclient6rdth, NULL, udpdtlsclientrd, (void *)&dtls_client6_sock))
4400             debugx(1, DBG_ERR, "pthread_create failed");
4401     
4402     if (find_conf_type(RAD_TCP, clconfs, NULL))
4403         createlisteners(RAD_TCP, options.listentcp);
4404     
4405     if (find_conf_type(RAD_TLS, clconfs, NULL))
4406         createlisteners(RAD_TLS, options.listentls);
4407     
4408     if (find_conf_type(RAD_DTLS, clconfs, NULL))
4409         createlisteners(RAD_DTLS, options.listendtls);
4410     
4411     if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4412         udp_server_replyq = newqueue();
4413         if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4414             debugx(1, DBG_ERR, "pthread_create failed");
4415         createlisteners(RAD_UDP, options.listenudp);
4416         if (options.listenaccudp)
4417             createlisteners(RAD_UDP, options.listenaccudp);
4418     }
4419     
4420     /* just hang around doing nothing, anything to do here? */
4421     for (;;)
4422         sleep(1000);
4423 }