removing some lint warnings
[libradsec.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 /* Code contributions from:
10  *
11  * Arne Schwabe <schwabe at uni-paderborn.de>
12  */
13
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15  *              rd is responsible for init and launching wr
16  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17  *          each tlsserverrd launches tlsserverwr
18  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19  *          for init and launching rd
20  *
21  * serverrd will receive a request, processes it and puts it in the requestq of
22  *          the appropriate clientwr
23  * clientwr monitors its requestq and sends requests
24  * clientrd looks for responses, processes them and puts them in the replyq of
25  *          the peer the request came from
26  * serverwr monitors its reply and sends replies
27  *
28  * In addition to the main thread, we have:
29  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31  * For each TLS peer connecting to us there will be 2 more TLS threads
32  *       This is only for connected peers
33  * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
35 */
36
37 /* Bugs:
38  * May segfault when dtls connections go down? More testing needed
39  * Remove expired stuff from clients request list?
40  * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
41  * Useful for TCP accounting? Now we require separate server config for alt port
42  */
43
44 #include <signal.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <netdb.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include <limits.h>
51 #ifdef SYS_SOLARIS9
52 #include <fcntl.h>
53 #endif
54 #include <sys/time.h>
55 #include <sys/types.h>
56 #include <sys/select.h>
57 #include <ctype.h>
58 #include <sys/wait.h>
59 #include <arpa/inet.h>
60 #include <regex.h>
61 #include <libgen.h>
62 #include <pthread.h>
63 #include <openssl/ssl.h>
64 #include <openssl/rand.h>
65 #include <openssl/err.h>
66 #include <openssl/md5.h>
67 #include <openssl/hmac.h>
68 #include <openssl/x509v3.h>
69 #include "debug.h"
70 #include "list.h"
71 #include "hash.h"
72 #include "util.h"
73 #include "gconfig.h"
74 #include "radsecproxy.h"
75 #include "udp.h"
76 #include "tcp.h"
77 #include "tls.h"
78 #include "dtls.h"
79
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, NULL, 0, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL
176     }
177 };
178
179 uint8_t protoname2int(const char *name) {
180     uint8_t 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 = (uint8_t)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     uint8_t 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         if (rqout->rq->buf) {
946             free(rqout->rq->buf);
947             rqout->rq->buf = NULL;
948         }
949         freerq(rqout->rq);
950         rqout->rq = NULL;
951     }
952     rqout->tries = 0;
953     memset(&rqout->expiry, 0, sizeof(struct timeval));
954 }
955
956 void sendrq(struct request *rq) {
957     int i, start;
958     struct server *to;
959
960     removeclientrqs_sendrq_freeserver_lock(1);
961     to = rq->to;
962     if (!to)
963         goto errexit;
964     
965     start = to->conf->statusserver ? 1 : 0;
966     pthread_mutex_lock(&to->newrq_mutex);
967     if (start && rq->msg->code == RAD_Status_Server) {
968         pthread_mutex_lock(to->requests[0].lock);
969         if (to->requests[0].rq) {
970             pthread_mutex_unlock(to->requests[0].lock);
971             debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
972             goto errexit;
973         }
974         i = 0;
975     } else {
976         if (!to->nextid)
977             to->nextid = start;
978         /* might simplify if only try nextid, might be ok */
979         for (i = to->nextid; i < MAX_REQUESTS; i++) {
980             if (!to->requests[i].rq) {
981                 pthread_mutex_lock(to->requests[i].lock);
982                 if (!to->requests[i].rq)
983                     break;
984                 pthread_mutex_unlock(to->requests[i].lock);
985             }
986         }
987         if (i == MAX_REQUESTS) {
988             for (i = start; i < to->nextid; i++) {
989                 if (!to->requests[i].rq) {
990                     pthread_mutex_lock(to->requests[i].lock);
991                     if (!to->requests[i].rq)
992                         break;
993                     pthread_mutex_unlock(to->requests[i].lock);
994                 }
995             }
996             if (i == to->nextid) {
997                 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
998                 goto errexit;
999             }
1000         }
1001     }
1002     rq->newid = (uint8_t)i;
1003     rq->msg->id = (uint8_t)i;
1004     rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1005     if (!rq->buf) {
1006         pthread_mutex_unlock(to->requests[i].lock);
1007         debug(DBG_ERR, "sendrq: radmsg2buf failed");
1008         goto errexit;
1009     }
1010     
1011     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1012     to->requests[i].rq = rq;
1013     pthread_mutex_unlock(to->requests[i].lock);
1014     if (i >= start) /* i is not reserved for statusserver */
1015         to->nextid = i + 1;
1016
1017     if (!to->newrq) {
1018         to->newrq = 1;
1019         debug(DBG_DBG, "sendrq: signalling client writer");
1020         pthread_cond_signal(&to->newrq_cond);
1021     }
1022
1023     pthread_mutex_unlock(&to->newrq_mutex);
1024     removeclientrqs_sendrq_freeserver_lock(0);
1025     return;
1026
1027  errexit:
1028     if (rq->from)
1029         rmclientrq(rq, rq->msg->id);
1030     freerq(rq);
1031     pthread_mutex_unlock(&to->newrq_mutex);
1032     removeclientrqs_sendrq_freeserver_lock(0);
1033 }
1034
1035 void sendreply(struct request *rq) {
1036     uint8_t first;
1037     struct client *to = rq->from;
1038     
1039     if (!rq->replybuf)
1040         rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1041     radmsg_free(rq->msg);
1042     rq->msg = NULL;
1043     if (!rq->replybuf) {
1044         freerq(rq);
1045         debug(DBG_ERR, "sendreply: radmsg2buf failed");
1046         return;
1047     }
1048
1049     pthread_mutex_lock(&to->replyq->mutex);
1050     first = list_first(to->replyq->entries) == NULL;
1051     
1052     if (!list_push(to->replyq->entries, rq)) {
1053         pthread_mutex_unlock(&to->replyq->mutex);
1054         freerq(rq);
1055         debug(DBG_ERR, "sendreply: malloc failed");
1056         return;
1057     }
1058     
1059     if (first) {
1060         debug(DBG_DBG, "signalling server writer");
1061         pthread_cond_signal(&to->replyq->cond);
1062     }
1063     pthread_mutex_unlock(&to->replyq->mutex);
1064 }
1065
1066 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1067     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1068     static unsigned char first = 1;
1069     static EVP_MD_CTX mdctx;
1070     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1071     unsigned int md_len;
1072     uint8_t i, offset = 0, out[128];
1073     
1074     pthread_mutex_lock(&lock);
1075     if (first) {
1076         EVP_MD_CTX_init(&mdctx);
1077         first = 0;
1078     }
1079
1080     input = auth;
1081     for (;;) {
1082         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1083             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1084             !EVP_DigestUpdate(&mdctx, input, 16) ||
1085             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1086             md_len != 16) {
1087             pthread_mutex_unlock(&lock);
1088             return 0;
1089         }
1090         for (i = 0; i < 16; i++)
1091             out[offset + i] = hash[i] ^ in[offset + i];
1092         input = out + offset - 16;
1093         offset += 16;
1094         if (offset == len)
1095             break;
1096     }
1097     memcpy(in, out, len);
1098     pthread_mutex_unlock(&lock);
1099     return 1;
1100 }
1101
1102 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1103     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1104     static unsigned char first = 1;
1105     static EVP_MD_CTX mdctx;
1106     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1107     unsigned int md_len;
1108     uint8_t i, offset = 0, out[128];
1109     
1110     pthread_mutex_lock(&lock);
1111     if (first) {
1112         EVP_MD_CTX_init(&mdctx);
1113         first = 0;
1114     }
1115
1116     input = auth;
1117     for (;;) {
1118         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1119             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1120             !EVP_DigestUpdate(&mdctx, input, 16) ||
1121             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1122             md_len != 16) {
1123             pthread_mutex_unlock(&lock);
1124             return 0;
1125         }
1126         for (i = 0; i < 16; i++)
1127             out[offset + i] = hash[i] ^ in[offset + i];
1128         input = in + offset;
1129         offset += 16;
1130         if (offset == len)
1131             break;
1132     }
1133     memcpy(in, out, len);
1134     pthread_mutex_unlock(&lock);
1135     return 1;
1136 }
1137
1138 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1139     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1140     static unsigned char first = 1;
1141     static EVP_MD_CTX mdctx;
1142     unsigned char hash[EVP_MAX_MD_SIZE];
1143     unsigned int md_len;
1144     uint8_t i, offset;
1145     
1146     pthread_mutex_lock(&lock);
1147     if (first) {
1148         EVP_MD_CTX_init(&mdctx);
1149         first = 0;
1150     }
1151
1152 #if 0
1153     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1154     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1155     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1156 #endif
1157     
1158     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1159         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1160         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1161         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1162         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1163         pthread_mutex_unlock(&lock);
1164         return 0;
1165     }
1166
1167 #if 0    
1168     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1169 #endif
1170     
1171     for (i = 0; i < 16; i++)
1172         text[i] ^= hash[i];
1173     
1174     for (offset = 16; offset < len; offset += 16) {
1175 #if 0   
1176         printf("text + offset - 16 c(%d): ", offset / 16);
1177         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1178 #endif
1179         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1180             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1181             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1182             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1183             md_len != 16) {
1184             pthread_mutex_unlock(&lock);
1185             return 0;
1186         }
1187 #if 0
1188         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1189 #endif    
1190         
1191         for (i = 0; i < 16; i++)
1192             text[offset + i] ^= hash[i];
1193     }
1194     
1195 #if 0
1196     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1197 #endif
1198
1199     pthread_mutex_unlock(&lock);
1200     return 1;
1201 }
1202
1203 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1204     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1205     static unsigned char first = 1;
1206     static EVP_MD_CTX mdctx;
1207     unsigned char hash[EVP_MAX_MD_SIZE];
1208     unsigned int md_len;
1209     uint8_t i, offset;
1210     char plain[255];
1211     
1212     pthread_mutex_lock(&lock);
1213     if (first) {
1214         EVP_MD_CTX_init(&mdctx);
1215         first = 0;
1216     }
1217
1218 #if 0
1219     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1220     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1221     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1222 #endif
1223     
1224     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1225         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1226         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1227         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1228         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1229         pthread_mutex_unlock(&lock);
1230         return 0;
1231     }
1232
1233 #if 0    
1234     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1235 #endif
1236     
1237     for (i = 0; i < 16; i++)
1238         plain[i] = text[i] ^ hash[i];
1239     
1240     for (offset = 16; offset < len; offset += 16) {
1241 #if 0   
1242         printf("text + offset - 16 c(%d): ", offset / 16);
1243         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1244 #endif
1245         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1246             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1247             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1248             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1249             md_len != 16) {
1250             pthread_mutex_unlock(&lock);
1251             return 0;
1252         }
1253 #if 0
1254         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1255 #endif    
1256
1257         for (i = 0; i < 16; i++)
1258             plain[offset + i] = text[offset + i] ^ hash[i];
1259     }
1260
1261     memcpy(text, plain, len);
1262 #if 0
1263     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1264 #endif
1265
1266     pthread_mutex_unlock(&lock);
1267     return 1;
1268 }
1269
1270 struct realm *newrealmref(struct realm *r) {
1271     if (r)
1272         r->refcount++;
1273     return r;
1274 }
1275
1276 /* returns with lock on realm */
1277 struct realm *id2realm(struct list *realmlist, char *id) {
1278     struct list_node *entry;
1279     struct realm *realm, *subrealm;
1280
1281     /* need to do locking for subrealms and check subrealm timers */
1282     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1283         realm = (struct realm *)entry->data;
1284         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1285             pthread_mutex_lock(&realm->mutex);
1286             if (realm->subrealms) {
1287                 subrealm = id2realm(realm->subrealms, id);
1288                 if (subrealm) {
1289                     pthread_mutex_unlock(&realm->mutex);
1290                     return subrealm;
1291                 }
1292             }
1293             return newrealmref(realm);
1294         }
1295     }
1296     return NULL;
1297 }
1298
1299 /* helper function, only used by removeserversubrealms() */
1300 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1301     struct list_node *entry, *entry2;
1302     struct realm *realm;
1303
1304     for (entry = list_first(realmlist); entry;) {
1305         realm = newrealmref((struct realm *)entry->data);
1306         pthread_mutex_lock(&realm->mutex);
1307         entry = list_next(entry);
1308
1309         if (realm->srvconfs) {
1310             for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1311                 if (entry2->data == srv)
1312                     freerealm(realm);
1313             list_removedata(realm->srvconfs, srv);
1314             if (!list_first(realm->srvconfs)) {
1315                 list_destroy(realm->srvconfs);
1316                 realm->srvconfs = NULL;
1317             }
1318         }
1319         if (realm->accsrvconfs) {
1320             for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1321                 if (entry2->data == srv)
1322                     freerealm(realm);
1323             list_removedata(realm->accsrvconfs, srv);
1324             if (!list_first(realm->accsrvconfs)) {
1325                 list_destroy(realm->accsrvconfs);
1326                 realm->accsrvconfs = NULL;
1327             }
1328         }
1329
1330         /* remove subrealm if no servers */
1331         if (!realm->srvconfs && !realm->accsrvconfs)
1332             list_removedata(realmlist, realm);
1333
1334         pthread_mutex_unlock(&realm->mutex);
1335         freerealm(realm);
1336     }
1337 }
1338
1339 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1340     struct list_node *entry;
1341     struct realm *realm;
1342     
1343     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1344         realm = (struct realm *)entry->data;
1345         pthread_mutex_lock(&realm->mutex);
1346         if (realm->subrealms) {
1347             _internal_removeserversubrealms(realm->subrealms, srv);
1348             if (!list_first(realm->subrealms)) {
1349                 list_destroy(realm->subrealms);
1350                 realm->subrealms = NULL;
1351             }
1352         }
1353         pthread_mutex_unlock(&realm->mutex);
1354     }
1355 }
1356                         
1357 int attrvalidate(unsigned char *attrs, int length) {
1358     while (length > 1) {
1359         if (ATTRLEN(attrs) < 2) {
1360             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1361             return 0;
1362         }
1363         length -= ATTRLEN(attrs);
1364         if (length < 0) {
1365             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1366             return 0;
1367         }
1368         attrs += ATTRLEN(attrs);
1369     }
1370     if (length)
1371         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1372     return 1;
1373 }
1374
1375 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1376     if (len < 16 || len > 128 || len % 16) {
1377         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1378         return 0;
1379     }
1380         
1381     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1382         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1383         return 0;
1384     }
1385 #ifdef DEBUG
1386     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1387 #endif  
1388     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1389         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1390         return 0;
1391     }
1392     return 1;
1393 }
1394
1395 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1396     if (len < 18)
1397         return 0;
1398     if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1399         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1400         return 0;
1401     }
1402     if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1403         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1404         return 0;
1405     }
1406     return 1;
1407 }
1408
1409 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1410            char *oldsecret, char *newsecret) {
1411     unsigned char *attr;
1412     
1413     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1414         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1415         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1416             return 0;
1417     }
1418     return 1;
1419 }
1420
1421 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1422     if (!attrs)
1423         return 0;
1424     
1425     for (; attrs[0]; attrs += 2)
1426         if (attrs[0] == vendor && attrs[1] == subattr)
1427             return 1;
1428     return 0;
1429 }
1430
1431 /* returns 1 if entire element is to be removed, else 0 */
1432 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1433     uint8_t alen, sublen;
1434     uint32_t vendor;
1435     uint8_t *subattrs;
1436     
1437     if (!removevendorattrs)
1438         return 0;
1439
1440     memcpy(&vendor, attr->v, 4);
1441     vendor = ntohl(vendor);
1442     while (*removevendorattrs && *removevendorattrs != vendor)
1443         removevendorattrs += 2;
1444     if (!*removevendorattrs)
1445         return 0;
1446     
1447     if (findvendorsubattr(removevendorattrs, vendor, -1))
1448         return 1; /* remove entire vendor attribute */
1449
1450     sublen = attr->l - 4;
1451     subattrs = attr->v + 4;
1452     
1453     if (!attrvalidate(subattrs, sublen)) {
1454         debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1455         return 0;
1456     }
1457
1458     while (sublen > 1) {
1459         alen = ATTRLEN(subattrs);
1460         sublen -= alen;
1461         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1462             memmove(subattrs, subattrs + alen, sublen);
1463             attr->l -= alen;
1464         } else
1465             subattrs += alen;
1466     }
1467     return 0;
1468 }
1469
1470 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1471     struct list_node *n, *p;
1472     struct tlv *attr;
1473
1474     p = NULL;
1475     n = list_first(msg->attrs);
1476     while (n) {
1477         attr = (struct tlv *)n->data;
1478         if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1479             (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1480             list_removedata(msg->attrs, attr);
1481             freetlv(attr);
1482             n = p ? list_next(p) : list_first(msg->attrs);
1483         } else
1484             p = n;
1485             n = list_next(n);
1486     }
1487 }
1488
1489 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1490     struct list_node *n;
1491     struct tlv *a;
1492     
1493     for (n = list_first(addattrs); n; n = list_next(n)) {
1494         a = copytlv((struct tlv *)n->data);
1495         if (!a)
1496             return 0;
1497         if (!radmsg_add(msg, a)) {
1498             freetlv(a);
1499             return 0;
1500         }
1501     }
1502     return 1;
1503 }
1504
1505 int resizeattr(struct tlv *attr, uint8_t newlen) {
1506     uint8_t *newv;
1507     
1508     if (newlen != attr->l) {
1509         newv = realloc(attr->v, newlen);
1510         if (!newv)
1511             return 0;
1512         attr->v = newv;
1513         attr->l = newlen;
1514     }
1515     return 1;
1516 }
1517
1518 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1519     size_t nmatch = 10, reslen = 0, start = 0;
1520     regmatch_t pmatch[10], *pfield;
1521     int i;
1522     char *in, *out;
1523
1524     in = stringcopy((char *)attr->v, attr->l);
1525     if (!in)
1526         return 0;
1527     
1528     if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1529         free(in);
1530         return 1;
1531     }
1532     
1533     out = modattr->replacement;
1534     
1535     for (i = start; out[i]; i++) {
1536         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1537             pfield = &pmatch[out[i + 1] - '0'];
1538             if (pfield->rm_so >= 0) {
1539                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1540                 start = i + 2;
1541             }
1542             i++;
1543         }
1544     }
1545     reslen += i - start;
1546     if (reslen > 253) {
1547         debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1548         free(in);
1549         return 0;
1550     }
1551
1552     if (!resizeattr(attr, reslen)) {
1553         free(in);
1554         return 0;
1555     }
1556
1557     start = 0;
1558     reslen = 0;
1559     for (i = start; out[i]; i++) {
1560         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1561             pfield = &pmatch[out[i + 1] - '0'];
1562             if (pfield->rm_so >= 0) {
1563                 memcpy(attr->v + reslen, out + start, i - start);
1564                 reslen += i - start;
1565                 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1566                 reslen += pfield->rm_eo - pfield->rm_so;
1567                 start = i + 2;
1568             }
1569             i++;
1570         }
1571     }
1572
1573     memcpy(attr->v + reslen, out + start, i - start);
1574     return 1;
1575 }
1576
1577 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1578     struct list_node *n, *m;
1579
1580     for (n = list_first(msg->attrs); n; n = list_next(n))
1581         for (m = list_first(modattrs); m; m = list_next(m))
1582             if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1583                 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1584                 return 0;
1585     return 1;
1586 }
1587
1588 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1589     if (!rewrite)
1590         return 1;
1591     if (rewrite->removeattrs || rewrite->removevendorattrs)
1592         dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1593     if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1594         return 0;
1595     if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1596         return 0;
1597     return 1;
1598 }
1599
1600 int rewriteusername(struct request *rq, struct tlv *attr) {
1601     char *orig = (char *)tlv2str(attr);
1602     if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1603         free(orig);
1604         return 0;
1605     }
1606     if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1607         rq->origusername = (char *)orig;
1608     else
1609         free(orig);
1610     return 1;
1611 }
1612
1613 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1614     struct tlv *vattr;
1615     uint8_t l, *v;
1616
1617     l = attr->l + 6;
1618     v = malloc(l);
1619     if (v) {
1620         vendor = htonl(vendor);
1621         memcpy(v, &vendor, 4);
1622         tlv2buf(v + 4, attr);
1623         v[5] += 2;
1624         vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1625         if (vattr && radmsg_add(msg, vattr))
1626             return 1;
1627         freetlv(vattr);
1628     }
1629     return 0;
1630 }
1631
1632 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1633     uint8_t ttl[4];
1634     struct tlv *attr;
1635
1636     memset(ttl, 0, 4);
1637     ttl[3] = addttl;
1638     
1639     if (attrtype[1] == -1) { /* not vendor */
1640         attr = maketlv(attrtype[0], 4, ttl);
1641         if (attr && !radmsg_add(msg, attr))
1642             freetlv(attr);
1643     } else {
1644         attr = maketlv(attrtype[1], 4, ttl);
1645         if (attr) {
1646             addvendorattr(msg, attrtype[0], attr);
1647             freetlv(attr);
1648         }
1649     }
1650 }
1651
1652 int decttl(uint8_t l, uint8_t *v) {
1653     int i;
1654
1655     i = l - 1;
1656     if (v[i]) {
1657         if (--v[i--])
1658             return 1;
1659         while (i >= 0 && !v[i])
1660             i--;
1661         return i >= 0;
1662     }
1663     for (i--; i >= 0 && !v[i]; i--);
1664     if (i < 0)
1665         return 0;
1666     v[i]--;
1667     while (++i < l)
1668         v[i] = 255;
1669     return 1;
1670 }
1671
1672 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1673 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1674     uint8_t alen, *subattrs;
1675     struct tlv *attr;
1676     struct list_node *node;
1677     uint32_t vendor;
1678     int sublen;
1679     
1680     if (attrtype[1] == -1) { /* not vendor */
1681         attr = radmsg_gettype(msg, attrtype[0]);
1682         if (attr)
1683             return decttl(attr->l, attr->v);
1684     } else
1685         for (node = list_first(msg->attrs); node; node = list_next(node)) {
1686             attr = (struct tlv *)node->data;
1687             if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1688                 continue;
1689             memcpy(&vendor, attr->v, 4);
1690             if (ntohl(vendor) != attrtype[0])
1691                 continue;
1692             sublen = attr->l - 4;
1693             subattrs = attr->v + 4;  
1694             if (!attrvalidate(subattrs, sublen))
1695                 continue;
1696             while (sublen > 1) {
1697                 if (ATTRTYPE(subattrs) == attrtype[1])
1698                     return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1699                 alen = ATTRLEN(subattrs);
1700                 sublen -= alen;
1701                 subattrs += alen;
1702             }
1703         }
1704     return -1;
1705 }
1706           
1707 const char *radmsgtype2string(uint8_t code) {
1708     static const char *rad_msg_names[] = {
1709         "", "Access-Request", "Access-Accept", "Access-Reject",
1710         "Accounting-Request", "Accounting-Response", "", "",
1711         "", "", "", "Access-Challenge",
1712         "Status-Server", "Status-Client"
1713     };
1714     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1715 }
1716
1717 void char2hex(char *h, unsigned char c) {
1718     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1719                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1720     h[0] = hexdigits[c / 16];
1721     h[1] = hexdigits[c % 16];
1722     return;
1723 }
1724
1725 uint8_t *radattr2ascii(struct tlv *attr) {
1726     int i, l;
1727     uint8_t *a, *d;
1728
1729     if (!attr)
1730         return NULL;
1731
1732     l = attr->l;
1733     for (i = 0; i < attr->l; i++)
1734         if (attr->v[i] < 32 || attr->v[i] > 126)
1735             l += 2;
1736     if (l == attr->l)
1737         return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1738     
1739     a = malloc(l + 1);
1740     if (!a)
1741         return NULL;
1742
1743     d = a;
1744     for (i = 0; i < attr->l; i++)
1745         if (attr->v[i] < 32 || attr->v[i] > 126) {
1746             *d++ = '%';
1747             char2hex((char *)d, attr->v[i]);
1748             d += 2;
1749         } else
1750             *d++ = attr->v[i];
1751     *d = '\0';
1752     return a;
1753 }
1754
1755 void acclog(struct radmsg *msg, char *host) {
1756     struct tlv *attr;
1757     uint8_t *username;
1758     
1759     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1760     if (!attr) {
1761         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1762         return;
1763     }
1764     username = radattr2ascii(attr);
1765     if (username) {
1766         debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1767         free(username);
1768     }
1769 }
1770
1771 void respond(struct request *rq, uint8_t code, char *message) {
1772     struct radmsg *msg;
1773     struct tlv *attr;
1774
1775     msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1776     if (!msg) {
1777         debug(DBG_ERR, "respond: malloc failed");
1778         return;
1779     }
1780     if (message && *message) {
1781         attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1782         if (!attr || !radmsg_add(msg, attr)) {
1783             freetlv(attr);
1784             radmsg_free(msg);
1785             debug(DBG_ERR, "respond: malloc failed");
1786             return;
1787         }
1788     }
1789
1790     radmsg_free(rq->msg);
1791     rq->msg = msg;
1792     debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1793     sendreply(newrqref(rq));
1794 }
1795
1796 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1797     struct list_node *entry;
1798     struct clsrvconf *server, *best = NULL, *first = NULL;
1799
1800     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1801         server = (struct clsrvconf *)entry->data;
1802         if (!server->servers)
1803             return server;
1804         if (!first)
1805             first = server;
1806         if (!server->servers->connectionok)
1807             continue;
1808         if (!server->servers->lostrqs)
1809             return server;
1810         if (!best) {
1811             best = server;
1812             continue;
1813         }
1814         if (server->servers->lostrqs < best->servers->lostrqs)
1815             best = server;
1816     }
1817     return best ? best : first;
1818 }
1819
1820 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1821 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1822     struct clsrvconf *srvconf;
1823     struct realm *subrealm;
1824     struct server *server = NULL;
1825     char *id = (char *)tlv2str(username);
1826     
1827     if (!id)
1828         return NULL;
1829     /* returns with lock on realm */
1830     *realm = id2realm(realms, id);
1831     if (!*realm)
1832         goto exit;
1833     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1834     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1835     if (!srvconf)
1836         goto exit;
1837     server = srvconf->servers;
1838     if (!acc && !(*realm)->parent && !srvconf->servers) {
1839         subrealm = adddynamicrealmserver(*realm, srvconf, id);
1840         if (subrealm) {
1841             pthread_mutex_lock(&subrealm->mutex);
1842             pthread_mutex_unlock(&(*realm)->mutex);
1843             freerealm(*realm);
1844             *realm = subrealm;
1845             server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1846         }
1847     }
1848  exit:    
1849     free(id);
1850     return server;
1851 }
1852
1853
1854 struct request *newrequest() {
1855     struct request *rq;
1856
1857     rq = malloc(sizeof(struct request));
1858     if (!rq) {
1859         debug(DBG_ERR, "newrequest: malloc failed");
1860         return NULL;
1861     }
1862     memset(rq, 0, sizeof(struct request));
1863     rq->refcount = 1;
1864     gettimeofday(&rq->created, NULL);
1865     return rq;
1866 }
1867
1868 int addclientrq(struct request *rq) {
1869     struct request *r;
1870     struct timeval now;
1871     
1872     r = rq->from->rqs[rq->rqid];
1873     if (r) {
1874         if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1875             gettimeofday(&now, NULL);
1876             if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1877                 if (r->replybuf) {
1878                     debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1879                     sendreply(newrqref(r));
1880                 } else
1881                     debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1882                 return 0;
1883             }
1884         }
1885         freerq(r);
1886     }
1887     rq->from->rqs[rq->rqid] = newrqref(rq);
1888     return 1;
1889 }
1890
1891 void rmclientrq(struct request *rq, uint8_t id) {
1892     struct request *r;
1893
1894     r = rq->from->rqs[id];
1895     if (r) {
1896         freerq(r);
1897         rq->from->rqs[id] = NULL;
1898     }
1899 }
1900
1901 /* returns 0 if validation/authentication fails, else 1 */
1902 int radsrv(struct request *rq) {
1903     struct radmsg *msg = NULL;
1904     struct tlv *attr;
1905     uint8_t *userascii = NULL;
1906     struct realm *realm = NULL;
1907     struct server *to = NULL;
1908     struct client *from = rq->from;
1909     int ttlres;
1910     
1911     msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1912     free(rq->buf);
1913     rq->buf = NULL;
1914
1915     if (!msg) {
1916         debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1917         freerq(rq);
1918         return 0;
1919     }
1920     
1921     rq->msg = msg;
1922     rq->rqid = msg->id;
1923     memcpy(rq->rqauth, msg->auth, 16);
1924
1925     debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1926     if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1927         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");      
1928         goto exit;
1929     }
1930     
1931     if (!addclientrq(rq))
1932         goto exit;
1933
1934     if (msg->code == RAD_Status_Server) {
1935         respond(rq, RAD_Access_Accept, NULL);
1936         goto exit;
1937     }
1938
1939     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1940
1941     if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1942         goto rmclrqexit;
1943
1944     ttlres = checkttl(msg, options.ttlattrtype);
1945     if (!ttlres) {
1946         debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1947         goto exit;
1948     }
1949         
1950     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1951     if (!attr) {
1952         if (msg->code == RAD_Accounting_Request) {
1953             acclog(msg, from->conf->host);
1954             respond(rq, RAD_Accounting_Response, NULL);
1955         } else
1956             debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1957         goto exit;
1958     }
1959     
1960     if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1961         debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1962         goto rmclrqexit;
1963     }
1964     
1965     userascii = radattr2ascii(attr);
1966     if (!userascii)
1967         goto rmclrqexit;
1968     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1969
1970     /* will return with lock on the realm */
1971     to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1972     if (!realm) {
1973         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1974         goto exit;
1975     }
1976
1977     if (!to) {
1978         if (realm->message && msg->code == RAD_Access_Request) {
1979             debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1980             respond(rq, RAD_Access_Reject, realm->message);
1981         } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1982             acclog(msg, from->conf->host);
1983             respond(rq, RAD_Accounting_Response, NULL);
1984         }
1985         goto exit;
1986     }
1987     
1988     if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1989         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1990               from->conf->name, addr2string(from->addr), to->conf->name);
1991         goto exit;
1992     }
1993
1994     if (msg->code == RAD_Accounting_Request)
1995         memset(msg->auth, 0, 16);
1996     else if (!RAND_bytes(msg->auth, 16)) {
1997         debug(DBG_WARN, "radsrv: failed to generate random auth");
1998         goto rmclrqexit;
1999     }
2000     
2001 #ifdef DEBUG
2002     printfchars(NULL, "auth", "%02x ", auth, 16);
2003 #endif
2004
2005     attr = radmsg_gettype(msg, RAD_Attr_User_Password);
2006     if (attr) {
2007         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
2008         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2009             goto rmclrqexit;
2010     }
2011
2012     attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
2013     if (attr) {
2014         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
2015         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
2016             goto rmclrqexit;
2017     }
2018
2019     if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
2020         goto rmclrqexit;
2021     
2022     if (ttlres == -1 && (options.addttl || to->conf->addttl))
2023         addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
2024     
2025     free(userascii);
2026     rq->to = to;
2027     sendrq(rq);
2028     pthread_mutex_unlock(&realm->mutex);
2029     freerealm(realm);
2030     return 1;
2031     
2032  rmclrqexit:
2033     rmclientrq(rq, msg->id);
2034  exit:
2035     freerq(rq);
2036     free(userascii);
2037     if (realm) {
2038         pthread_mutex_unlock(&realm->mutex);
2039         freerealm(realm);
2040     }
2041     return 1;
2042 }
2043
2044 void replyh(struct server *server, unsigned char *buf) {
2045     struct client *from;
2046     struct rqout *rqout;
2047     int sublen, ttlres;
2048     unsigned char *subattrs;
2049     uint8_t *username, *stationid, *replymsg;
2050     struct radmsg *msg = NULL;
2051     struct tlv *attr;
2052     struct list_node *node;
2053     
2054     server->connectionok = 1;
2055     server->lostrqs = 0;
2056
2057     rqout = server->requests + buf[1];
2058     pthread_mutex_lock(rqout->lock);
2059     if (!rqout->tries) {
2060         free(buf);
2061         buf = NULL;
2062         debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
2063         goto errunlock;
2064     }
2065         
2066     msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
2067     free(buf);
2068     buf = NULL;
2069     if (!msg) {
2070         debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
2071         goto errunlock;
2072     }
2073     if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
2074         && msg->code != RAD_Accounting_Response) {
2075         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
2076         goto errunlock;
2077     }
2078     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
2079
2080     gettimeofday(&server->lastrcv, NULL);
2081     
2082     if (rqout->rq->msg->code == RAD_Status_Server) {
2083         freerqoutdata(rqout);
2084         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2085         goto errunlock;
2086     }
2087
2088     gettimeofday(&server->lastreply, NULL);
2089     from = rqout->rq->from;
2090         
2091     if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
2092         debug(DBG_WARN, "replyh: rewritein failed");
2093         goto errunlock;
2094     }
2095     
2096     ttlres = checkttl(msg, options.ttlattrtype);
2097     if (!ttlres) {    
2098         debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
2099         goto errunlock;
2100     }
2101     
2102     /* MS MPPE */
2103     for (node = list_first(msg->attrs); node; node = list_next(node)) {
2104         attr = (struct tlv *)node->data;
2105         if (attr->t != RAD_Attr_Vendor_Specific)
2106             continue;
2107         if (attr->l <= 4)
2108             break;
2109         if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55)  /* 311 == MS */
2110             continue;
2111             
2112         sublen = attr->l - 4;
2113         subattrs = attr->v + 4;  
2114         if (!attrvalidate(subattrs, sublen) ||
2115             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2116                     rqout->rq, server->conf->secret, from->conf->secret) ||
2117             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2118                     rqout->rq, server->conf->secret, from->conf->secret))
2119             break;
2120     }
2121     if (node) {
2122         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2123         goto errunlock;
2124     }
2125
2126     if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2127         username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
2128         if (username) {
2129             stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
2130             replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2131             if (stationid) {
2132                 if (replymsg) {
2133                     debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2134                           radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2135                     free(replymsg);
2136                 } else
2137                     debug(DBG_INFO, "%s for user %s stationid %s from %s",
2138                           radmsgtype2string(msg->code), username, stationid, server->conf->host);
2139                 free(stationid);
2140             } else {
2141                 if (replymsg) {
2142                     debug(DBG_INFO, "%s for user %s from %s (%s)",
2143                           radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2144                     free(replymsg);
2145                 } else
2146                     debug(DBG_INFO, "%s for user %s from %s",
2147                           radmsgtype2string(msg->code), username, server->conf->host);
2148             }
2149             free(username);
2150         }
2151     }
2152
2153     msg->id = (char)rqout->rq->rqid;
2154     memcpy(msg->auth, rqout->rq->rqauth, 16);
2155
2156 #ifdef DEBUG    
2157     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2158 #endif
2159
2160     if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2161         if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2162             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2163             goto errunlock;
2164         }
2165         memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2166     }
2167
2168     if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2169         debug(DBG_WARN, "replyh: rewriteout failed");
2170         goto errunlock;
2171     }
2172     
2173     if (ttlres == -1 && (options.addttl || from->conf->addttl))
2174         addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
2175
2176     debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2177     radmsg_free(rqout->rq->msg);
2178     rqout->rq->msg = msg;
2179     sendreply(newrqref(rqout->rq));
2180     freerqoutdata(rqout);
2181     pthread_mutex_unlock(rqout->lock);
2182     return;
2183
2184  errunlock:
2185     radmsg_free(msg);
2186     pthread_mutex_unlock(rqout->lock);
2187     return;
2188 }
2189
2190 struct request *createstatsrvrq() {
2191     struct request *rq;
2192     struct tlv *attr;
2193
2194     rq = newrequest();
2195     if (!rq)
2196         return NULL;
2197     rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2198     if (!rq->msg)
2199         goto exit;
2200     attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2201     if (!attr)
2202         goto exit;
2203     if (!radmsg_add(rq->msg, attr)) {
2204         freetlv(attr);
2205         goto exit;
2206     }
2207     return rq;
2208
2209  exit:
2210     freerq(rq);
2211     return NULL;
2212 }
2213
2214 /* code for removing state not finished */
2215 void *clientwr(void *arg) {
2216     struct server *server = (struct server *)arg;
2217     struct rqout *rqout = NULL;
2218     pthread_t clientrdth;
2219     int i, dynconffail = 0;
2220     time_t secs;
2221     uint8_t rnd;
2222     struct timeval now, laststatsrv;
2223     struct timespec timeout;
2224     struct request *statsrvrq;
2225     struct clsrvconf *conf;
2226     
2227     conf = server->conf;
2228     
2229     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2230         dynconffail = 1;
2231         goto errexit;
2232     }
2233     
2234     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2235         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2236         goto errexit;
2237     }
2238
2239     memset(&timeout, 0, sizeof(struct timespec));
2240     
2241     if (conf->statusserver) {
2242         gettimeofday(&server->lastrcv, NULL);
2243         gettimeofday(&laststatsrv, NULL);
2244     }
2245
2246     if (conf->pdef->connecter) {
2247         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2248             goto errexit;
2249         server->connectionok = 1;
2250         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2251             debug(DBG_ERR, "clientwr: pthread_create failed");
2252             goto errexit;
2253         }
2254     } else
2255         server->connectionok = 1;
2256     
2257     for (;;) {
2258         pthread_mutex_lock(&server->newrq_mutex);
2259         if (!server->newrq) {
2260             gettimeofday(&now, NULL);
2261             /* random 0-7 seconds */
2262             RAND_bytes(&rnd, 1);
2263             rnd /= 32;
2264             if (conf->statusserver) {
2265                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2266                 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2267                     secs = now.tv_sec;
2268                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2269                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2270             } else {
2271                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2272                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2273             }
2274 #if 0
2275             if (timeout.tv_sec > now.tv_sec)
2276                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2277 #endif      
2278             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2279             timeout.tv_sec = 0;
2280         }
2281         if (server->newrq) {
2282             debug(DBG_DBG, "clientwr: got new request");
2283             server->newrq = 0;
2284         }
2285 #if 0   
2286         else
2287             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2288 #endif  
2289         pthread_mutex_unlock(&server->newrq_mutex);
2290
2291         for (i = 0; i < MAX_REQUESTS; i++) {
2292             if (server->clientrdgone) {
2293                 pthread_join(clientrdth, NULL);
2294                 goto errexit;
2295             }
2296
2297             for (; i < MAX_REQUESTS; i++) {
2298                 rqout = server->requests + i;
2299                 if (rqout->rq) {
2300                     pthread_mutex_lock(rqout->lock);
2301                     if (rqout->rq)
2302                         break;
2303                     pthread_mutex_unlock(rqout->lock);
2304                 }
2305             }
2306                 
2307             if (i == MAX_REQUESTS)
2308                 break;
2309
2310             gettimeofday(&now, NULL);
2311             if (now.tv_sec < rqout->expiry.tv_sec) {
2312                 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2313                     timeout.tv_sec = rqout->expiry.tv_sec;
2314                 pthread_mutex_unlock(rqout->lock);
2315                 continue;
2316             }
2317
2318             if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2319                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2320                 if (conf->statusserver) {
2321                     if (*rqout->rq->buf == RAD_Status_Server) {
2322                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2323                         if (server->lostrqs < 255)
2324                             server->lostrqs++;
2325                     }
2326                 } else {
2327                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2328                     if (server->lostrqs < 255)
2329                         server->lostrqs++;
2330                 }
2331                 freerqoutdata(rqout);
2332                 pthread_mutex_unlock(rqout->lock);
2333                 continue;
2334             }
2335
2336             rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2337             if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2338                 timeout.tv_sec = rqout->expiry.tv_sec;
2339             rqout->tries++;
2340             conf->pdef->clientradput(server, rqout->rq->buf);
2341             pthread_mutex_unlock(rqout->lock);
2342         }
2343         if (conf->statusserver && server->connectionok) {
2344             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2345             gettimeofday(&now, NULL);
2346             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2347                 laststatsrv = now;
2348                 statsrvrq = createstatsrvrq();
2349                 if (statsrvrq) {
2350                     statsrvrq->to = server;
2351                     debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2352                     sendrq(statsrvrq);
2353                 }
2354             }
2355         }
2356     }
2357  errexit:
2358     conf->servers = NULL;
2359     if (server->dynamiclookuparg) {
2360         removeserversubrealms(realms, conf);
2361         if (dynconffail)
2362             free(conf);
2363         else
2364             freeclsrvconf(conf);
2365     }
2366     freeserver(server, 1);
2367     ERR_remove_state(0);
2368     return NULL;
2369 }
2370
2371 void createlistener(uint8_t type, char *arg) {
2372     pthread_t th;
2373     struct clsrvconf *listenres;
2374     struct addrinfo *res;
2375     int s = -1, on = 1, *sp = NULL;
2376     
2377     listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2378     if (!listenres)
2379         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2380     
2381     for (res = listenres->addrinfo; res; res = res->ai_next) {
2382         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2383         if (s < 0) {
2384             debug(DBG_WARN, "createlistener: socket failed");
2385             continue;
2386         }
2387         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2388 #ifdef IPV6_V6ONLY
2389         if (res->ai_family == AF_INET6)
2390             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2391 #endif          
2392         if (bind(s, res->ai_addr, res->ai_addrlen)) {
2393             debug(DBG_WARN, "createlistener: bind failed");
2394             close(s);
2395             s = -1;
2396             continue;
2397         }
2398
2399         sp = malloc(sizeof(int));
2400         if (!sp)
2401             debugx(1, DBG_ERR, "malloc failed");
2402         *sp = s;
2403         if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2404             debugx(1, DBG_ERR, "pthread_create failed");
2405         pthread_detach(th);
2406     }
2407     if (!sp)
2408         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2409     
2410     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2411           listenres->host ? listenres->host : "*", listenres->port);
2412     freeclsrvres(listenres);
2413 }
2414
2415 void createlisteners(uint8_t type, char **args) {
2416     int i;
2417
2418     if (args)
2419         for (i = 0; args[i]; i++)
2420             createlistener(type, args[i]);
2421     else
2422         createlistener(type, NULL);
2423 }
2424
2425 #ifdef DEBUG
2426 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2427     const char *s;
2428     int w;
2429
2430     w = where & ~SSL_ST_MASK;
2431
2432     if (w & SSL_ST_CONNECT)
2433         s = "SSL_connect";
2434     else if (w & SSL_ST_ACCEPT)
2435         s = "SSL_accept";
2436     else
2437         s = "undefined";
2438
2439     if (where & SSL_CB_LOOP)
2440         debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2441     else if (where & SSL_CB_ALERT) {
2442         s = (where & SSL_CB_READ) ? "read" : "write";
2443         debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2444     }
2445     else if (where & SSL_CB_EXIT) {
2446         if (ret == 0)
2447             debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2448         else if (ret < 0)
2449             debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2450     }
2451 }
2452 #endif
2453
2454 void tlsinit() {
2455     int i;
2456     time_t t;
2457     pid_t pid;
2458     
2459     ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2460     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2461     for (i = 0; i < CRYPTO_num_locks(); i++) {
2462         ssl_lock_count[i] = 0;
2463         pthread_mutex_init(&ssl_locks[i], NULL);
2464     }
2465     CRYPTO_set_id_callback(ssl_thread_id);
2466     CRYPTO_set_locking_callback(ssl_locking_callback);
2467
2468     SSL_load_error_strings();
2469     SSL_library_init();
2470
2471     while (!RAND_status()) {
2472         t = time(NULL);
2473         pid = getpid();
2474         RAND_seed((unsigned char *)&t, sizeof(time_t));
2475         RAND_seed((unsigned char *)&pid, sizeof(pid));
2476     }
2477 }
2478
2479 X509_VERIFY_PARAM *createverifyparams(char **poids) {
2480     X509_VERIFY_PARAM *pm;
2481     ASN1_OBJECT *pobject;
2482     int i;
2483     
2484     pm = X509_VERIFY_PARAM_new();
2485     if (!pm)
2486         return NULL;
2487     
2488     for (i = 0; poids[i]; i++) {
2489         pobject = OBJ_txt2obj(poids[i], 0);
2490         if (!pobject) {
2491             X509_VERIFY_PARAM_free(pm);
2492             return NULL;
2493         }
2494         X509_VERIFY_PARAM_add0_policy(pm, pobject);
2495     }
2496
2497     X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
2498     return pm;
2499 }
2500
2501 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2502     STACK_OF(X509_NAME) *calist;
2503     X509_STORE *x509_s;
2504     unsigned long error;
2505
2506     if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2507         while ((error = ERR_get_error()))
2508             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2509         debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2510         return 0;
2511     }
2512
2513     calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2514     if (!conf->cacertfile || calist) {
2515         if (conf->cacertpath) {
2516             if (!calist)
2517                 calist = sk_X509_NAME_new_null();
2518             if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2519                 sk_X509_NAME_free(calist);
2520                 calist = NULL;
2521             }
2522         }
2523     }
2524     if (!calist) {
2525         while ((error = ERR_get_error()))
2526             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2527         debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2528         return 0;
2529     }
2530     ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2531     SSL_CTX_set_client_CA_list(ctx, calist);
2532
2533     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2534     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2535
2536     if (conf->crlcheck || conf->vpm) {
2537         x509_s = SSL_CTX_get_cert_store(ctx);
2538         if (conf->crlcheck)
2539             X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2540         if (conf->vpm)
2541             X509_STORE_set1_param(x509_s, conf->vpm);
2542     }
2543
2544     debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2545     return 1;
2546 }
2547
2548 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2549     SSL_CTX *ctx = NULL;
2550     unsigned long error;
2551
2552     if (!ssl_locks)
2553         tlsinit();
2554
2555     switch (type) {
2556     case RAD_TLS:
2557         ctx = SSL_CTX_new(TLSv1_method());
2558 #ifdef DEBUG    
2559         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2560 #endif  
2561         break;
2562     case RAD_DTLS:
2563         ctx = SSL_CTX_new(DTLSv1_method());
2564 #ifdef DEBUG    
2565         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2566 #endif  
2567         SSL_CTX_set_read_ahead(ctx, 1);
2568         break;
2569     }
2570     if (!ctx) {
2571         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2572         return NULL;
2573     }
2574     
2575     if (conf->certkeypwd) {
2576         SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2577         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2578     }
2579     if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2580         !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2581         !SSL_CTX_check_private_key(ctx)) {
2582         while ((error = ERR_get_error()))
2583             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2584         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2585         SSL_CTX_free(ctx);
2586         return NULL;
2587     }
2588
2589     if (conf->policyoids) {
2590         if (!conf->vpm) {
2591             conf->vpm = createverifyparams(conf->policyoids);
2592             if (!conf->vpm) {
2593                 debug(DBG_ERR, "tlsaddcacrl: Failed to add policyOIDs in TLS context %s", conf->name);
2594                 SSL_CTX_free(ctx);
2595                 return NULL;
2596             }
2597         }
2598     }
2599
2600     if (!tlsaddcacrl(ctx, conf)) {
2601         if (conf->vpm) {
2602             X509_VERIFY_PARAM_free(conf->vpm);
2603             conf->vpm = NULL;
2604         }
2605         SSL_CTX_free(ctx);
2606         return NULL;
2607     }
2608
2609     debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2610     return ctx;
2611 }
2612
2613 struct tls *tlsgettls(char *alt1, char *alt2) {
2614     struct tls *t;
2615
2616     t = hash_read(tlsconfs, alt1, strlen(alt1));
2617     if (!t)
2618         t = hash_read(tlsconfs, alt2, strlen(alt2));
2619     return t;
2620 }
2621
2622 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2623     struct timeval now;
2624     
2625     if (!t)
2626         return NULL;
2627     gettimeofday(&now, NULL);
2628     
2629     switch (type) {
2630     case RAD_TLS:
2631         if (t->tlsexpiry && t->tlsctx) {
2632             if (t->tlsexpiry < now.tv_sec) {
2633                 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2634                 tlsaddcacrl(t->tlsctx, t);
2635             }
2636         }
2637         if (!t->tlsctx) {
2638             t->tlsctx = tlscreatectx(RAD_TLS, t);
2639             if (t->cacheexpiry)
2640                 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2641         }
2642         return t->tlsctx;
2643     case RAD_DTLS:
2644         if (t->dtlsexpiry && t->dtlsctx) {
2645             if (t->dtlsexpiry < now.tv_sec) {
2646                 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2647                 tlsaddcacrl(t->dtlsctx, t);
2648             }
2649         }
2650         if (!t->dtlsctx) {
2651             t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2652             if (t->cacheexpiry)
2653                 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2654         }
2655         return t->dtlsctx;
2656     }
2657     return NULL;
2658 }
2659
2660 struct list *addsrvconfs(char *value, char **names) {
2661     struct list *conflist;
2662     int n;
2663     struct list_node *entry;
2664     struct clsrvconf *conf = NULL;
2665     
2666     if (!names || !*names)
2667         return NULL;
2668     
2669     conflist = list_create();
2670     if (!conflist) {
2671         debug(DBG_ERR, "malloc failed");
2672         return NULL;
2673     }
2674
2675     for (n = 0; names[n]; n++) {
2676         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2677             conf = (struct clsrvconf *)entry->data;
2678             if (!strcasecmp(names[n], conf->name))
2679                 break;
2680         }
2681         if (!entry) {
2682             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2683             list_destroy(conflist);
2684             return NULL;
2685         }
2686         if (!list_push(conflist, conf)) {
2687             debug(DBG_ERR, "malloc failed");
2688             list_destroy(conflist);
2689             return NULL;
2690         }
2691         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2692     }
2693     return conflist;
2694 }
2695
2696 void freerealm(struct realm *realm) {
2697     if (!realm)
2698         return;
2699     debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2700     if (--realm->refcount)
2701         return;
2702
2703     free(realm->name);
2704     free(realm->message);
2705     regfree(&realm->regex);
2706     pthread_mutex_destroy(&realm->mutex);
2707     /* if refcount == 0, all subrealms gone */
2708     list_destroy(realm->subrealms);
2709     /* if refcount == 0, all srvconfs gone */
2710     list_destroy(realm->srvconfs);
2711     /* if refcount == 0, all accsrvconfs gone */
2712     list_destroy(realm->accsrvconfs);
2713     freerealm(realm->parent);
2714     free(realm);
2715 }
2716
2717 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2718     int n;
2719     struct realm *realm;
2720     char *s, *regex = NULL;
2721     
2722     if (*value == '/') {
2723         /* regexp, remove optional trailing / if present */
2724         if (value[strlen(value) - 1] == '/')
2725             value[strlen(value) - 1] = '\0';
2726     } else {
2727         /* not a regexp, let us make it one */
2728         if (*value == '*' && !value[1])
2729             regex = stringcopy(".*", 0);
2730         else {
2731             for (n = 0, s = value; *s;)
2732                 if (*s++ == '.')
2733                     n++;
2734             regex = malloc(strlen(value) + n + 3);
2735             if (regex) {
2736                 regex[0] = '@';
2737                 for (n = 1, s = value; *s; s++) {
2738                     if (*s == '.')
2739                         regex[n++] = '\\';
2740                     regex[n++] = *s;
2741                 }
2742                 regex[n++] = '$';
2743                 regex[n] = '\0';
2744             }
2745         }
2746         if (!regex) {
2747             debug(DBG_ERR, "malloc failed");
2748             realm = NULL;
2749             goto exit;
2750         }
2751         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2752     }
2753
2754     realm = malloc(sizeof(struct realm));
2755     if (!realm) {
2756         debug(DBG_ERR, "malloc failed");
2757         goto exit;
2758     }
2759     memset(realm, 0, sizeof(struct realm));
2760     
2761     if (pthread_mutex_init(&realm->mutex, NULL)) {
2762         debug(DBG_ERR, "mutex init failed");
2763         free(realm);
2764         realm = NULL;
2765         goto exit;
2766     }
2767
2768     realm->name = stringcopy(value, 0);
2769     if (!realm->name) {
2770         debug(DBG_ERR, "malloc failed");
2771         goto errexit;
2772     }
2773     if (message && strlen(message) > 253) {
2774         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2775         goto errexit;
2776     }
2777     realm->message = message;
2778     realm->accresp = accresp;
2779     
2780     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2781         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2782         goto errexit;
2783     }
2784     
2785     if (servers && *servers) {
2786         realm->srvconfs = addsrvconfs(value, servers);
2787         if (!realm->srvconfs)
2788             goto errexit;
2789     }
2790     
2791     if (accservers && *accservers) {
2792         realm->accsrvconfs = addsrvconfs(value, accservers);
2793         if (!realm->accsrvconfs)
2794             goto errexit;
2795     }
2796
2797     if (!list_push(realmlist, realm)) {
2798         debug(DBG_ERR, "malloc failed");
2799         pthread_mutex_destroy(&realm->mutex);
2800         goto errexit;
2801     }
2802     
2803     debug(DBG_DBG, "addrealm: added realm %s", value);
2804     goto exit;
2805
2806  errexit:
2807     while (list_shift(realm->srvconfs));
2808     while (list_shift(realm->accsrvconfs));
2809     freerealm(realm);
2810     realm = NULL;
2811  exit:
2812     free(regex);
2813     if (servers) {
2814         if (realm)
2815             for (n = 0; servers[n]; n++)
2816                 newrealmref(realm);
2817         freegconfmstr(servers);
2818     }
2819     if (accservers) {
2820         if (realm)
2821             for (n = 0; accservers[n]; n++)
2822                 newrealmref(realm);
2823         freegconfmstr(accservers);
2824     }
2825     return newrealmref(realm);
2826 }
2827
2828 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2829     struct clsrvconf *srvconf;
2830     struct realm *newrealm = NULL;
2831     char *realmname, *s;
2832     pthread_t clientth;
2833     
2834     if (!conf->dynamiclookupcommand)
2835         return NULL;
2836
2837     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2838     realmname = strrchr(id, '@');
2839     if (!realmname)
2840         return NULL;
2841     realmname++;
2842     if (!*realmname)
2843         return NULL;
2844     for (s = realmname; *s; s++)
2845         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2846             return NULL;
2847     
2848     srvconf = malloc(sizeof(struct clsrvconf));
2849     if (!srvconf) {
2850         debug(DBG_ERR, "malloc failed");
2851         return NULL;
2852     }
2853     *srvconf = *conf;
2854     if (!addserver(srvconf))
2855         goto errexit;
2856
2857     if (!realm->subrealms)
2858         realm->subrealms = list_create();
2859     if (!realm->subrealms)
2860         goto errexit;
2861     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2862     if (!newrealm)
2863         goto errexit;
2864     newrealm->parent = newrealmref(realm);
2865     
2866     /* add server and accserver to newrealm */
2867     newrealm->srvconfs = list_create();
2868     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2869         debug(DBG_ERR, "malloc failed");
2870         goto errexit;
2871     }
2872     newrealmref(newrealm);
2873     newrealm->accsrvconfs = list_create();
2874     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2875         debug(DBG_ERR, "malloc failed");
2876         list_shift(realm->srvconfs);
2877         freerealm(newrealm);
2878         goto errexit;
2879     }
2880     newrealmref(newrealm);
2881
2882     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2883     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2884         debug(DBG_ERR, "pthread_create failed");
2885         list_shift(realm->srvconfs);
2886         freerealm(newrealm);
2887         list_shift(realm->accsrvconfs);
2888         freerealm(newrealm);
2889         goto errexit;
2890     }
2891     pthread_detach(clientth);
2892     return newrealm;
2893     
2894  errexit:
2895     if (newrealm) {
2896         list_removedata(realm->subrealms, newrealm);
2897         freerealm(newrealm);
2898         if (!list_first(realm->subrealms)) {
2899             list_destroy(realm->subrealms);
2900             realm->subrealms = NULL;
2901         }
2902     }
2903     freeserver(srvconf->servers, 1);
2904     free(srvconf);
2905     debug(DBG_ERR, "failed to create dynamic server");
2906     return NULL;
2907 }
2908
2909 int dynamicconfig(struct server *server) {
2910     int ok, fd[2], status;
2911     pid_t pid;
2912     struct clsrvconf *conf = server->conf;
2913     struct gconffile *cf = NULL;
2914     
2915     /* for now we only learn hostname/address */
2916     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2917
2918     if (pipe(fd) > 0) {
2919         debug(DBG_ERR, "dynamicconfig: pipe error");
2920         goto errexit;
2921     }
2922     pid = fork();
2923     if (pid < 0) {
2924         debug(DBG_ERR, "dynamicconfig: fork error");
2925         close(fd[0]);
2926         close(fd[1]);
2927         goto errexit;
2928     } else if (pid == 0) {
2929         /* child */
2930         close(fd[0]);
2931         if (fd[1] != STDOUT_FILENO) {
2932             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2933                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2934             close(fd[1]);
2935         }
2936         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2937             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2938     }
2939
2940     close(fd[1]);
2941     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2942     ok = getgenericconfig(&cf, NULL,
2943                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2944                           NULL
2945                           );
2946     freegconf(&cf);
2947         
2948     if (waitpid(pid, &status, 0) < 0) {
2949         debug(DBG_ERR, "dynamicconfig: wait error");
2950         goto errexit;
2951     }
2952     
2953     if (status) {
2954         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2955         goto errexit;
2956     }
2957
2958     if (ok)
2959         return 1;
2960
2961  errexit:    
2962     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2963     return 0;
2964 }
2965
2966 int addmatchcertattr(struct clsrvconf *conf) {
2967     char *v;
2968     regex_t **r;
2969     
2970     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2971         r = &conf->certcnregex;
2972         v = conf->matchcertattr + 4;
2973     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2974         r = &conf->certuriregex;
2975         v = conf->matchcertattr + 20;
2976     } else
2977         return 0;
2978     if (!*v)
2979         return 0;
2980     /* regexp, remove optional trailing / if present */
2981     if (v[strlen(v) - 1] == '/')
2982         v[strlen(v) - 1] = '\0';
2983     if (!*v)
2984         return 0;
2985
2986     *r = malloc(sizeof(regex_t));
2987     if (!*r) {
2988         debug(DBG_ERR, "malloc failed");
2989         return 0;
2990     }
2991     if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2992         free(*r);
2993         *r = NULL;
2994         debug(DBG_ERR, "failed to compile regular expression %s", v);
2995         return 0;
2996     }
2997     return 1;
2998 }
2999
3000 /* should accept both names and numeric values, only numeric right now */
3001 uint8_t attrname2val(char *attrname) {
3002     int val = 0;
3003     
3004     val = atoi(attrname);
3005     return val > 0 && val < 256 ? val : 0;
3006 }
3007
3008 /* should accept both names and numeric values, only numeric right now */
3009 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3010     char *s;
3011     
3012     *vendor = atoi(attrname);
3013     s = strchr(attrname, ':');
3014     if (!s) {
3015         *type = -1;
3016         return 1;
3017     }
3018     *type = atoi(s + 1);
3019     return *type >= 0 && *type < 256;
3020 }
3021
3022 /* should accept both names and numeric values, only numeric right now */
3023 struct tlv *extractattr(char *nameval) {
3024     int len, name = 0;
3025     char *s;
3026     struct tlv *a;
3027     
3028     s = strchr(nameval, ':');
3029     name = atoi(nameval);
3030     if (!s || name < 1 || name > 255)
3031         return NULL;
3032     len = strlen(s + 1);
3033     if (len > 253)
3034         return NULL;
3035     a = malloc(sizeof(struct tlv));
3036     if (!a)
3037         return NULL;
3038     a->v = (uint8_t *)stringcopy(s + 1, 0);
3039     if (!a->v) {
3040         free(a);
3041         return NULL;
3042     }
3043     a->t = name;
3044     a->l = len;
3045     return a;
3046 }
3047
3048 /* should accept both names and numeric values, only numeric right now */
3049 struct modattr *extractmodattr(char *nameval) {
3050     int name = 0;
3051     char *s, *t;
3052     struct modattr *m;
3053
3054     if (!strncasecmp(nameval, "User-Name:/", 11)) {
3055         s = nameval + 11;
3056         name = 1;
3057     } else {
3058         s = strchr(nameval, ':');
3059         name = atoi(nameval);
3060         if (!s || name < 1 || name > 255 || s[1] != '/')
3061             return NULL;
3062         s += 2;
3063     }
3064     /* regexp, remove optional trailing / if present */
3065     if (s[strlen(s) - 1] == '/')
3066         s[strlen(s) - 1] = '\0';
3067
3068     t = strchr(s, '/');
3069     if (!t)
3070         return NULL;
3071     *t = '\0';
3072     t++;
3073
3074     m = malloc(sizeof(struct modattr));
3075     if (!m) {
3076         debug(DBG_ERR, "malloc failed");
3077         return NULL;
3078     }
3079     m->t = name;
3080
3081     m->replacement = stringcopy(t, 0);
3082     if (!m->replacement) {
3083         free(m);
3084         debug(DBG_ERR, "malloc failed");
3085         return NULL;
3086     }
3087         
3088     m->regex = malloc(sizeof(regex_t));
3089     if (!m->regex) {
3090         free(m->replacement);
3091         free(m);
3092         debug(DBG_ERR, "malloc failed");
3093         return NULL;
3094     }
3095     
3096     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
3097         free(m->regex);
3098         free(m->replacement);
3099         free(m);
3100         debug(DBG_ERR, "failed to compile regular expression %s", s);
3101         return NULL;
3102     }
3103
3104     return m;
3105 }
3106
3107 struct rewrite *getrewrite(char *alt1, char *alt2) {
3108     struct rewrite *r;
3109
3110     if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
3111         return r;
3112     if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
3113         return r;
3114     return NULL;
3115 }
3116
3117 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3118     struct rewrite *rewrite = NULL;
3119     int i, n;
3120     uint8_t *rma = NULL;
3121     uint32_t *p, *rmva = NULL;
3122     struct list *adda = NULL, *moda = NULL;
3123     struct tlv *a;
3124     struct modattr *m;
3125     
3126     if (rmattrs) {
3127         for (n = 0; rmattrs[n]; n++);
3128         rma = calloc(n + 1, sizeof(uint8_t));
3129         if (!rma)
3130             debugx(1, DBG_ERR, "malloc failed");
3131     
3132         for (i = 0; i < n; i++)
3133             if (!(rma[i] = attrname2val(rmattrs[i])))
3134                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3135         freegconfmstr(rmattrs);
3136         rma[i] = 0;
3137     }
3138     
3139     if (rmvattrs) {
3140         for (n = 0; rmvattrs[n]; n++);
3141         rmva = calloc(2 * n + 1, sizeof(uint32_t));
3142         if (!rmva)
3143             debugx(1, DBG_ERR, "malloc failed");
3144     
3145         for (p = rmva, i = 0; i < n; i++, p += 2)
3146             if (!vattrname2val(rmvattrs[i], p, p + 1))
3147                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3148         freegconfmstr(rmvattrs);
3149         *p = 0;
3150     }
3151     
3152     if (addattrs) {
3153         adda = list_create();
3154         if (!adda)
3155             debugx(1, DBG_ERR, "malloc failed");
3156         for (i = 0; addattrs[i]; i++) {
3157             a = extractattr(addattrs[i]);
3158             if (!a)
3159                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3160             if (!list_push(adda, a))
3161                 debugx(1, DBG_ERR, "malloc failed");
3162         }
3163         freegconfmstr(addattrs);
3164     }
3165
3166     if (modattrs) {
3167         moda = list_create();
3168         if (!moda)
3169             debugx(1, DBG_ERR, "malloc failed");
3170         for (i = 0; modattrs[i]; i++) {
3171             m = extractmodattr(modattrs[i]);
3172             if (!m)
3173                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3174             if (!list_push(moda, m))
3175                 debugx(1, DBG_ERR, "malloc failed");
3176         }
3177         freegconfmstr(modattrs);
3178     }
3179         
3180     if (rma || rmva || adda || moda) {
3181         rewrite = malloc(sizeof(struct rewrite));
3182         if (!rewrite)
3183             debugx(1, DBG_ERR, "malloc failed");
3184         rewrite->removeattrs = rma;
3185         rewrite->removevendorattrs = rmva;
3186         rewrite->addattrs = adda;
3187         rewrite->modattrs = moda;
3188     }
3189     
3190     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3191         debugx(1, DBG_ERR, "malloc failed");
3192     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3193 }
3194
3195 int setttlattr(struct options *opts, char *defaultattr) {
3196     char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
3197      
3198     if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
3199         (opts->ttlattrtype[1] != -1 || opts->ttlattrtype[0] < 256))
3200         return 1;
3201     debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
3202     return 0;
3203 }
3204
3205 void freeclsrvconf(struct clsrvconf *conf) {
3206     free(conf->name);
3207     free(conf->host);
3208     free(conf->port);
3209     free(conf->secret);
3210     free(conf->tls);
3211     free(conf->matchcertattr);
3212     if (conf->certcnregex)
3213         regfree(conf->certcnregex);
3214     if (conf->certuriregex)
3215         regfree(conf->certuriregex);
3216     free(conf->confrewritein);
3217     free(conf->confrewriteout);
3218     if (conf->rewriteusername) {
3219         if (conf->rewriteusername->regex)
3220             regfree(conf->rewriteusername->regex);
3221         free(conf->rewriteusername->replacement);
3222         free(conf->rewriteusername);
3223     }
3224     free(conf->dynamiclookupcommand);
3225     free(conf->rewritein);
3226     free(conf->rewriteout);
3227     if (conf->addrinfo)
3228         freeaddrinfo(conf->addrinfo);
3229     if (conf->lock) {
3230         pthread_mutex_destroy(conf->lock);
3231         free(conf->lock);
3232     }
3233     /* not touching ssl_ctx, clients and servers */
3234     free(conf);
3235 }
3236
3237 int mergeconfstring(char **dst, char **src) {
3238     char *t;
3239     
3240     if (*src) {
3241         *dst = *src;
3242         *src = NULL;
3243         return 1;
3244     }
3245     if (*dst) {
3246         t = stringcopy(*dst, 0);
3247         if (!t) {
3248             debug(DBG_ERR, "malloc failed");
3249             return 0;
3250         }
3251         *dst = t;
3252     }
3253     return 1;
3254 }
3255
3256 /* assumes dst is a shallow copy */
3257 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3258     if (!mergeconfstring(&dst->name, &src->name) ||
3259         !mergeconfstring(&dst->host, &src->host) ||
3260         !mergeconfstring(&dst->port, &src->port) ||
3261         !mergeconfstring(&dst->secret, &src->secret) ||
3262         !mergeconfstring(&dst->tls, &src->tls) ||
3263         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3264         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3265         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3266         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3267         return 0;
3268     if (src->pdef)
3269         dst->pdef = src->pdef;
3270     dst->statusserver = src->statusserver;
3271     dst->certnamecheck = src->certnamecheck;
3272     if (src->retryinterval != 255)
3273         dst->retryinterval = src->retryinterval;
3274     if (src->retrycount != 255)
3275         dst->retrycount = src->retrycount;
3276     return 1;
3277 }
3278
3279 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3280     struct clsrvconf *conf;
3281     char *conftype = NULL, *rewriteinalias = NULL;
3282     long int dupinterval = LONG_MIN, addttl = LONG_MIN;
3283     
3284     debug(DBG_DBG, "confclient_cb called for %s", block);
3285
3286     conf = malloc(sizeof(struct clsrvconf));
3287     if (!conf)
3288         debugx(1, DBG_ERR, "malloc failed");
3289     memset(conf, 0, sizeof(struct clsrvconf));
3290     conf->certnamecheck = 1;
3291     
3292     if (!getgenericconfig(cf, block,
3293                           "type", CONF_STR, &conftype,
3294                           "host", CONF_STR, &conf->host,
3295                           "secret", CONF_STR, &conf->secret,
3296                           "tls", CONF_STR, &conf->tls,
3297                           "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3298                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3299                           "DuplicateInterval", CONF_LINT, &dupinterval,
3300                           "addTTL", CONF_LINT, &addttl,
3301                           "rewrite", CONF_STR, &rewriteinalias,
3302                           "rewriteIn", CONF_STR, &conf->confrewritein,
3303                           "rewriteOut", CONF_STR, &conf->confrewriteout,
3304                           "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3305                           NULL
3306                           ))
3307         debugx(1, DBG_ERR, "configuration error");
3308     
3309     conf->name = stringcopy(val, 0);
3310     if (!conf->host)
3311         conf->host = stringcopy(val, 0);
3312     if (!conf->name || !conf->host)
3313         debugx(1, DBG_ERR, "malloc failed");
3314         
3315     if (!conftype)
3316         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3317     conf->type = protoname2int(conftype);
3318     conf->pdef = &protodefs[conf->type];
3319     if (!conf->pdef->name)
3320         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3321     free(conftype);
3322     
3323     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3324         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3325         if (!conf->tlsconf)
3326             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3327         if (conf->matchcertattr && !addmatchcertattr(conf))
3328             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3329     }
3330     
3331     if (dupinterval != LONG_MIN) {
3332         if (dupinterval < 0 || dupinterval > 255)
3333             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3334         conf->dupinterval = (uint8_t)dupinterval;
3335     } else
3336         conf->dupinterval = conf->pdef->duplicateintervaldefault;
3337     
3338     if (addttl != LONG_MIN) {
3339         if (addttl < 1 || addttl > 255)
3340             debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3341         conf->addttl = (uint8_t)addttl;
3342     }
3343     
3344     if (!conf->confrewritein)
3345         conf->confrewritein = rewriteinalias;
3346     else
3347         free(rewriteinalias);
3348     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3349     if (conf->confrewriteout)
3350         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3351     
3352     if (conf->confrewriteusername) {
3353         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3354         if (!conf->rewriteusername)
3355             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3356     }
3357     
3358     if (!resolvepeer(conf, 0))
3359         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3360     
3361     if (!conf->secret) {
3362         if (!conf->pdef->secretdefault)
3363             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3364         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3365         if (!conf->secret)
3366             debugx(1, DBG_ERR, "malloc failed");
3367     }
3368
3369     conf->lock = malloc(sizeof(pthread_mutex_t));
3370     if (!conf->lock)
3371         debugx(1, DBG_ERR, "malloc failed");
3372
3373     pthread_mutex_init(conf->lock, NULL);
3374     if (!list_push(clconfs, conf))
3375         debugx(1, DBG_ERR, "malloc failed");
3376     return 1;
3377 }
3378
3379 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3380     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3381         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3382         if (!conf->tlsconf) {
3383             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3384             return 0;
3385         }
3386         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3387             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3388             return 0;
3389         }
3390     }
3391
3392     if (!conf->port) {
3393         conf->port = stringcopy(conf->pdef->portdefault, 0);
3394         if (!conf->port) {
3395             debug(DBG_ERR, "malloc failed");
3396             return 0;
3397         }
3398     }
3399     
3400     if (conf->retryinterval == 255)
3401         conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3402     if (conf->retrycount == 255)
3403         conf->retrycount = protodefs[conf->type].retrycountdefault;
3404     
3405     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3406     if (conf->confrewriteout)
3407         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3408
3409     if (!conf->secret) {
3410         if (!conf->pdef->secretdefault) {
3411             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3412             return 0;
3413         }
3414         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3415         if (!conf->secret) {
3416             debug(DBG_ERR, "malloc failed");
3417             return 0;
3418         }
3419     }
3420     
3421     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3422         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3423         return 0;
3424     }
3425     return 1;
3426 }
3427                         
3428 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3429     struct clsrvconf *conf, *resconf;
3430     char *conftype = NULL, *rewriteinalias = NULL;
3431     long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
3432     
3433     debug(DBG_DBG, "confserver_cb called for %s", block);
3434
3435     conf = malloc(sizeof(struct clsrvconf));
3436     if (!conf) {
3437         debug(DBG_ERR, "malloc failed");
3438         return 0;
3439     }
3440     memset(conf, 0, sizeof(struct clsrvconf));
3441     resconf = (struct clsrvconf *)arg;
3442     if (resconf) {
3443         conf->statusserver = resconf->statusserver;
3444         conf->certnamecheck = resconf->certnamecheck;
3445     } else
3446         conf->certnamecheck = 1;
3447
3448     if (!getgenericconfig(cf, block,
3449                           "type", CONF_STR, &conftype,
3450                           "host", CONF_STR, &conf->host,
3451                           "port", CONF_STR, &conf->port,
3452                           "secret", CONF_STR, &conf->secret,
3453                           "tls", CONF_STR, &conf->tls,
3454                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3455                           "addTTL", CONF_LINT, &addttl,
3456                           "rewrite", CONF_STR, &rewriteinalias,
3457                           "rewriteIn", CONF_STR, &conf->confrewritein,
3458                           "rewriteOut", CONF_STR, &conf->confrewriteout,
3459                           "StatusServer", CONF_BLN, &conf->statusserver,
3460                           "RetryInterval", CONF_LINT, &retryinterval,
3461                           "RetryCount", CONF_LINT, &retrycount,
3462                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3463                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3464                           NULL
3465                           )) {
3466         debug(DBG_ERR, "configuration error");
3467         goto errexit;
3468     }
3469     
3470     conf->name = stringcopy(val, 0);
3471     if (!conf->name) {
3472         debug(DBG_ERR, "malloc failed");
3473         goto errexit;
3474     }
3475     if (!conf->host) {
3476         conf->host = stringcopy(val, 0);
3477         if (!conf->host) {
3478             debug(DBG_ERR, "malloc failed");
3479             goto errexit;
3480         }
3481     }
3482
3483     if (!conftype)
3484         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3485     conf->type = protoname2int(conftype);
3486     conf->pdef = &protodefs[conf->type];
3487     if (!conf->pdef->name) {
3488         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3489         goto errexit;
3490     }
3491     free(conftype);
3492     conftype = NULL;
3493
3494     if (!conf->confrewritein)
3495         conf->confrewritein = rewriteinalias;
3496     else
3497         free(rewriteinalias);
3498     rewriteinalias = NULL;
3499
3500     if (retryinterval != LONG_MIN) {
3501         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3502             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3503             goto errexit;
3504         }
3505         conf->retryinterval = (uint8_t)retryinterval;
3506     } else
3507         conf->retryinterval = 255;
3508     
3509     if (retrycount != LONG_MIN) {
3510         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3511             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3512             goto errexit;
3513         }
3514         conf->retrycount = (uint8_t)retrycount;
3515     } else
3516         conf->retrycount = 255;
3517     
3518     if (addttl != LONG_MIN) {
3519         if (addttl < 1 || addttl > 255) {
3520             debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3521             goto errexit;
3522         }
3523         conf->addttl = (uint8_t)addttl;
3524     }
3525     
3526     if (resconf) {
3527         if (!mergesrvconf(resconf, conf))
3528             goto errexit;
3529         free(conf);
3530         conf = resconf;
3531         if (conf->dynamiclookupcommand) {
3532             free(conf->dynamiclookupcommand);
3533             conf->dynamiclookupcommand = NULL;
3534         }
3535     }
3536
3537     if (resconf || !conf->dynamiclookupcommand) {
3538         if (!compileserverconfig(conf, block))
3539             goto errexit;
3540     }
3541     
3542     if (resconf)
3543         return 1;
3544         
3545     if (!list_push(srvconfs, conf)) {
3546         debug(DBG_ERR, "malloc failed");
3547         goto errexit;
3548     }
3549     return 1;
3550
3551  errexit:
3552     free(conftype);
3553     free(rewriteinalias);
3554     freeclsrvconf(conf);
3555     return 0;
3556 }
3557
3558 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3559     char **servers = NULL, **accservers = NULL, *msg = NULL;
3560     uint8_t accresp = 0;
3561     
3562     debug(DBG_DBG, "confrealm_cb called for %s", block);
3563     
3564     if (!getgenericconfig(cf, block,
3565                           "server", CONF_MSTR, &servers,
3566                           "accountingServer", CONF_MSTR, &accservers,
3567                           "ReplyMessage", CONF_STR, &msg,
3568                           "AccountingResponse", CONF_BLN, &accresp,
3569                           NULL
3570                           ))
3571         debugx(1, DBG_ERR, "configuration error");
3572
3573     addrealm(realms, val, servers, accservers, msg, accresp);
3574     return 1;
3575 }
3576
3577 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3578     struct tls *conf;
3579     long int expiry = LONG_MIN;
3580     
3581     debug(DBG_DBG, "conftls_cb called for %s", block);
3582     
3583     conf = malloc(sizeof(struct tls));
3584     if (!conf) {
3585         debug(DBG_ERR, "conftls_cb: malloc failed");
3586         return 0;
3587     }
3588     memset(conf, 0, sizeof(struct tls));
3589     
3590     if (!getgenericconfig(cf, block,
3591                           "CACertificateFile", CONF_STR, &conf->cacertfile,
3592                           "CACertificatePath", CONF_STR, &conf->cacertpath,
3593                           "CertificateFile", CONF_STR, &conf->certfile,
3594                           "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3595                           "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3596                           "CacheExpiry", CONF_LINT, &expiry,
3597                           "CRLCheck", CONF_BLN, &conf->crlcheck,
3598                           "PolicyOID", CONF_MSTR, &conf->policyoids,
3599                           NULL
3600                           )) {
3601         debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3602         goto errexit;
3603     }
3604     if (!conf->certfile || !conf->certkeyfile) {
3605         debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3606         goto errexit;
3607     }
3608     if (!conf->cacertfile && !conf->cacertpath) {
3609         debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3610         goto errexit;
3611     }
3612     if (expiry != LONG_MIN) {
3613         if (expiry < 0) {
3614             debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3615             goto errexit;
3616         }
3617         conf->cacheexpiry = expiry;
3618     }    
3619
3620     conf->name = stringcopy(val, 0);
3621     if (!conf->name) {
3622         debug(DBG_ERR, "conftls_cb: malloc failed");
3623         goto errexit;
3624     }
3625
3626     if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3627         debug(DBG_ERR, "conftls_cb: malloc failed");
3628         goto errexit;
3629     }
3630     if (!tlsgetctx(RAD_TLS, conf))
3631         debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3632     debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3633     return 1;
3634
3635  errexit:
3636     free(conf->cacertfile);
3637     free(conf->cacertpath);
3638     free(conf->certfile);
3639     free(conf->certkeyfile);
3640     free(conf->certkeypwd);
3641     freegconfmstr(conf->policyoids);
3642     free(conf);
3643     return 0;
3644 }
3645
3646 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3647     char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3648     
3649     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3650     
3651     if (!getgenericconfig(cf, block,
3652                           "removeAttribute", CONF_MSTR, &rmattrs,
3653                           "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3654                           "addAttribute", CONF_MSTR, &addattrs,
3655                           "modifyAttribute", CONF_MSTR, &modattrs,
3656                           NULL
3657                           ))
3658         debugx(1, DBG_ERR, "configuration error");
3659     addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3660     return 1;
3661 }
3662
3663 void getmainconfig(const char *configfile) {
3664     long int addttl = LONG_MIN, loglevel = LONG_MIN;
3665     struct gconffile *cfs;
3666
3667     cfs = openconfigfile(configfile);
3668     memset(&options, 0, sizeof(options));
3669     
3670     clconfs = list_create();
3671     if (!clconfs)
3672         debugx(1, DBG_ERR, "malloc failed");
3673     
3674     srvconfs = list_create();
3675     if (!srvconfs)
3676         debugx(1, DBG_ERR, "malloc failed");
3677     
3678     realms = list_create();
3679     if (!realms)
3680         debugx(1, DBG_ERR, "malloc failed");    
3681  
3682     tlsconfs = hash_create();
3683     if (!tlsconfs)
3684         debugx(1, DBG_ERR, "malloc failed");
3685     
3686     rewriteconfs = hash_create();
3687     if (!rewriteconfs)
3688         debugx(1, DBG_ERR, "malloc failed");    
3689  
3690     if (!getgenericconfig(&cfs, NULL,
3691                           "ListenUDP", CONF_MSTR, &options.listenargs[RAD_UDP],
3692                           "ListenTCP", CONF_MSTR, &options.listenargs[RAD_TCP],
3693                           "ListenTLS", CONF_MSTR, &options.listenargs[RAD_TLS],
3694                           "ListenDTLS", CONF_MSTR, &options.listenargs[RAD_DTLS],
3695                           "SourceUDP", CONF_STR, &options.sourcearg[RAD_UDP],
3696                           "SourceTCP", CONF_STR, &options.sourcearg[RAD_TCP],
3697                           "SourceTLS", CONF_STR, &options.sourcearg[RAD_TLS],
3698                           "SourceDTLS", CONF_STR, &options.sourcearg[RAD_DTLS],
3699                           "TTLAttribute", CONF_STR, &options.ttlattr,
3700                           "addTTL", CONF_LINT, &addttl,
3701                           "LogLevel", CONF_LINT, &loglevel,
3702                           "LogDestination", CONF_STR, &options.logdestination,
3703                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3704                           "Client", CONF_CBK, confclient_cb, NULL,
3705                           "Server", CONF_CBK, confserver_cb, NULL,
3706                           "Realm", CONF_CBK, confrealm_cb, NULL,
3707                           "TLS", CONF_CBK, conftls_cb, NULL,
3708                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3709                           NULL
3710                           ))
3711         debugx(1, DBG_ERR, "configuration error");
3712     
3713     if (loglevel != LONG_MIN) {
3714         if (loglevel < 1 || loglevel > 4)
3715             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3716         options.loglevel = (uint8_t)loglevel;
3717     }
3718     if (addttl != LONG_MIN) {
3719         if (addttl < 1 || addttl > 255)
3720             debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3721         options.addttl = (uint8_t)addttl;
3722     }
3723     if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3724         debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3725 }
3726
3727 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3728     int c;
3729
3730     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3731         switch (c) {
3732         case 'c':
3733             *configfile = optarg;
3734             break;
3735         case 'd':
3736             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3737                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3738             *loglevel = *optarg - '0';
3739             break;
3740         case 'f':
3741             *foreground = 1;
3742             break;
3743         case 'p':
3744             *pretend = 1;
3745             break;
3746         case 'v':
3747                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3748         default:
3749             goto usage;
3750         }
3751     }
3752     if (!(argc - optind))
3753         return;
3754
3755  usage:
3756     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3757 }
3758
3759 #ifdef SYS_SOLARIS9
3760 int daemon(int a, int b) {
3761     int i;
3762
3763     if (fork())
3764         exit(0);
3765
3766     setsid();
3767
3768     for (i = 0; i < 3; i++) {
3769         close(i);
3770         open("/dev/null", O_RDWR);
3771     }
3772     return 1;
3773 }
3774 #endif
3775
3776 void *sighandler(void *arg) {
3777     sigset_t sigset;
3778     int sig;
3779
3780     for(;;) {
3781         sigemptyset(&sigset);
3782         sigaddset(&sigset, SIGPIPE);
3783         sigwait(&sigset, &sig);
3784         /* only get SIGPIPE right now, so could simplify below code */
3785         switch (sig) {
3786         case 0:
3787             /* completely ignoring this */
3788             break;
3789         case SIGPIPE:
3790             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3791             break;
3792         default:
3793             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3794         }
3795     }
3796 }
3797
3798 int main(int argc, char **argv) {
3799     pthread_t sigth;
3800     sigset_t sigset;
3801     struct list_node *entry;
3802     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3803     char *configfile = NULL;
3804     struct clsrvconf *srvconf;
3805     int i;
3806     
3807     debug_init("radsecproxy");
3808     debug_set_level(DEBUG_LEVEL);
3809  
3810     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3811     if (loglevel)
3812         debug_set_level(loglevel);
3813     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3814     if (loglevel)
3815         options.loglevel = loglevel;
3816     else if (options.loglevel)
3817         debug_set_level(options.loglevel);
3818     if (!foreground)
3819         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3820     free(options.logdestination);
3821
3822     if (!list_first(clconfs))
3823         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3824     if (!list_first(realms))
3825         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3826
3827     if (pretend)
3828         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3829
3830     if (!foreground && (daemon(0, 0) < 0))
3831         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3832     
3833     debug_timestamp_on();
3834     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3835
3836     sigemptyset(&sigset);
3837     /* exit on all but SIGPIPE, ignore more? */
3838     sigaddset(&sigset, SIGPIPE);
3839     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3840     pthread_create(&sigth, NULL, sighandler, NULL);
3841
3842     memset(srcprotores, 0, sizeof(srcprotores));
3843     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3844         srvconf = (struct clsrvconf *)entry->data;
3845         if (srvconf->dynamiclookupcommand)
3846             continue;
3847         if (!addserver(srvconf))
3848             debugx(1, DBG_ERR, "failed to add server");
3849         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3850                            (void *)(srvconf->servers)))
3851             debugx(1, DBG_ERR, "pthread_create failed");
3852     }
3853
3854     for (i = 0; protodefs[i].name; i++) {
3855         if (protodefs[i].freesrcprotores && srcprotores[i]) {
3856             freeaddrinfo(srcprotores[i]);
3857             srcprotores[i] = NULL;
3858         }
3859         if (protodefs[i].initextra)
3860             protodefs[i].initextra();
3861         if (find_clconf_type(i, NULL))
3862             createlisteners(i, options.listenargs[i]);
3863     }
3864     
3865     /* just hang around doing nothing, anything to do here? */
3866     for (;;)
3867         sleep(1000);
3868 }