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