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