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