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