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