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