made it so it works with mix of dynamic and static servers for a realm
[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         goto errexit;
1914     }
1915     
1916     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
1917         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
1918         goto errexit;
1919     }
1920
1921     memset(&timeout, 0, sizeof(struct timespec));
1922     
1923     if (conf->statusserver) {
1924         gettimeofday(&server->lastrcv, NULL);
1925         gettimeofday(&laststatsrv, NULL);
1926     }
1927
1928     if (conf->pdef->connecter) {
1929         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr")) {
1930             if (server->dynamiclookuparg) {
1931                 server->dynstartup = 0;
1932                 sleep(900);
1933             }
1934             goto errexit;
1935         }
1936         server->connectionok = 1;
1937         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1938             debug(DBG_ERR, "clientwr: pthread_create failed");
1939             goto errexit;
1940         }
1941     } else
1942         server->connectionok = 1;
1943     server->dynstartup = 0;
1944     
1945     for (;;) {
1946         pthread_mutex_lock(&server->newrq_mutex);
1947         if (!server->newrq) {
1948             gettimeofday(&now, NULL);
1949             /* random 0-7 seconds */
1950             RAND_bytes(&rnd, 1);
1951             rnd /= 32;
1952             if (conf->statusserver) {
1953                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1954                 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1955                     secs = now.tv_sec;
1956                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1957                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1958             } else {
1959                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1960                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1961             }
1962 #if 0
1963             if (timeout.tv_sec > now.tv_sec)
1964                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1965 #endif      
1966             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1967             timeout.tv_sec = 0;
1968         }
1969         if (server->newrq) {
1970             debug(DBG_DBG, "clientwr: got new request");
1971             server->newrq = 0;
1972         }
1973 #if 0   
1974         else
1975             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1976 #endif  
1977         pthread_mutex_unlock(&server->newrq_mutex);
1978
1979         for (i = 0; i < MAX_REQUESTS; i++) {
1980             if (server->clientrdgone) {
1981                 pthread_join(clientrdth, NULL);
1982                 goto errexit;
1983             }
1984
1985             for (; i < MAX_REQUESTS; i++) {
1986                 rqout = server->requests + i;
1987                 if (rqout->rq) {
1988                     pthread_mutex_lock(rqout->lock);
1989                     if (rqout->rq)
1990                         break;
1991                     pthread_mutex_unlock(rqout->lock);
1992                 }
1993             }
1994                 
1995             if (i == MAX_REQUESTS)
1996                 break;
1997
1998             gettimeofday(&now, NULL);
1999             if (now.tv_sec < rqout->expiry.tv_sec) {
2000                 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2001                     timeout.tv_sec = rqout->expiry.tv_sec;
2002                 pthread_mutex_unlock(rqout->lock);
2003                 continue;
2004             }
2005
2006             if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2007                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2008                 if (conf->statusserver) {
2009                     if (*rqout->rq->buf == RAD_Status_Server) {
2010                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2011                         if (server->lostrqs < 255)
2012                             server->lostrqs++;
2013                     }
2014                 } else {
2015                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2016                     if (server->lostrqs < 255)
2017                         server->lostrqs++;
2018                 }
2019                 freerqoutdata(rqout);
2020                 pthread_mutex_unlock(rqout->lock);
2021                 continue;
2022             }
2023
2024             rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2025             if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2026                 timeout.tv_sec = rqout->expiry.tv_sec;
2027             rqout->tries++;
2028             conf->pdef->clientradput(server, rqout->rq->buf);
2029             pthread_mutex_unlock(rqout->lock);
2030         }
2031         if (conf->statusserver && server->connectionok) {
2032             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2033             gettimeofday(&now, NULL);
2034             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2035                 laststatsrv = now;
2036                 statsrvrq = createstatsrvrq();
2037                 if (statsrvrq) {
2038                     statsrvrq->to = server;
2039                     debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2040                     sendrq(statsrvrq);
2041                 }
2042             }
2043         }
2044     }
2045  errexit:
2046     conf->servers = NULL;
2047     if (server->dynamiclookuparg) {
2048         removeserversubrealms(realms, conf);
2049         if (dynconffail)
2050             free(conf);
2051         else
2052             freeclsrvconf(conf);
2053     }
2054     freeserver(server, 1);
2055     ERR_remove_state(0);
2056     return NULL;
2057 }
2058
2059 void createlistener(uint8_t type, char *arg) {
2060     pthread_t th;
2061     struct clsrvconf *listenres;
2062     struct addrinfo *res;
2063     int s = -1, on = 1, *sp = NULL;
2064     
2065     listenres = resolve_hostport(type, arg, protodefs[type]->portdefault);
2066     if (!listenres)
2067         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2068     
2069     for (res = listenres->addrinfo; res; res = res->ai_next) {
2070         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2071         if (s < 0) {
2072             debug(DBG_WARN, "createlistener: socket failed");
2073             continue;
2074         }
2075         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2076 #ifdef IPV6_V6ONLY
2077         if (res->ai_family == AF_INET6)
2078             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2079 #endif          
2080         if (bind(s, res->ai_addr, res->ai_addrlen)) {
2081             debug(DBG_WARN, "createlistener: bind failed");
2082             close(s);
2083             s = -1;
2084             continue;
2085         }
2086
2087         sp = malloc(sizeof(int));
2088         if (!sp)
2089             debugx(1, DBG_ERR, "malloc failed");
2090         *sp = s;
2091         if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
2092             debugx(1, DBG_ERR, "pthread_create failed");
2093         pthread_detach(th);
2094     }
2095     if (!sp)
2096         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2097     
2098     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name,
2099           listenres->host ? listenres->host : "*", listenres->port);
2100     freeclsrvres(listenres);
2101 }
2102
2103 void createlisteners(uint8_t type) {
2104     int i;
2105     char **args;
2106
2107     args = protodefs[type]->getlistenerargs();
2108     if (args)
2109         for (i = 0; args[i]; i++)
2110             createlistener(type, args[i]);
2111     else
2112         createlistener(type, NULL);
2113 }
2114
2115 void sslinit() {
2116     int i;
2117     time_t t;
2118     pid_t pid;
2119     
2120     ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2121     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2122     for (i = 0; i < CRYPTO_num_locks(); i++) {
2123         ssl_lock_count[i] = 0;
2124         pthread_mutex_init(&ssl_locks[i], NULL);
2125     }
2126     CRYPTO_set_id_callback(ssl_thread_id);
2127     CRYPTO_set_locking_callback(ssl_locking_callback);
2128
2129     SSL_load_error_strings();
2130     SSL_library_init();
2131
2132     while (!RAND_status()) {
2133         t = time(NULL);
2134         pid = getpid();
2135         RAND_seed((unsigned char *)&t, sizeof(time_t));
2136         RAND_seed((unsigned char *)&pid, sizeof(pid));
2137     }
2138 }
2139
2140 struct list *addsrvconfs(char *value, char **names) {
2141     struct list *conflist;
2142     int n;
2143     struct list_node *entry;
2144     struct clsrvconf *conf = NULL;
2145     
2146     if (!names || !*names)
2147         return NULL;
2148     
2149     conflist = list_create();
2150     if (!conflist) {
2151         debug(DBG_ERR, "malloc failed");
2152         return NULL;
2153     }
2154
2155     for (n = 0; names[n]; n++) {
2156         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2157             conf = (struct clsrvconf *)entry->data;
2158             if (!strcasecmp(names[n], conf->name))
2159                 break;
2160         }
2161         if (!entry) {
2162             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2163             list_destroy(conflist);
2164             return NULL;
2165         }
2166         if (!list_push(conflist, conf)) {
2167             debug(DBG_ERR, "malloc failed");
2168             list_destroy(conflist);
2169             return NULL;
2170         }
2171         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2172     }
2173     return conflist;
2174 }
2175
2176 void freerealm(struct realm *realm) {
2177     if (!realm)
2178         return;
2179     debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2180     if (--realm->refcount)
2181         return;
2182
2183     free(realm->name);
2184     free(realm->message);
2185     regfree(&realm->regex);
2186     pthread_mutex_destroy(&realm->mutex);
2187     /* if refcount == 0, all subrealms gone */
2188     list_destroy(realm->subrealms);
2189     /* if refcount == 0, all srvconfs gone */
2190     list_destroy(realm->srvconfs);
2191     /* if refcount == 0, all accsrvconfs gone */
2192     list_destroy(realm->accsrvconfs);
2193     freerealm(realm->parent);
2194     free(realm);
2195 }
2196
2197 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2198     int n;
2199     struct realm *realm;
2200     char *s, *regex = NULL;
2201     
2202     if (*value == '/') {
2203         /* regexp, remove optional trailing / if present */
2204         if (value[strlen(value) - 1] == '/')
2205             value[strlen(value) - 1] = '\0';
2206     } else {
2207         /* not a regexp, let us make it one */
2208         if (*value == '*' && !value[1])
2209             regex = stringcopy(".*", 0);
2210         else {
2211             for (n = 0, s = value; *s;)
2212                 if (*s++ == '.')
2213                     n++;
2214             regex = malloc(strlen(value) + n + 3);
2215             if (regex) {
2216                 regex[0] = '@';
2217                 for (n = 1, s = value; *s; s++) {
2218                     if (*s == '.')
2219                         regex[n++] = '\\';
2220                     regex[n++] = *s;
2221                 }
2222                 regex[n++] = '$';
2223                 regex[n] = '\0';
2224             }
2225         }
2226         if (!regex) {
2227             debug(DBG_ERR, "malloc failed");
2228             realm = NULL;
2229             goto exit;
2230         }
2231         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2232     }
2233
2234     realm = malloc(sizeof(struct realm));
2235     if (!realm) {
2236         debug(DBG_ERR, "malloc failed");
2237         goto exit;
2238     }
2239     memset(realm, 0, sizeof(struct realm));
2240     
2241     if (pthread_mutex_init(&realm->mutex, NULL)) {
2242         debug(DBG_ERR, "mutex init failed");
2243         free(realm);
2244         realm = NULL;
2245         goto exit;
2246     }
2247
2248     realm->name = stringcopy(value, 0);
2249     if (!realm->name) {
2250         debug(DBG_ERR, "malloc failed");
2251         goto errexit;
2252     }
2253     if (message && strlen(message) > 253) {
2254         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2255         goto errexit;
2256     }
2257     realm->message = message;
2258     realm->accresp = accresp;
2259     
2260     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2261         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2262         goto errexit;
2263     }
2264     
2265     if (servers && *servers) {
2266         realm->srvconfs = addsrvconfs(value, servers);
2267         if (!realm->srvconfs)
2268             goto errexit;
2269     }
2270     
2271     if (accservers && *accservers) {
2272         realm->accsrvconfs = addsrvconfs(value, accservers);
2273         if (!realm->accsrvconfs)
2274             goto errexit;
2275     }
2276
2277     if (!list_push(realmlist, realm)) {
2278         debug(DBG_ERR, "malloc failed");
2279         pthread_mutex_destroy(&realm->mutex);
2280         goto errexit;
2281     }
2282     
2283     debug(DBG_DBG, "addrealm: added realm %s", value);
2284     goto exit;
2285
2286  errexit:
2287     while (list_shift(realm->srvconfs));
2288     while (list_shift(realm->accsrvconfs));
2289     freerealm(realm);
2290     realm = NULL;
2291  exit:
2292     free(regex);
2293     if (servers) {
2294         if (realm)
2295             for (n = 0; servers[n]; n++)
2296                 newrealmref(realm);
2297         freegconfmstr(servers);
2298     }
2299     if (accservers) {
2300         if (realm)
2301             for (n = 0; accservers[n]; n++)
2302                 newrealmref(realm);
2303         freegconfmstr(accservers);
2304     }
2305     return newrealmref(realm);
2306 }
2307
2308 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2309     struct list_node *entry;
2310     struct clsrvconf *conf, *srvconf;
2311     struct list *subrealmservers = NULL;
2312     pthread_t clientth;
2313
2314     if (list_first(srvconfs)) {
2315         subrealmservers = list_create();
2316         if (!subrealmservers)
2317             return NULL;
2318     }
2319     
2320     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2321         conf = (struct clsrvconf *)entry->data;
2322         if (!conf->servers && conf->dynamiclookupcommand) {
2323             srvconf = malloc(sizeof(struct clsrvconf));
2324             if (!srvconf) {
2325                 debug(DBG_ERR, "malloc failed");
2326                 continue;
2327             }
2328             *srvconf = *conf;
2329             if (addserver(srvconf)) {
2330                 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2331                 srvconf->servers->dynstartup = 1;
2332                 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2333                     debug(DBG_ERR, "pthread_create failed");
2334                     freeserver(srvconf->servers, 1);
2335                     srvconf->servers = NULL;
2336                 } else
2337                     pthread_detach(clientth);
2338             }
2339             conf = srvconf;
2340         }
2341         if (conf->servers) {
2342             if (list_push(subrealmservers, conf))
2343                 newrealmref(realm);
2344             else
2345                 debug(DBG_ERR, "malloc failed");
2346         }
2347     }
2348     return subrealmservers;
2349 }
2350     
2351 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2352     struct realm *newrealm = NULL;
2353     char *realmname, *s;
2354     
2355     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2356     realmname = strrchr(id, '@');
2357     if (!realmname)
2358         return NULL;
2359     realmname++;
2360     if (!*realmname)
2361         return NULL;
2362     for (s = realmname; *s; s++)
2363         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2364             return NULL;
2365     
2366     if (!realm->subrealms)
2367         realm->subrealms = list_create();
2368     if (!realm->subrealms)
2369         return NULL;
2370     
2371     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2372     if (!newrealm) {
2373         list_destroy(realm->subrealms);
2374         realm->subrealms = NULL;
2375         return NULL;
2376     }
2377
2378     newrealm->parent = newrealmref(realm);
2379     /* add server and accserver to newrealm */
2380     newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2381     newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2382     return newrealm;
2383 }
2384
2385 int dynamicconfig(struct server *server) {
2386     int ok, fd[2], status;
2387     pid_t pid;
2388     struct clsrvconf *conf = server->conf;
2389     struct gconffile *cf = NULL;
2390     
2391     /* for now we only learn hostname/address */
2392     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2393
2394     if (pipe(fd) > 0) {
2395         debug(DBG_ERR, "dynamicconfig: pipe error");
2396         goto errexit;
2397     }
2398     pid = fork();
2399     if (pid < 0) {
2400         debug(DBG_ERR, "dynamicconfig: fork error");
2401         close(fd[0]);
2402         close(fd[1]);
2403         goto errexit;
2404     } else if (pid == 0) {
2405         /* child */
2406         close(fd[0]);
2407         if (fd[1] != STDOUT_FILENO) {
2408             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2409                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2410             close(fd[1]);
2411         }
2412         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2413             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2414     }
2415
2416     close(fd[1]);
2417     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2418     ok = getgenericconfig(&cf, NULL,
2419                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2420                           NULL
2421                           );
2422     freegconf(&cf);
2423         
2424     if (waitpid(pid, &status, 0) < 0) {
2425         debug(DBG_ERR, "dynamicconfig: wait error");
2426         goto errexit;
2427     }
2428     
2429     if (status) {
2430         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2431         goto errexit;
2432     }
2433
2434     if (ok)
2435         return 1;
2436
2437  errexit:    
2438     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2439     return 0;
2440 }
2441
2442 /* should accept both names and numeric values, only numeric right now */
2443 uint8_t attrname2val(char *attrname) {
2444     int val = 0;
2445     
2446     val = atoi(attrname);
2447     return val > 0 && val < 256 ? val : 0;
2448 }
2449
2450 /* should accept both names and numeric values, only numeric right now */
2451 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2452     char *s;
2453     
2454     *vendor = atoi(attrname);
2455     s = strchr(attrname, ':');
2456     if (!s) {
2457         *type = 256;
2458         return 1;
2459     }
2460     *type = atoi(s + 1);
2461     return *type < 256;
2462 }
2463
2464 /* should accept both names and numeric values, only numeric right now */
2465 struct tlv *extractattr(char *nameval) {
2466     int len, name = 0;
2467     char *s;
2468     struct tlv *a;
2469     
2470     s = strchr(nameval, ':');
2471     name = atoi(nameval);
2472     if (!s || name < 1 || name > 255)
2473         return NULL;
2474     len = strlen(s + 1);
2475     if (len > 253)
2476         return NULL;
2477     a = malloc(sizeof(struct tlv));
2478     if (!a)
2479         return NULL;
2480     a->v = (uint8_t *)stringcopy(s + 1, 0);
2481     if (!a->v) {
2482         free(a);
2483         return NULL;
2484     }
2485     a->t = name;
2486     a->l = len;
2487     return a;
2488 }
2489
2490 /* should accept both names and numeric values, only numeric right now */
2491 struct modattr *extractmodattr(char *nameval) {
2492     int name = 0;
2493     char *s, *t;
2494     struct modattr *m;
2495
2496     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2497         s = nameval + 11;
2498         name = 1;
2499     } else {
2500         s = strchr(nameval, ':');
2501         name = atoi(nameval);
2502         if (!s || name < 1 || name > 255 || s[1] != '/')
2503             return NULL;
2504         s += 2;
2505     }
2506     /* regexp, remove optional trailing / if present */
2507     if (s[strlen(s) - 1] == '/')
2508         s[strlen(s) - 1] = '\0';
2509
2510     t = strchr(s, '/');
2511     if (!t)
2512         return NULL;
2513     *t = '\0';
2514     t++;
2515
2516     m = malloc(sizeof(struct modattr));
2517     if (!m) {
2518         debug(DBG_ERR, "malloc failed");
2519         return NULL;
2520     }
2521     m->t = name;
2522
2523     m->replacement = stringcopy(t, 0);
2524     if (!m->replacement) {
2525         free(m);
2526         debug(DBG_ERR, "malloc failed");
2527         return NULL;
2528     }
2529         
2530     m->regex = malloc(sizeof(regex_t));
2531     if (!m->regex) {
2532         free(m->replacement);
2533         free(m);
2534         debug(DBG_ERR, "malloc failed");
2535         return NULL;
2536     }
2537     
2538     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2539         free(m->regex);
2540         free(m->replacement);
2541         free(m);
2542         debug(DBG_ERR, "failed to compile regular expression %s", s);
2543         return NULL;
2544     }
2545
2546     return m;
2547 }
2548
2549 struct rewrite *getrewrite(char *alt1, char *alt2) {
2550     struct rewrite *r;
2551
2552     if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
2553         return r;
2554     if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
2555         return r;
2556     return NULL;
2557 }
2558
2559 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2560     struct rewrite *rewrite = NULL;
2561     int i, n;
2562     uint8_t *rma = NULL;
2563     uint32_t *p, *rmva = NULL;
2564     struct list *adda = NULL, *moda = NULL;
2565     struct tlv *a;
2566     struct modattr *m;
2567     
2568     if (rmattrs) {
2569         for (n = 0; rmattrs[n]; n++);
2570         rma = calloc(n + 1, sizeof(uint8_t));
2571         if (!rma)
2572             debugx(1, DBG_ERR, "malloc failed");
2573     
2574         for (i = 0; i < n; i++)
2575             if (!(rma[i] = attrname2val(rmattrs[i])))
2576                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2577         freegconfmstr(rmattrs);
2578         rma[i] = 0;
2579     }
2580     
2581     if (rmvattrs) {
2582         for (n = 0; rmvattrs[n]; n++);
2583         rmva = calloc(2 * n + 1, sizeof(uint32_t));
2584         if (!rmva)
2585             debugx(1, DBG_ERR, "malloc failed");
2586     
2587         for (p = rmva, i = 0; i < n; i++, p += 2)
2588             if (!vattrname2val(rmvattrs[i], p, p + 1))
2589                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2590         freegconfmstr(rmvattrs);
2591         *p = 0;
2592     }
2593     
2594     if (addattrs) {
2595         adda = list_create();
2596         if (!adda)
2597             debugx(1, DBG_ERR, "malloc failed");
2598         for (i = 0; addattrs[i]; i++) {
2599             a = extractattr(addattrs[i]);
2600             if (!a)
2601                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2602             if (!list_push(adda, a))
2603                 debugx(1, DBG_ERR, "malloc failed");
2604         }
2605         freegconfmstr(addattrs);
2606     }
2607
2608     if (modattrs) {
2609         moda = list_create();
2610         if (!moda)
2611             debugx(1, DBG_ERR, "malloc failed");
2612         for (i = 0; modattrs[i]; i++) {
2613             m = extractmodattr(modattrs[i]);
2614             if (!m)
2615                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2616             if (!list_push(moda, m))
2617                 debugx(1, DBG_ERR, "malloc failed");
2618         }
2619         freegconfmstr(modattrs);
2620     }
2621         
2622     if (rma || rmva || adda || moda) {
2623         rewrite = malloc(sizeof(struct rewrite));
2624         if (!rewrite)
2625             debugx(1, DBG_ERR, "malloc failed");
2626         rewrite->removeattrs = rma;
2627         rewrite->removevendorattrs = rmva;
2628         rewrite->addattrs = adda;
2629         rewrite->modattrs = moda;
2630     }
2631     
2632     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2633         debugx(1, DBG_ERR, "malloc failed");
2634     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2635 }
2636
2637 int setttlattr(struct options *opts, char *defaultattr) {
2638     char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2639      
2640     if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2641         (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2642         return 1;
2643     debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2644     return 0;
2645 }
2646
2647 void freeclsrvconf(struct clsrvconf *conf) {
2648     free(conf->name);
2649     free(conf->host);
2650     free(conf->port);
2651     free(conf->secret);
2652     free(conf->tls);
2653     free(conf->matchcertattr);
2654     if (conf->certcnregex)
2655         regfree(conf->certcnregex);
2656     if (conf->certuriregex)
2657         regfree(conf->certuriregex);
2658     free(conf->confrewritein);
2659     free(conf->confrewriteout);
2660     if (conf->rewriteusername) {
2661         if (conf->rewriteusername->regex)
2662             regfree(conf->rewriteusername->regex);
2663         free(conf->rewriteusername->replacement);
2664         free(conf->rewriteusername);
2665     }
2666     free(conf->dynamiclookupcommand);
2667     free(conf->rewritein);
2668     free(conf->rewriteout);
2669     if (conf->addrinfo)
2670         freeaddrinfo(conf->addrinfo);
2671     if (conf->lock) {
2672         pthread_mutex_destroy(conf->lock);
2673         free(conf->lock);
2674     }
2675     /* not touching ssl_ctx, clients and servers */
2676     free(conf);
2677 }
2678
2679 int mergeconfstring(char **dst, char **src) {
2680     char *t;
2681     
2682     if (*src) {
2683         *dst = *src;
2684         *src = NULL;
2685         return 1;
2686     }
2687     if (*dst) {
2688         t = stringcopy(*dst, 0);
2689         if (!t) {
2690             debug(DBG_ERR, "malloc failed");
2691             return 0;
2692         }
2693         *dst = t;
2694     }
2695     return 1;
2696 }
2697
2698 /* assumes dst is a shallow copy */
2699 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2700     if (!mergeconfstring(&dst->name, &src->name) ||
2701         !mergeconfstring(&dst->host, &src->host) ||
2702         !mergeconfstring(&dst->port, &src->port) ||
2703         !mergeconfstring(&dst->secret, &src->secret) ||
2704         !mergeconfstring(&dst->tls, &src->tls) ||
2705         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2706         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2707         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2708         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2709         return 0;
2710     if (src->pdef)
2711         dst->pdef = src->pdef;
2712     dst->statusserver = src->statusserver;
2713     dst->certnamecheck = src->certnamecheck;
2714     if (src->retryinterval != 255)
2715         dst->retryinterval = src->retryinterval;
2716     if (src->retrycount != 255)
2717         dst->retrycount = src->retrycount;
2718     return 1;
2719 }
2720
2721 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2722     struct clsrvconf *conf;
2723     char *conftype = NULL, *rewriteinalias = NULL;
2724     long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2725     
2726     debug(DBG_DBG, "confclient_cb called for %s", block);
2727
2728     conf = malloc(sizeof(struct clsrvconf));
2729     if (!conf)
2730         debugx(1, DBG_ERR, "malloc failed");
2731     memset(conf, 0, sizeof(struct clsrvconf));
2732     conf->certnamecheck = 1;
2733     
2734     if (!getgenericconfig(cf, block,
2735                           "type", CONF_STR, &conftype,
2736                           "host", CONF_STR, &conf->host,
2737                           "secret", CONF_STR, &conf->secret,
2738 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)    
2739                           "tls", CONF_STR, &conf->tls,
2740                           "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2741                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2742 #endif                    
2743                           "DuplicateInterval", CONF_LINT, &dupinterval,
2744                           "addTTL", CONF_LINT, &addttl,
2745                           "rewrite", CONF_STR, &rewriteinalias,
2746                           "rewriteIn", CONF_STR, &conf->confrewritein,
2747                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2748                           "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2749                           NULL
2750                           ))
2751         debugx(1, DBG_ERR, "configuration error");
2752     
2753     conf->name = stringcopy(val, 0);
2754     if (!conf->host)
2755         conf->host = stringcopy(val, 0);
2756     if (!conf->name || !conf->host)
2757         debugx(1, DBG_ERR, "malloc failed");
2758         
2759     if (!conftype)
2760         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2761     conf->type = protoname2int(conftype);
2762     if (conf->type == 255)
2763         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2764     free(conftype);
2765     conf->pdef = protodefs[conf->type];
2766
2767 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)    
2768     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2769         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2770         if (!conf->tlsconf)
2771             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2772         if (conf->matchcertattr && !addmatchcertattr(conf))
2773             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2774     }
2775 #endif
2776     
2777     if (dupinterval != LONG_MIN) {
2778         if (dupinterval < 0 || dupinterval > 255)
2779             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2780         conf->dupinterval = (uint8_t)dupinterval;
2781     } else
2782         conf->dupinterval = conf->pdef->duplicateintervaldefault;
2783     
2784     if (addttl != LONG_MIN) {
2785         if (addttl < 1 || addttl > 255)
2786             debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2787         conf->addttl = (uint8_t)addttl;
2788     }
2789     
2790     if (!conf->confrewritein)
2791         conf->confrewritein = rewriteinalias;
2792     else
2793         free(rewriteinalias);
2794     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2795     if (conf->confrewriteout)
2796         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2797     
2798     if (conf->confrewriteusername) {
2799         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2800         if (!conf->rewriteusername)
2801             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2802     }
2803     
2804     if (!resolvepeer(conf, 0))
2805         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2806     
2807     if (!conf->secret) {
2808         if (!conf->pdef->secretdefault)
2809             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2810         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2811         if (!conf->secret)
2812             debugx(1, DBG_ERR, "malloc failed");
2813     }
2814
2815     conf->lock = malloc(sizeof(pthread_mutex_t));
2816     if (!conf->lock)
2817         debugx(1, DBG_ERR, "malloc failed");
2818
2819     pthread_mutex_init(conf->lock, NULL);
2820     if (!list_push(clconfs, conf))
2821         debugx(1, DBG_ERR, "malloc failed");
2822     return 1;
2823 }
2824
2825 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2826 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)    
2827     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2828         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2829         if (!conf->tlsconf) {
2830             debug(DBG_ERR, "error in block %s, no tls context defined", block);
2831             return 0;
2832         }
2833         if (conf->matchcertattr && !addmatchcertattr(conf)) {
2834             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2835             return 0;
2836         }
2837     }
2838 #endif
2839     
2840     if (!conf->port) {
2841         conf->port = stringcopy(conf->pdef->portdefault, 0);
2842         if (!conf->port) {
2843             debug(DBG_ERR, "malloc failed");
2844             return 0;
2845         }
2846     }
2847     
2848     if (conf->retryinterval == 255)
2849         conf->retryinterval = conf->pdef->retryintervaldefault;
2850     if (conf->retrycount == 255)
2851         conf->retrycount = conf->pdef->retrycountdefault;
2852     
2853     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2854     if (conf->confrewriteout)
2855         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2856
2857     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
2858         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2859         return 0;
2860     }
2861     return 1;
2862 }
2863                         
2864 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2865     struct clsrvconf *conf, *resconf;
2866     char *conftype = NULL, *rewriteinalias = NULL;
2867     long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2868     
2869     debug(DBG_DBG, "confserver_cb called for %s", block);
2870
2871     conf = malloc(sizeof(struct clsrvconf));
2872     if (!conf) {
2873         debug(DBG_ERR, "malloc failed");
2874         return 0;
2875     }
2876     memset(conf, 0, sizeof(struct clsrvconf));
2877     resconf = (struct clsrvconf *)arg;
2878     if (resconf) {
2879         conf->statusserver = resconf->statusserver;
2880         conf->certnamecheck = resconf->certnamecheck;
2881     } else
2882         conf->certnamecheck = 1;
2883
2884     if (!getgenericconfig(cf, block,
2885                           "type", CONF_STR, &conftype,
2886                           "host", CONF_STR, &conf->host,
2887                           "port", CONF_STR, &conf->port,
2888                           "secret", CONF_STR, &conf->secret,
2889 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)    
2890                           "tls", CONF_STR, &conf->tls,
2891                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2892                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2893 #endif                    
2894                           "addTTL", CONF_LINT, &addttl,
2895                           "rewrite", CONF_STR, &rewriteinalias,
2896                           "rewriteIn", CONF_STR, &conf->confrewritein,
2897                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2898                           "StatusServer", CONF_BLN, &conf->statusserver,
2899                           "RetryInterval", CONF_LINT, &retryinterval,
2900                           "RetryCount", CONF_LINT, &retrycount,
2901                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2902                           NULL
2903                           )) {
2904         debug(DBG_ERR, "configuration error");
2905         goto errexit;
2906     }
2907     
2908     conf->name = stringcopy(val, 0);
2909     if (!conf->name) {
2910         debug(DBG_ERR, "malloc failed");
2911         goto errexit;
2912     }
2913     if (!conf->host) {
2914         conf->host = stringcopy(val, 0);
2915         if (!conf->host) {
2916             debug(DBG_ERR, "malloc failed");
2917             goto errexit;
2918         }
2919     }
2920
2921     if (!conftype) {
2922         debug(DBG_ERR, "error in block %s, option type missing", block);
2923         goto errexit;
2924     }
2925     conf->type = protoname2int(conftype);
2926     if (conf->type == 255) {
2927         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2928         goto errexit;
2929     }
2930     free(conftype);
2931     conftype = NULL;
2932         
2933     conf->pdef = protodefs[conf->type];
2934
2935     if (!conf->confrewritein)
2936         conf->confrewritein = rewriteinalias;
2937     else
2938         free(rewriteinalias);
2939     rewriteinalias = NULL;
2940
2941     if (retryinterval != LONG_MIN) {
2942         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2943             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2944             goto errexit;
2945         }
2946         conf->retryinterval = (uint8_t)retryinterval;
2947     } else
2948         conf->retryinterval = 255;
2949     
2950     if (retrycount != LONG_MIN) {
2951         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2952             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2953             goto errexit;
2954         }
2955         conf->retrycount = (uint8_t)retrycount;
2956     } else
2957         conf->retrycount = 255;
2958     
2959     if (addttl != LONG_MIN) {
2960         if (addttl < 1 || addttl > 255) {
2961             debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2962             goto errexit;
2963         }
2964         conf->addttl = (uint8_t)addttl;
2965     }
2966     
2967     if (resconf) {
2968         if (!mergesrvconf(resconf, conf))
2969             goto errexit;
2970         free(conf);
2971         conf = resconf;
2972         if (conf->dynamiclookupcommand) {
2973             free(conf->dynamiclookupcommand);
2974             conf->dynamiclookupcommand = NULL;
2975         }
2976     }
2977
2978     if (resconf || !conf->dynamiclookupcommand) {
2979         if (!compileserverconfig(conf, block))
2980             goto errexit;
2981     }
2982     
2983     if (!conf->secret) {
2984         if (!conf->pdef->secretdefault) {
2985             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2986             return 0;
2987         }
2988         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2989         if (!conf->secret) {
2990             debug(DBG_ERR, "malloc failed");
2991             return 0;
2992         }
2993     }
2994     
2995     if (resconf)
2996         return 1;
2997
2998     if (!list_push(srvconfs, conf)) {
2999         debug(DBG_ERR, "malloc failed");
3000         goto errexit;
3001     }
3002     return 1;
3003
3004  errexit:
3005     free(conftype);
3006     free(rewriteinalias);
3007     freeclsrvconf(conf);
3008     return 0;
3009 }
3010
3011 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3012     char **servers = NULL, **accservers = NULL, *msg = NULL;
3013     uint8_t accresp = 0;
3014     
3015     debug(DBG_DBG, "confrealm_cb called for %s", block);
3016     
3017     if (!getgenericconfig(cf, block,
3018                           "server", CONF_MSTR, &servers,
3019                           "accountingServer", CONF_MSTR, &accservers,
3020                           "ReplyMessage", CONF_STR, &msg,
3021                           "AccountingResponse", CONF_BLN, &accresp,
3022                           NULL
3023                           ))
3024         debugx(1, DBG_ERR, "configuration error");
3025
3026     addrealm(realms, val, servers, accservers, msg, accresp);
3027     return 1;
3028 }
3029
3030 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3031     char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3032     
3033     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3034     
3035     if (!getgenericconfig(cf, block,
3036                           "removeAttribute", CONF_MSTR, &rmattrs,
3037                           "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3038                           "addAttribute", CONF_MSTR, &addattrs,
3039                           "modifyAttribute", CONF_MSTR, &modattrs,
3040                           NULL
3041                           ))
3042         debugx(1, DBG_ERR, "configuration error");
3043     addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3044     return 1;
3045 }
3046
3047 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3048     struct commonprotoopts *protoopts;
3049
3050     protoopts = malloc(sizeof(struct commonprotoopts));
3051     if (!protoopts)
3052         return 0;
3053     memset(protoopts, 0, sizeof(struct commonprotoopts));
3054     protoopts->listenargs = listenargs;
3055     protoopts->sourcearg = sourcearg;
3056     protodefs[type]->setprotoopts(protoopts);
3057     return 1;
3058 }
3059
3060 void getmainconfig(const char *configfile) {
3061     long int addttl = LONG_MIN, loglevel = LONG_MIN;
3062     struct gconffile *cfs;
3063     char **listenargs[RAD_PROTOCOUNT];
3064     char *sourcearg[RAD_PROTOCOUNT];
3065     int i;
3066     
3067     cfs = openconfigfile(configfile);
3068     memset(&options, 0, sizeof(options));
3069     memset(&listenargs, 0, sizeof(listenargs));
3070     memset(&sourcearg, 0, sizeof(sourcearg));
3071     
3072     clconfs = list_create();
3073     if (!clconfs)
3074         debugx(1, DBG_ERR, "malloc failed");
3075     
3076     srvconfs = list_create();
3077     if (!srvconfs)
3078         debugx(1, DBG_ERR, "malloc failed");
3079     
3080     realms = list_create();
3081     if (!realms)
3082         debugx(1, DBG_ERR, "malloc failed");    
3083  
3084     rewriteconfs = hash_create();
3085     if (!rewriteconfs)
3086         debugx(1, DBG_ERR, "malloc failed");    
3087  
3088     if (!getgenericconfig(&cfs, NULL,
3089 #ifdef RADPROT_UDP                        
3090                           "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3091                           "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3092 #endif                    
3093 #ifdef RADPROT_TCP                        
3094                           "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3095                           "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3096 #endif                    
3097 #ifdef RADPROT_TLS
3098                           "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3099                           "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3100 #endif                    
3101 #ifdef RADPROT_DTLS
3102                           "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3103                           "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3104 #endif                    
3105                           "TTLAttribute", CONF_STR, &options.ttlattr,
3106                           "addTTL", CONF_LINT, &addttl,
3107                           "LogLevel", CONF_LINT, &loglevel,
3108                           "LogDestination", CONF_STR, &options.logdestination,
3109                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3110                           "Client", CONF_CBK, confclient_cb, NULL,
3111                           "Server", CONF_CBK, confserver_cb, NULL,
3112                           "Realm", CONF_CBK, confrealm_cb, NULL,
3113 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)                         
3114                           "TLS", CONF_CBK, conftls_cb, NULL,
3115 #endif                    
3116                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3117                           NULL
3118                           ))
3119         debugx(1, DBG_ERR, "configuration error");
3120     
3121     if (loglevel != LONG_MIN) {
3122         if (loglevel < 1 || loglevel > 4)
3123             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3124         options.loglevel = (uint8_t)loglevel;
3125     }
3126     if (addttl != LONG_MIN) {
3127         if (addttl < 1 || addttl > 255)
3128             debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3129         options.addttl = (uint8_t)addttl;
3130     }
3131     if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3132         debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3133
3134     for (i = 0; i < RAD_PROTOCOUNT; i++)
3135         if (listenargs[i] || sourcearg[i])
3136             setprotoopts(i, listenargs[i], sourcearg[i]);
3137 }
3138
3139 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3140     int c;
3141
3142     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3143         switch (c) {
3144         case 'c':
3145             *configfile = optarg;
3146             break;
3147         case 'd':
3148             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3149                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3150             *loglevel = *optarg - '0';
3151             break;
3152         case 'f':
3153             *foreground = 1;
3154             break;
3155         case 'p':
3156             *pretend = 1;
3157             break;
3158         case 'v':
3159                 debug(DBG_ERR, "radsecproxy revision $Rev$");
3160                 debug(DBG_ERR, "This binary was built with support for the following transports:");
3161 #ifdef RADPROT_UDP
3162                 debug(DBG_ERR, "  UDP");
3163 #endif          
3164 #ifdef RADPROT_TCP
3165                 debug(DBG_ERR, "  TCP");
3166 #endif          
3167 #ifdef RADPROT_TLS
3168                 debug(DBG_ERR, "  TLS");
3169 #endif          
3170 #ifdef RADPROT_DTLS
3171                 debug(DBG_ERR, "  DTLS");
3172 #endif
3173                 exit(0);
3174         default:
3175             goto usage;
3176         }
3177     }
3178     if (!(argc - optind))
3179         return;
3180
3181  usage:
3182     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3183 }
3184
3185 #ifdef SYS_SOLARIS9
3186 int daemon(int a, int b) {
3187     int i;
3188
3189     if (fork())
3190         exit(0);
3191
3192     setsid();
3193
3194     for (i = 0; i < 3; i++) {
3195         close(i);
3196         open("/dev/null", O_RDWR);
3197     }
3198     return 1;
3199 }
3200 #endif
3201
3202 void *sighandler(void *arg) {
3203     sigset_t sigset;
3204     int sig;
3205
3206     for(;;) {
3207         sigemptyset(&sigset);
3208         sigaddset(&sigset, SIGPIPE);
3209         sigwait(&sigset, &sig);
3210         /* only get SIGPIPE right now, so could simplify below code */
3211         switch (sig) {
3212         case 0:
3213             /* completely ignoring this */
3214             break;
3215         case SIGPIPE:
3216             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3217             break;
3218         default:
3219             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3220         }
3221     }
3222 }
3223
3224 int main(int argc, char **argv) {
3225     pthread_t sigth;
3226     sigset_t sigset;
3227     struct list_node *entry;
3228     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3229     char *configfile = NULL;
3230     struct clsrvconf *srvconf;
3231     int i;
3232     
3233     debug_init("radsecproxy");
3234     debug_set_level(DEBUG_LEVEL);
3235
3236     for (i = 0; i < RAD_PROTOCOUNT; i++)
3237         protodefs[i] = protoinits[i](i);
3238
3239     /* needed even if no TLS/DTLS transport */
3240     sslinit();
3241     
3242     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3243     if (loglevel)
3244         debug_set_level(loglevel);
3245     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3246     if (loglevel)
3247         options.loglevel = loglevel;
3248     else if (options.loglevel)
3249         debug_set_level(options.loglevel);
3250     if (!foreground)
3251         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3252     free(options.logdestination);
3253
3254     if (!list_first(clconfs))
3255         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3256     if (!list_first(realms))
3257         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3258
3259     if (pretend)
3260         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3261
3262     if (!foreground && (daemon(0, 0) < 0))
3263         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3264     
3265     debug_timestamp_on();
3266     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3267
3268     sigemptyset(&sigset);
3269     /* exit on all but SIGPIPE, ignore more? */
3270     sigaddset(&sigset, SIGPIPE);
3271     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3272     pthread_create(&sigth, NULL, sighandler, NULL);
3273
3274     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3275         srvconf = (struct clsrvconf *)entry->data;
3276         if (srvconf->dynamiclookupcommand)
3277             continue;
3278         if (!addserver(srvconf))
3279             debugx(1, DBG_ERR, "failed to add server");
3280         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3281                            (void *)(srvconf->servers)))
3282             debugx(1, DBG_ERR, "pthread_create failed");
3283     }
3284
3285     for (i = 0; i < RAD_PROTOCOUNT; i++) {
3286         if (!protodefs[i])
3287             continue;
3288         if (protodefs[i]->initextra)
3289             protodefs[i]->initextra();
3290         if (find_clconf_type(i, NULL))
3291             createlisteners(i);
3292     }
3293     
3294     /* just hang around doing nothing, anything to do here? */
3295     for (;;)
3296         sleep(1000);
3297 }