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