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