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