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