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