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