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