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