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