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