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