more generalised transport
[radsecproxy.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 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10  *              rd is responsible for init and launching wr
11  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12  *          each tlsserverrd launches tlsserverwr
13  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14  *          for init and launching rd
15  *
16  * serverrd will receive a request, processes it and puts it in the requestq of
17  *          the appropriate clientwr
18  * clientwr monitors its requestq and sends requests
19  * clientrd looks for responses, processes them and puts them in the replyq of
20  *          the peer the request came from
21  * serverwr monitors its reply and sends replies
22  *
23  * In addition to the main thread, we have:
24  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26  * For each TLS peer connecting to us there will be 2 more TLS threads
27  *       This is only for connected peers
28  * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
30 */
31
32 #include <signal.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netdb.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <limits.h>
39 #ifdef SYS_SOLARIS9
40 #include <fcntl.h>
41 #endif
42 #include <sys/time.h>
43 #include <sys/types.h>
44 #include <sys/select.h>
45 #include <ctype.h>
46 #include <sys/wait.h>
47 #include <arpa/inet.h>
48 #include <regex.h>
49 #include <libgen.h>
50 #include <pthread.h>
51 #include <openssl/ssl.h>
52 #include <openssl/rand.h>
53 #include <openssl/err.h>
54 #include <openssl/md5.h>
55 #include <openssl/hmac.h>
56 #include <openssl/x509v3.h>
57 #include "debug.h"
58 #include "list.h"
59 #include "util.h"
60 #include "gconfig.h"
61 #include "radsecproxy.h"
62
63 static struct options options;
64 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
65
66 static struct addrinfo *srcudpres = NULL;
67 static struct addrinfo *srctcpres = NULL;
68
69 static struct replyq *udp_server_replyq = NULL;
70 static int udp_client4_sock = -1;
71 static int udp_client6_sock = -1;
72 static pthread_mutex_t *ssl_locks;
73 static long *ssl_lock_count;
74 extern int optind;
75 extern char *optarg;
76
77 /* minimum required declarations to avoid reordering code */
78 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
79 int dynamicconfig(struct server *server);
80 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
81 void freerealm(struct realm *realm);
82 void freeclsrvconf(struct clsrvconf *conf);
83 void freerqdata(struct request *rq);
84
85 static const struct protodefs protodefs[] = {
86     {   "udp", /* UDP, assuming RAD_UDP defined as 0 */
87         NULL, /* secretdefault */
88         SOCK_DGRAM, /* socktype */
89         "1812", /* portdefault */
90         REQUEST_RETRY_COUNT, /* retrycountdefault */
91         10, /* retrycountmax */
92         REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
93         60 /* retryintervalmax */
94     },
95     {   "tls", /* TLS, assuming RAD_TLS defined as 1 */
96         "mysecret", /* secretdefault */
97         SOCK_STREAM, /* socktype */
98         "2083", /* portdefault */
99         0, /* retrycountdefault */
100         0, /* retrycountmax */
101         REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
102         60 /* retryintervalmax */
103     },
104     {   "tcp", /* TCP, assuming RAD_TCP defined as 2 */
105         NULL, /* secretdefault */
106         SOCK_STREAM, /* socktype */
107         "1812", /* portdefault */
108         0, /* retrycountdefault */
109         0, /* retrycountmax */
110         REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
111         60 /* retryintervalmax */
112     },
113     {   NULL
114     }
115 };
116
117 uint8_t protoname2int(const char *name) {
118     int i;
119
120     for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
121     return i;
122 }
123     
124 /* callbacks for making OpenSSL thread safe */
125 unsigned long ssl_thread_id() {
126         return (unsigned long)pthread_self();
127 }
128
129 void ssl_locking_callback(int mode, int type, const char *file, int line) {
130     if (mode & CRYPTO_LOCK) {
131         pthread_mutex_lock(&ssl_locks[type]);
132         ssl_lock_count[type]++;
133     } else
134         pthread_mutex_unlock(&ssl_locks[type]);
135 }
136
137 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
138     int pwdlen = strlen(userdata);
139     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
140         return 0;
141     memcpy(buf, userdata, pwdlen);
142     return pwdlen;
143 }
144
145 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
146   char buf[256];
147   X509 *err_cert;
148   int err, depth;
149
150   err_cert = X509_STORE_CTX_get_current_cert(ctx);
151   err = X509_STORE_CTX_get_error(ctx);
152   depth = X509_STORE_CTX_get_error_depth(ctx);
153
154   if (depth > MAX_CERT_DEPTH) {
155       ok = 0;
156       err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
157       X509_STORE_CTX_set_error(ctx, err);
158   }
159
160   if (!ok) {
161       X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
162       debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
163
164       switch (err) {
165       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
166           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
167           debug(DBG_WARN, "\tIssuer=%s", buf);
168           break;
169       case X509_V_ERR_CERT_NOT_YET_VALID:
170       case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
171           debug(DBG_WARN, "\tCertificate not yet valid");
172           break;
173       case X509_V_ERR_CERT_HAS_EXPIRED:
174           debug(DBG_WARN, "Certificate has expired");
175           break;
176       case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
177           debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
178           break;
179       }
180   }
181 #ifdef DEBUG  
182   printf("certificate verify returns %d\n", ok);
183 #endif  
184   return ok;
185 }
186
187 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
188     struct addrinfo hints, *addrinfo, *res;
189     char *slash, *s;
190     int plen;
191
192     slash = conf->host ? strchr(conf->host, '/') : NULL;
193     if (slash) {
194         s = slash + 1;
195         if (!*s) {
196             debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
197             return 0;
198         }
199         for (; *s; s++)
200             if (*s < '0' || *s > '9') {
201                 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
202                 return 0;
203             }
204         plen = atoi(slash + 1);
205         if (plen < 0 || plen > 128) {
206             debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
207             return 0;
208         }
209         *slash = '\0';
210     }
211     memset(&hints, 0, sizeof(hints));
212     hints.ai_socktype = conf->pdef->socktype;
213     hints.ai_family = AF_UNSPEC;
214     hints.ai_flags = ai_flags;
215     if (!conf->host && !conf->port) {
216         /* getaddrinfo() doesn't like host and port to be NULL */
217         if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
218             debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
219             return 0;
220         }
221         for (res = addrinfo; res; res = res->ai_next) {
222             switch (res->ai_family) {
223             case AF_INET:
224                 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
225                 break;
226             case AF_INET6:
227                 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
228                 break;
229             }
230         }
231     } else {
232         if (slash)
233             hints.ai_flags |= AI_NUMERICHOST;
234         if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
235             debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
236             return 0;
237         }
238         if (slash) {
239             *slash = '/';
240             switch (addrinfo->ai_family) {
241             case AF_INET:
242                 if (plen > 32) {
243                     debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
244                     freeaddrinfo(addrinfo);
245                     return 0;
246                 }
247                 break;
248             case AF_INET6:
249                 break;
250             default:
251                 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
252                 freeaddrinfo(addrinfo);
253                 return 0;
254             }
255             conf->prefixlen = plen;
256         } else
257             conf->prefixlen = 255;
258     }
259     if (conf->addrinfo)
260         freeaddrinfo(conf->addrinfo);
261     conf->addrinfo = addrinfo;
262     return 1;
263 }         
264
265 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
266     int s, on = 1;
267     struct addrinfo *res;
268     
269     for (res = addrinfo; res; res = res->ai_next) {
270         if (family != AF_UNSPEC && family != res->ai_family)
271             continue;
272         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
273         if (s < 0) {
274             debug(DBG_WARN, "bindtoaddr: socket failed");
275             continue;
276         }
277         if (reuse)
278             setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
279 #ifdef IPV6_V6ONLY
280         if (v6only)
281             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
282 #endif          
283
284         if (!bind(s, res->ai_addr, res->ai_addrlen))
285             return s;
286         debug(DBG_WARN, "bindtoaddr: bind failed");
287         close(s);
288     }
289     return -1;
290 }         
291
292 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
293     char *p, *field;
294     int ipv6 = 0;
295
296     p = s;
297     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
298     if (*p == '[') {
299         p++;
300         field = p;
301         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
302         if (*p != ']')
303             debugx(1, DBG_ERR, "no ] matching initial [");
304         ipv6 = 1;
305     } else {
306         field = p;
307         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
308     }
309     if (field == p)
310         debugx(1, DBG_ERR, "missing host/address");
311
312     conf->host = stringcopy(field, p - field);
313     if (ipv6) {
314         p++;
315         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
316             debugx(1, DBG_ERR, "unexpected character after ]");
317     }
318     if (*p == ':') {
319             /* port number or service name is specified */;
320             field = ++p;
321             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
322             if (field == p)
323                 debugx(1, DBG_ERR, "syntax error, : but no following port");
324             conf->port = stringcopy(field, p - field);
325     } else
326         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
327     return p;
328 }
329
330 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
331     struct clsrvconf *conf;
332
333     conf = malloc(sizeof(struct clsrvconf));
334     if (!conf)
335         debugx(1, DBG_ERR, "malloc failed");
336     memset(conf, 0, sizeof(struct clsrvconf));
337     conf->type = type;
338     conf->pdef = &protodefs[conf->type];
339     if (lconf) {
340         parsehostport(lconf, conf, default_port);
341         if (!strcmp(conf->host, "*")) {
342             free(conf->host);
343             conf->host = NULL;
344         }
345     } else
346         conf->port = default_port ? stringcopy(default_port, 0) : NULL;
347     if (!resolvepeer(conf, AI_PASSIVE))
348         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
349     return conf;
350 }
351
352 void freeclsrvres(struct clsrvconf *res) {
353     free(res->host);
354     free(res->port);
355     if (res->addrinfo)
356         freeaddrinfo(res->addrinfo);
357     free(res);
358 }
359
360 int connecttcp(struct addrinfo *addrinfo) {
361     int s;
362     struct addrinfo *res;
363
364     s = -1;
365     for (res = addrinfo; res; res = res->ai_next) {
366         s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
367         if (s < 0) {
368             debug(DBG_WARN, "connecttoserver: socket failed");
369             continue;
370         }
371         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
372             break;
373         debug(DBG_WARN, "connecttoserver: connect failed");
374         close(s);
375         s = -1;
376     }
377     return s;
378 }         
379
380 /* returns 1 if the len first bits are equal, else 0 */
381 int prefixmatch(void *a1, void *a2, uint8_t len) {
382     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
383     int r, l = len / 8;
384     if (l && memcmp(a1, a2, l))
385         return 0;
386     r = len % 8;
387     if (!r)
388         return 1;
389     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
390 }
391
392 /* check if conf has matching address */
393 struct clsrvconf *checkconfaddr(uint8_t type, struct sockaddr *addr, struct clsrvconf *conf) {
394     struct sockaddr_in6 *sa6 = NULL;
395     struct in_addr *a4 = NULL;
396     struct addrinfo *res;
397     
398     if (addr->sa_family == AF_INET6) {
399         sa6 = (struct sockaddr_in6 *)addr;
400         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
401             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
402             sa6 = NULL;
403         }
404     } else
405         a4 = &((struct sockaddr_in *)addr)->sin_addr;
406
407     if (conf->type == type) {
408         if (conf->prefixlen == 255) {
409             for (res = conf->addrinfo; res; res = res->ai_next)
410                 if ((a4 && res->ai_family == AF_INET &&
411                      !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
412                     (sa6 && res->ai_family == AF_INET6 &&
413                      !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
414                     return conf;
415         } else {
416             res = conf->addrinfo;
417             if (res &&
418                 ((a4 && res->ai_family == AF_INET &&
419                   prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
420                  (sa6 && res->ai_family == AF_INET6 &&
421                   prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
422                 return conf;
423         }
424     }
425     return NULL;
426 }
427
428 /* returns next config with matching address, or NULL */
429 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
430     struct sockaddr_in6 *sa6 = NULL;
431     struct in_addr *a4 = NULL;
432     struct addrinfo *res;
433     struct list_node *entry;
434     struct clsrvconf *conf;
435     
436     if (addr->sa_family == AF_INET6) {
437         sa6 = (struct sockaddr_in6 *)addr;
438         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
439             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
440             sa6 = NULL;
441         }
442     } else
443         a4 = &((struct sockaddr_in *)addr)->sin_addr;
444
445     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
446         conf = (struct clsrvconf *)entry->data;
447         if (conf->type == type) {
448             if (conf->prefixlen == 255) {
449                 for (res = conf->addrinfo; res; res = res->ai_next)
450                     if ((a4 && res->ai_family == AF_INET &&
451                          !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
452                         (sa6 && res->ai_family == AF_INET6 &&
453                          !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
454                         if (cur)
455                             *cur = entry;
456                         return conf;
457                     }
458             } else {
459                 res = conf->addrinfo;
460                 if (res &&
461                     ((a4 && res->ai_family == AF_INET &&
462                       prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
463                      (sa6 && res->ai_family == AF_INET6 &&
464                       prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
465                     if (cur)
466                         *cur = entry;
467                     return conf;
468                 }
469             }
470         }
471     }    
472     return NULL;
473 }
474
475 /* returns next config of given type, or NULL */
476 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
477     struct list_node *entry;
478     struct clsrvconf *conf;
479     
480     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
481         conf = (struct clsrvconf *)entry->data;
482         if (conf->type == type) {
483             if (cur)
484                 *cur = entry;
485             return conf;
486         }
487     }    
488     return NULL;
489 }
490
491 struct replyq *newreplyq() {
492     struct replyq *replyq;
493     
494     replyq = malloc(sizeof(struct replyq));
495     if (!replyq)
496         debugx(1, DBG_ERR, "malloc failed");
497     replyq->replies = list_create();
498     if (!replyq->replies)
499         debugx(1, DBG_ERR, "malloc failed");
500     pthread_mutex_init(&replyq->mutex, NULL);
501     pthread_cond_init(&replyq->cond, NULL);
502     return replyq;
503 }
504
505 struct client *addclient(struct clsrvconf *conf) {
506     struct client *new = malloc(sizeof(struct client));
507     
508     if (!new) {
509         debug(DBG_ERR, "malloc failed");
510         return NULL;
511     }
512     if (!conf->clients) {
513         conf->clients = list_create();
514         if (!conf->clients) {
515             debug(DBG_ERR, "malloc failed");
516             return NULL;
517         }
518     }
519     
520     memset(new, 0, sizeof(struct client));
521     new->conf = conf;
522     new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newreplyq();
523
524     list_push(conf->clients, new);
525     return new;
526 }
527
528 void removeclient(struct client *client) {
529     struct list_node *entry;
530     
531     if (!client || !client->conf->clients)
532         return;
533
534     pthread_mutex_lock(&client->replyq->mutex);
535     for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
536         free(((struct reply *)entry)->buf);
537     list_destroy(client->replyq->replies);
538     pthread_cond_destroy(&client->replyq->cond);
539     pthread_mutex_unlock(&client->replyq->mutex);
540     pthread_mutex_destroy(&client->replyq->mutex);
541     list_removedata(client->conf->clients, client);
542     free(client);
543 }
544
545 void removeclientrqs(struct client *client) {
546     struct list_node *entry;
547     struct server *server;
548     struct request *rq;
549     int i;
550     
551     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
552         server = ((struct clsrvconf *)entry->data)->servers;
553         pthread_mutex_lock(&server->newrq_mutex);
554         for (i = 0; i < MAX_REQUESTS; i++) {
555             rq = server->requests + i;
556             if (rq->from == client)
557                 rq->from = NULL;
558         }
559         pthread_mutex_unlock(&server->newrq_mutex);
560     }
561 }
562
563 void freeserver(struct server *server, uint8_t destroymutex) {
564     struct request *rq, *end;
565
566     if (!server)
567         return;
568
569     if(server->requests) {
570         rq = server->requests;
571         for (end = rq + MAX_REQUESTS; rq < end; rq++)
572             freerqdata(rq);
573         free(server->requests);
574     }
575     free(server->dynamiclookuparg);
576     if (destroymutex) {
577         pthread_mutex_destroy(&server->lock);
578         pthread_cond_destroy(&server->newrq_cond);
579         pthread_mutex_destroy(&server->newrq_mutex);
580     }
581     free(server);
582 }
583
584 int addserver(struct clsrvconf *conf) {
585     struct clsrvconf *res;
586     
587     if (conf->servers) {
588         debug(DBG_ERR, "addserver: currently works with just one server per conf");
589         return 0;
590     }
591     conf->servers = malloc(sizeof(struct server));
592     if (!conf->servers) {
593         debug(DBG_ERR, "malloc failed");
594         return 0;
595     }
596     memset(conf->servers, 0, sizeof(struct server));
597     conf->servers->conf = conf;
598
599     if (conf->type == RAD_UDP) {
600         if (!srcudpres) {
601             res = resolve_hostport(RAD_UDP, options.sourceudp, NULL);
602             srcudpres = res->addrinfo;
603             res->addrinfo = NULL;
604             freeclsrvres(res);
605         }
606         switch (conf->addrinfo->ai_family) {
607         case AF_INET:
608             if (udp_client4_sock < 0) {
609                 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
610                 if (udp_client4_sock < 0)
611                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
612             }
613             conf->servers->sock = udp_client4_sock;
614             break;
615         case AF_INET6:
616             if (udp_client6_sock < 0) {
617                 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
618                 if (udp_client6_sock < 0)
619                     debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
620             }
621             conf->servers->sock = udp_client6_sock;
622             break;
623         default:
624             debugx(1, DBG_ERR, "addserver: unsupported address family");
625         }
626         
627     } else {
628         if (!srctcpres) {
629             res = resolve_hostport(RAD_TLS, options.sourcetcp, NULL);
630             srctcpres = res->addrinfo;
631             res->addrinfo = NULL;
632             freeclsrvres(res);
633         }
634         conf->servers->sock = -1;
635     }
636     
637     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
638     if (!conf->servers->requests) {
639         debug(DBG_ERR, "malloc failed");
640         goto errexit;
641     }
642     if (pthread_mutex_init(&conf->servers->lock, NULL)) {
643         debug(DBG_ERR, "mutex init failed");
644         goto errexit;
645     }
646     conf->servers->newrq = 0;
647     if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
648         debug(DBG_ERR, "mutex init failed");
649         pthread_mutex_destroy(&conf->servers->lock);
650         goto errexit;
651     }
652     if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
653         debug(DBG_ERR, "mutex init failed");
654         pthread_mutex_destroy(&conf->servers->newrq_mutex);
655         pthread_mutex_destroy(&conf->servers->lock);
656         goto errexit;
657     }
658
659     return 1;
660     
661  errexit:
662     freeserver(conf->servers, 0);
663     conf->servers = NULL;
664     return 0;
665 }
666
667 /* exactly one of client and server must be non-NULL */
668 /* should probably take peer list (client(s) or server(s)) as argument instead */
669 /* if *peer == NULL we return who we received from, else require it to be from peer */
670 /* return from in sa if not NULL */
671 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
672     int cnt, len;
673     unsigned char buf[65536], *rad;
674     struct sockaddr_storage from;
675     socklen_t fromlen = sizeof(from);
676     struct clsrvconf *p;
677     struct list_node *node;
678     
679     for (;;) {
680         cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
681         if (cnt == -1) {
682             debug(DBG_WARN, "radudpget: recv failed");
683             continue;
684         }
685         debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
686
687         if (cnt < 20) {
688             debug(DBG_WARN, "radudpget: packet too small");
689             continue;
690         }
691     
692         len = RADLEN(buf);
693         if (len < 20) {
694             debug(DBG_WARN, "radudpget: length too small");
695             continue;
696         }
697
698         if (cnt < len) {
699             debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
700             continue;
701         }
702         if (cnt > len)
703             debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
704
705         if (client)
706             if (*client)
707                 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*client)->conf);
708             else
709                 p = find_conf(RAD_UDP, (struct sockaddr *)&from, clconfs, NULL);
710         else
711             if (*server)
712                 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*server)->conf);
713             else
714                 p = find_conf(RAD_UDP, (struct sockaddr *)&from, srvconfs, NULL);
715
716         if (!p) {
717             debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
718             continue;
719         }
720         
721         rad = malloc(len);
722         if (!rad) {
723             debug(DBG_ERR, "radudpget: malloc failed");
724             continue;
725         }
726         
727         if (client && !*client) {
728             node = list_first(p->clients);
729             *client = node ? (struct client *)node->data : addclient(p);
730             if (!*client) {
731                 free(rad);
732                 continue;
733             }
734         } else if (server && !*server)
735             *server = p->servers;
736         
737         break;
738     }
739     memcpy(rad, buf, len);
740     if (sa)
741         *sa = from;
742     return rad;
743 }
744
745 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
746     int loc, i, l, n, r = 0;
747     char *v;
748     X509_EXTENSION *ex;
749     STACK_OF(GENERAL_NAME) *alt;
750     GENERAL_NAME *gn;
751     
752     debug(DBG_DBG, "subjectaltnameaddr");
753     
754     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
755     if (loc < 0)
756         return r;
757     
758     ex = X509_get_ext(cert, loc);
759     alt = X509V3_EXT_d2i(ex);
760     if (!alt)
761         return r;
762     
763     n = sk_GENERAL_NAME_num(alt);
764     for (i = 0; i < n; i++) {
765         gn = sk_GENERAL_NAME_value(alt, i);
766         if (gn->type != GEN_IPADD)
767             continue;
768         r = -1;
769         v = (char *)ASN1_STRING_data(gn->d.ia5);
770         l = ASN1_STRING_length(gn->d.ia5);
771         if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
772             && !memcmp(v, &addr, l)) {
773             r = 1;
774             break;
775         }
776     }
777     GENERAL_NAMES_free(alt);
778     return r;
779 }
780
781 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
782     int loc, l;
783     char *v, *s;
784     X509_NAME *nm;
785     X509_NAME_ENTRY *e;
786     ASN1_STRING *t;
787
788     nm = X509_get_subject_name(cert);
789     loc = -1;
790     for (;;) {
791         loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
792         if (loc == -1)
793             break;
794         e = X509_NAME_get_entry(nm, loc);
795         t = X509_NAME_ENTRY_get_data(e);
796         v = (char *) ASN1_STRING_data(t);
797         l = ASN1_STRING_length(t);
798         if (l < 0)
799             continue;
800         if (exact) {
801             if (l == strlen(exact) && !strncasecmp(exact, v, l))
802                 return 1;
803         } else {
804             s = stringcopy((char *)v, l);
805             if (!s) {
806                 debug(DBG_ERR, "malloc failed");
807                 continue;
808             }
809             if (regexec(regex, s, 0, NULL, 0)) {
810                 free(s);
811                 continue;
812             }
813             free(s);
814             return 1;
815         }
816     }
817     return 0;
818 }
819
820 int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
821     int loc, i, l, n, r = 0;
822     char *s, *v;
823     X509_EXTENSION *ex;
824     STACK_OF(GENERAL_NAME) *alt;
825     GENERAL_NAME *gn;
826     
827     debug(DBG_DBG, "subjectaltnameregexp");
828     
829     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
830     if (loc < 0)
831         return r;
832     
833     ex = X509_get_ext(cert, loc);
834     alt = X509V3_EXT_d2i(ex);
835     if (!alt)
836         return r;
837     
838     n = sk_GENERAL_NAME_num(alt);
839     for (i = 0; i < n; i++) {
840         gn = sk_GENERAL_NAME_value(alt, i);
841         if (gn->type != type)
842             continue;
843         r = -1;
844         v = (char *)ASN1_STRING_data(gn->d.ia5);
845         l = ASN1_STRING_length(gn->d.ia5);
846         if (l <= 0)
847             continue;
848 #ifdef DEBUG
849         printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
850 #endif  
851         if (exact) {
852             if (memcmp(v, exact, l))
853                 continue;
854         } else {
855             s = stringcopy((char *)v, l);
856             if (!s) {
857                 debug(DBG_ERR, "malloc failed");
858                 continue;
859             }
860             if (regexec(regex, s, 0, NULL, 0)) {
861                 free(s);
862                 continue;
863             }
864             free(s);
865         }
866         r = 1;
867         break;
868     }
869     GENERAL_NAMES_free(alt);
870     return r;
871 }
872
873 X509 *verifytlscert(SSL *ssl) {
874     X509 *cert;
875     unsigned long error;
876     
877     if (SSL_get_verify_result(ssl) != X509_V_OK) {
878         debug(DBG_ERR, "verifytlscert: basic validation failed");
879         while ((error = ERR_get_error()))
880             debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
881         return NULL;
882     }
883
884     cert = SSL_get_peer_certificate(ssl);
885     if (!cert)
886         debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
887     return cert;
888 }
889     
890 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
891     int r;
892     uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
893     struct in6_addr addr;
894     
895     if (conf->certnamecheck && conf->prefixlen == 255) {
896         if (inet_pton(AF_INET, conf->host, &addr))
897             type = AF_INET;
898         else if (inet_pton(AF_INET6, conf->host, &addr))
899             type = AF_INET6;
900
901         r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
902         if (r) {
903             if (r < 0) {
904                 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
905                 return 0;
906             }
907             debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
908         } else {
909             if (!cnregexp(cert, conf->host, NULL)) {
910                 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
911                 return 0;
912             }           
913             debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
914         }
915     }
916     if (conf->certcnregex) {
917         if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
918             debug(DBG_WARN, "verifyconfcert: CN not matching regex");
919             return 0;
920         }
921         debug(DBG_DBG, "verifyconfcert: CN matching regex");
922     }
923     if (conf->certuriregex) {
924         if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
925             debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
926             return 0;
927         }
928         debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
929     }
930     return 1;
931 }
932
933 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
934     struct timeval now;
935     time_t elapsed;
936     X509 *cert;
937     
938     debug(DBG_DBG, "tlsconnect called from %s", text);
939     pthread_mutex_lock(&server->lock);
940     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
941         /* already reconnected, nothing to do */
942         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
943         pthread_mutex_unlock(&server->lock);
944         return 1;
945     }
946
947     debug(DBG_DBG, "tlsconnect %s", text);
948
949     for (;;) {
950         gettimeofday(&now, NULL);
951         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
952         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
953             debug(DBG_DBG, "tlsconnect: timeout");
954             if (server->sock >= 0)
955                 close(server->sock);
956             SSL_free(server->ssl);
957             server->ssl = NULL;
958             pthread_mutex_unlock(&server->lock);
959             return 0;
960         }
961         if (server->connectionok) {
962             server->connectionok = 0;
963             sleep(2);
964         } else if (elapsed < 1)
965             sleep(2);
966         else if (elapsed < 60) {
967             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
968             sleep(elapsed);
969         } else if (elapsed < 100000) {
970             debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
971             sleep(60);
972         } else
973             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
974         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
975         if (server->sock >= 0)
976             close(server->sock);
977         if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
978             debug(DBG_ERR, "tlsconnect: connecttcp failed");
979             continue;
980         }
981         
982         SSL_free(server->ssl);
983         server->ssl = SSL_new(server->conf->ssl_ctx);
984         SSL_set_fd(server->ssl, server->sock);
985         if (SSL_connect(server->ssl) <= 0)
986             continue;
987         cert = verifytlscert(server->ssl);
988         if (!cert)
989             continue;
990         if (verifyconfcert(cert, server->conf)) {
991             X509_free(cert);
992             break;
993         }
994         X509_free(cert);
995     }
996     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
997     gettimeofday(&server->lastconnecttry, NULL);
998     pthread_mutex_unlock(&server->lock);
999     return 1;
1000 }
1001
1002 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1003 /* returns 0 on timeout, -1 on error and num if ok */
1004 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1005     int s, ndesc, cnt, len;
1006     fd_set readfds, writefds;
1007     struct timeval timer;
1008     
1009     s = SSL_get_fd(ssl);
1010     if (s < 0)
1011         return -1;
1012     /* make socket non-blocking? */
1013     for (len = 0; len < num; len += cnt) {
1014         FD_ZERO(&readfds);
1015         FD_SET(s, &readfds);
1016         writefds = readfds;
1017         if (timeout) {
1018             timer.tv_sec = timeout;
1019             timer.tv_usec = 0;
1020         }
1021         ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1022         if (ndesc < 1)
1023             return ndesc;
1024
1025         cnt = SSL_read(ssl, buf + len, num - len);
1026         if (cnt <= 0)
1027             switch (SSL_get_error(ssl, cnt)) {
1028             case SSL_ERROR_WANT_READ:
1029             case SSL_ERROR_WANT_WRITE:
1030                 cnt = 0;
1031                 continue;
1032             case SSL_ERROR_ZERO_RETURN:
1033                 /* remote end sent close_notify, send one back */
1034                 SSL_shutdown(ssl);
1035                 /* fall through */
1036             default:
1037                 return -1;
1038             }
1039     }
1040     return num;
1041 }
1042
1043 /* timeout in seconds, 0 means no timeout (blocking) */
1044 unsigned char *radtlsget(SSL *ssl, int timeout) {
1045     int cnt, len;
1046     unsigned char buf[4], *rad;
1047
1048     for (;;) {
1049         cnt = sslreadtimeout(ssl, buf, 4, timeout);
1050         if (cnt < 1) {
1051             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1052             return NULL;
1053         }
1054
1055         len = RADLEN(buf);
1056         rad = malloc(len);
1057         if (!rad) {
1058             debug(DBG_ERR, "radtlsget: malloc failed");
1059             continue;
1060         }
1061         memcpy(rad, buf, 4);
1062         
1063         cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1064         if (cnt < 1) {
1065             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1066             free(rad);
1067             return NULL;
1068         }
1069         
1070         if (len >= 20)
1071             break;
1072         
1073         free(rad);
1074         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1075     }
1076     
1077     debug(DBG_DBG, "radtlsget: got %d bytes", len);
1078     return rad;
1079 }
1080
1081 int clientradputudp(struct server *server, unsigned char *rad) {
1082     size_t len;
1083     struct sockaddr_storage sa;
1084     struct sockaddr *sap;
1085     struct clsrvconf *conf = server->conf;
1086     in_port_t *port = NULL;
1087     
1088     len = RADLEN(rad);
1089     
1090     if (*rad == RAD_Accounting_Request) {
1091         sap = (struct sockaddr *)&sa;
1092         memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1093     } else
1094         sap = conf->addrinfo->ai_addr;
1095     
1096     switch (sap->sa_family) {
1097     case AF_INET:
1098         port = &((struct sockaddr_in *)sap)->sin_port;
1099         break;
1100     case AF_INET6:
1101         port = &((struct sockaddr_in6 *)sap)->sin6_port;
1102         break;
1103     default:
1104         return 0;
1105     }
1106
1107     if (*rad == RAD_Accounting_Request)
1108         *port = htons(ntohs(*port) + 1);
1109     
1110     if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1111         debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1112         return 1;
1113     }
1114
1115     debug(DBG_WARN, "clientradputudp: send failed");
1116     return 0;
1117 }
1118
1119 int clientradputtls(struct server *server, unsigned char *rad) {
1120     int cnt;
1121     size_t len;
1122     unsigned long error;
1123     struct timeval lastconnecttry;
1124     struct clsrvconf *conf = server->conf;
1125     
1126     len = RADLEN(rad);
1127     lastconnecttry = server->lastconnecttry;
1128     while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1129         while ((error = ERR_get_error()))
1130             debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1131         if (server->dynamiclookuparg)
1132             return 0;
1133         tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1134         lastconnecttry = server->lastconnecttry;
1135     }
1136
1137     server->connectionok = 1;
1138     debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1139     return 1;
1140 }
1141
1142 int clientradput(struct server *server, unsigned char *rad) {
1143     switch (server->conf->type) {
1144     case RAD_UDP:
1145         return clientradputudp(server, rad);
1146     case RAD_TLS:
1147         return clientradputtls(server, rad);
1148     }
1149     return 0;
1150 }
1151
1152 int radsign(unsigned char *rad, unsigned char *sec) {
1153     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1154     static unsigned char first = 1;
1155     static EVP_MD_CTX mdctx;
1156     unsigned int md_len;
1157     int result;
1158     
1159     pthread_mutex_lock(&lock);
1160     if (first) {
1161         EVP_MD_CTX_init(&mdctx);
1162         first = 0;
1163     }
1164
1165     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1166         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1167         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1168         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1169         md_len == 16);
1170     pthread_mutex_unlock(&lock);
1171     return result;
1172 }
1173
1174 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1175     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1176     static unsigned char first = 1;
1177     static EVP_MD_CTX mdctx;
1178     unsigned char hash[EVP_MAX_MD_SIZE];
1179     unsigned int len;
1180     int result;
1181     
1182     pthread_mutex_lock(&lock);
1183     if (first) {
1184         EVP_MD_CTX_init(&mdctx);
1185         first = 0;
1186     }
1187
1188     len = RADLEN(rad);
1189     
1190     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1191               EVP_DigestUpdate(&mdctx, rad, 4) &&
1192               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1193               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1194               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1195               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1196               len == 16 &&
1197               !memcmp(hash, rad + 4, 16));
1198     pthread_mutex_unlock(&lock);
1199     return result;
1200 }
1201               
1202 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1203     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1204     static unsigned char first = 1;
1205     static HMAC_CTX hmacctx;
1206     unsigned int md_len;
1207     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1208     
1209     pthread_mutex_lock(&lock);
1210     if (first) {
1211         HMAC_CTX_init(&hmacctx);
1212         first = 0;
1213     }
1214
1215     memcpy(auth, authattr, 16);
1216     memset(authattr, 0, 16);
1217     md_len = 0;
1218     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1219     HMAC_Update(&hmacctx, rad, RADLEN(rad));
1220     HMAC_Final(&hmacctx, hash, &md_len);
1221     memcpy(authattr, auth, 16);
1222     if (md_len != 16) {
1223         debug(DBG_WARN, "message auth computation failed");
1224         pthread_mutex_unlock(&lock);
1225         return 0;
1226     }
1227
1228     if (memcmp(auth, hash, 16)) {
1229         debug(DBG_WARN, "message authenticator, wrong value");
1230         pthread_mutex_unlock(&lock);
1231         return 0;
1232     }   
1233         
1234     pthread_mutex_unlock(&lock);
1235     return 1;
1236 }
1237
1238 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1239     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1240     static unsigned char first = 1;
1241     static HMAC_CTX hmacctx;
1242     unsigned int md_len;
1243
1244     if (!authattrval)
1245         return 1;
1246     
1247     pthread_mutex_lock(&lock);
1248     if (first) {
1249         HMAC_CTX_init(&hmacctx);
1250         first = 0;
1251     }
1252
1253     memset(authattrval, 0, 16);
1254     md_len = 0;
1255     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1256     HMAC_Update(&hmacctx, rad, RADLEN(rad));
1257     HMAC_Final(&hmacctx, authattrval, &md_len);
1258     if (md_len != 16) {
1259         debug(DBG_WARN, "message auth computation failed");
1260         pthread_mutex_unlock(&lock);
1261         return 0;
1262     }
1263
1264     pthread_mutex_unlock(&lock);
1265     return 1;
1266 }
1267
1268 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1269     while (length > 1) {
1270         if (ATTRTYPE(attrs) == type)
1271             return attrs;
1272         length -= ATTRLEN(attrs);
1273         attrs += ATTRLEN(attrs);
1274     }
1275     return NULL;
1276 }
1277
1278 void freerqdata(struct request *rq) {
1279     if (rq->origusername)
1280         free(rq->origusername);
1281     if (rq->buf)
1282         free(rq->buf);
1283 }
1284
1285 void sendrq(struct server *to, struct request *rq) {
1286     int i;
1287     uint8_t *attr;
1288
1289     pthread_mutex_lock(&to->newrq_mutex);
1290     /* might simplify if only try nextid, might be ok */
1291     for (i = to->nextid; i < MAX_REQUESTS; i++)
1292         if (!to->requests[i].buf)
1293             break;
1294     if (i == MAX_REQUESTS) {
1295         for (i = 0; i < to->nextid; i++)
1296             if (!to->requests[i].buf)
1297                 break;
1298         if (i == to->nextid) {
1299             debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1300             freerqdata(rq);
1301             goto exit;
1302         }
1303     }
1304     
1305     rq->buf[1] = (char)i;
1306
1307     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1308     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1309         freerqdata(rq);
1310         goto exit;
1311     }
1312     
1313     if (*rq->buf == RAD_Accounting_Request) {
1314         if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1315             debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1316             freerqdata(rq);
1317             goto exit;
1318         }
1319     }
1320
1321     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1322     to->requests[i] = *rq;
1323     to->nextid = i + 1;
1324
1325     if (!to->newrq) {
1326         to->newrq = 1;
1327         debug(DBG_DBG, "sendrq: signalling client writer");
1328         pthread_cond_signal(&to->newrq_cond);
1329     }
1330  exit:
1331     pthread_mutex_unlock(&to->newrq_mutex);
1332 }
1333
1334 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1335     struct reply *reply;
1336     uint8_t first;
1337     
1338     if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1339         free(buf);
1340         debug(DBG_WARN, "sendreply: failed to sign message");
1341         return;
1342     }
1343
1344     reply = malloc(sizeof(struct reply));
1345     if (!reply) {
1346         free(buf);
1347         debug(DBG_ERR, "sendreply: malloc failed");
1348         return;
1349     }
1350     memset(reply, 0, sizeof(struct reply));
1351     reply->buf = buf;
1352     if (tosa)
1353         reply->tosa = *tosa;
1354     reply->toudpsock = toudpsock;
1355     
1356     pthread_mutex_lock(&to->replyq->mutex);
1357
1358     first = list_first(to->replyq->replies) == NULL;
1359     
1360     if (!list_push(to->replyq->replies, reply)) {
1361         pthread_mutex_unlock(&to->replyq->mutex);
1362         free(reply);
1363         free(buf);
1364         debug(DBG_ERR, "sendreply: malloc failed");
1365         return;
1366     }
1367     
1368     if (first) {
1369         debug(DBG_DBG, "signalling server writer");
1370         pthread_cond_signal(&to->replyq->cond);
1371     }
1372     pthread_mutex_unlock(&to->replyq->mutex);
1373 }
1374
1375 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1376     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1377     static unsigned char first = 1;
1378     static EVP_MD_CTX mdctx;
1379     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1380     unsigned int md_len;
1381     uint8_t i, offset = 0, out[128];
1382     
1383     pthread_mutex_lock(&lock);
1384     if (first) {
1385         EVP_MD_CTX_init(&mdctx);
1386         first = 0;
1387     }
1388
1389     input = auth;
1390     for (;;) {
1391         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1392             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1393             !EVP_DigestUpdate(&mdctx, input, 16) ||
1394             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1395             md_len != 16) {
1396             pthread_mutex_unlock(&lock);
1397             return 0;
1398         }
1399         for (i = 0; i < 16; i++)
1400             out[offset + i] = hash[i] ^ in[offset + i];
1401         input = out + offset - 16;
1402         offset += 16;
1403         if (offset == len)
1404             break;
1405     }
1406     memcpy(in, out, len);
1407     pthread_mutex_unlock(&lock);
1408     return 1;
1409 }
1410
1411 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1412     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1413     static unsigned char first = 1;
1414     static EVP_MD_CTX mdctx;
1415     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1416     unsigned int md_len;
1417     uint8_t i, offset = 0, out[128];
1418     
1419     pthread_mutex_lock(&lock);
1420     if (first) {
1421         EVP_MD_CTX_init(&mdctx);
1422         first = 0;
1423     }
1424
1425     input = auth;
1426     for (;;) {
1427         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1428             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1429             !EVP_DigestUpdate(&mdctx, input, 16) ||
1430             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1431             md_len != 16) {
1432             pthread_mutex_unlock(&lock);
1433             return 0;
1434         }
1435         for (i = 0; i < 16; i++)
1436             out[offset + i] = hash[i] ^ in[offset + i];
1437         input = in + offset;
1438         offset += 16;
1439         if (offset == len)
1440             break;
1441     }
1442     memcpy(in, out, len);
1443     pthread_mutex_unlock(&lock);
1444     return 1;
1445 }
1446
1447 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1448     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1449     static unsigned char first = 1;
1450     static EVP_MD_CTX mdctx;
1451     unsigned char hash[EVP_MAX_MD_SIZE];
1452     unsigned int md_len;
1453     uint8_t i, offset;
1454     
1455     pthread_mutex_lock(&lock);
1456     if (first) {
1457         EVP_MD_CTX_init(&mdctx);
1458         first = 0;
1459     }
1460
1461 #if 0
1462     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1463     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1464     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1465 #endif
1466     
1467     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1468         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1469         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1470         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1471         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1472         pthread_mutex_unlock(&lock);
1473         return 0;
1474     }
1475
1476 #if 0    
1477     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1478 #endif
1479     
1480     for (i = 0; i < 16; i++)
1481         text[i] ^= hash[i];
1482     
1483     for (offset = 16; offset < len; offset += 16) {
1484 #if 0   
1485         printf("text + offset - 16 c(%d): ", offset / 16);
1486         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1487 #endif
1488         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1489             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1490             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1491             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1492             md_len != 16) {
1493             pthread_mutex_unlock(&lock);
1494             return 0;
1495         }
1496 #if 0
1497         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1498 #endif    
1499         
1500         for (i = 0; i < 16; i++)
1501             text[offset + i] ^= hash[i];
1502     }
1503     
1504 #if 0
1505     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1506 #endif
1507
1508     pthread_mutex_unlock(&lock);
1509     return 1;
1510 }
1511
1512 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1513     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1514     static unsigned char first = 1;
1515     static EVP_MD_CTX mdctx;
1516     unsigned char hash[EVP_MAX_MD_SIZE];
1517     unsigned int md_len;
1518     uint8_t i, offset;
1519     char plain[255];
1520     
1521     pthread_mutex_lock(&lock);
1522     if (first) {
1523         EVP_MD_CTX_init(&mdctx);
1524         first = 0;
1525     }
1526
1527 #if 0
1528     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1529     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1530     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1531 #endif
1532     
1533     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1534         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1535         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1536         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1537         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1538         pthread_mutex_unlock(&lock);
1539         return 0;
1540     }
1541
1542 #if 0    
1543     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1544 #endif
1545     
1546     for (i = 0; i < 16; i++)
1547         plain[i] = text[i] ^ hash[i];
1548     
1549     for (offset = 16; offset < len; offset += 16) {
1550 #if 0   
1551         printf("text + offset - 16 c(%d): ", offset / 16);
1552         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1553 #endif
1554         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1555             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1556             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1557             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1558             md_len != 16) {
1559             pthread_mutex_unlock(&lock);
1560             return 0;
1561         }
1562 #if 0
1563         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1564 #endif    
1565
1566         for (i = 0; i < 16; i++)
1567             plain[offset + i] = text[offset + i] ^ hash[i];
1568     }
1569
1570     memcpy(text, plain, len);
1571 #if 0
1572     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1573 #endif
1574
1575     pthread_mutex_unlock(&lock);
1576     return 1;
1577 }
1578
1579 struct realm *id2realm(struct list *realmlist, char *id) {
1580     struct list_node *entry;
1581     struct realm *realm, *subrealm = NULL;
1582
1583     /* need to do locking for subrealms and check subrealm timers */
1584     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1585         realm = (struct realm *)entry->data;
1586         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1587             pthread_mutex_lock(&realm->subrealms_mutex);
1588             if (realm->subrealms)
1589                 subrealm = id2realm(realm->subrealms, id);
1590             pthread_mutex_unlock(&realm->subrealms_mutex);
1591             return subrealm ? subrealm : realm;
1592         }
1593     }
1594     return NULL;
1595 }
1596
1597 /* helper function, only used by removeserversubrealms() */
1598 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1599     struct list_node *entry;
1600     struct realm *realm;
1601     
1602     for (entry = list_first(realmlist); entry;) {
1603         realm = (struct realm *)entry->data;
1604         entry = list_next(entry);
1605         if (realm->srvconfs) {
1606             list_removedata(realm->srvconfs, srv);
1607             if (!list_first(realm->srvconfs)) {
1608                 list_destroy(realm->srvconfs);
1609                 realm->srvconfs = NULL;
1610             }
1611         }
1612         if (realm->accsrvconfs) {
1613             list_removedata(realm->accsrvconfs, srv);
1614             if (!list_first(realm->accsrvconfs)) {
1615                 list_destroy(realm->accsrvconfs);
1616                 realm->accsrvconfs = NULL;
1617             }
1618         }
1619
1620         /* remove subrealm if no servers */
1621         if (!realm->srvconfs && !realm->accsrvconfs) {
1622             list_removedata(realmlist, realm);
1623             freerealm(realm);
1624         }
1625     }
1626 }
1627
1628 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1629     struct list_node *entry;
1630     struct realm *realm;
1631     
1632     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1633         realm = (struct realm *)entry->data;
1634         pthread_mutex_lock(&realm->subrealms_mutex);
1635         if (realm->subrealms) {
1636             _internal_removeserversubrealms(realm->subrealms, srv);
1637             if (!list_first(realm->subrealms)) {
1638                 list_destroy(realm->subrealms);
1639                 realm->subrealms = NULL;
1640             }
1641         }
1642         pthread_mutex_unlock(&realm->subrealms_mutex);
1643     }
1644 }
1645                         
1646 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1647     struct request *rq = to->requests, *end;
1648     
1649     pthread_mutex_lock(&to->newrq_mutex);
1650     for (end = rq + MAX_REQUESTS; rq < end; rq++)
1651         if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1652             break;
1653     pthread_mutex_unlock(&to->newrq_mutex);
1654     
1655     return rq < end;
1656 }
1657
1658 int attrvalidate(unsigned char *attrs, int length) {
1659     while (length > 1) {
1660         if (ATTRLEN(attrs) < 2) {
1661             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1662             return 0;
1663         }
1664         length -= ATTRLEN(attrs);
1665         if (length < 0) {
1666             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1667             return 0;
1668         }
1669         attrs += ATTRLEN(attrs);
1670     }
1671     if (length)
1672         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1673     return 1;
1674 }
1675
1676 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1677     if (len < 16 || len > 128 || len % 16) {
1678         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1679         return 0;
1680     }
1681         
1682     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1683         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1684         return 0;
1685     }
1686 #ifdef DEBUG
1687     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1688 #endif  
1689     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1690         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1691         return 0;
1692     }
1693     return 1;
1694 }
1695
1696 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1697     if (len < 18)
1698         return 0;
1699     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1700         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1701         return 0;
1702     }
1703     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1704         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1705         return 0;
1706     }
1707     return 1;
1708 }
1709
1710 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1711            char *oldsecret, char *newsecret) {
1712     unsigned char *attr;
1713     
1714     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1715         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1716         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1717             return 0;
1718     }
1719     return 1;
1720 }
1721
1722 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1723     if (!attrs)
1724         return 0;
1725     
1726     for (; attrs[0]; attrs += 2)
1727         if (attrs[0] == vendor && attrs[1] == subattr)
1728             return 1;
1729     return 0;
1730 }
1731
1732 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1733     uint8_t alen, sublen, rmlen = 0;
1734     uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1735     uint8_t *subattrs;
1736     
1737     if (!removevendorattrs)
1738         return 0;
1739
1740     while (*removevendorattrs && *removevendorattrs != vendor)
1741         removevendorattrs += 2;
1742     if (!*removevendorattrs)
1743         return 0;
1744     
1745     alen = ATTRLEN(attrs);
1746
1747     if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1748         /* remove entire vendor attribute */
1749         memmove(attrs, attrs + alen, length - alen);
1750         return alen;
1751     }
1752
1753     sublen = alen - 4;
1754     subattrs = ATTRVAL(attrs) + 4;
1755     
1756     if (!attrvalidate(subattrs, sublen)) {
1757         debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1758         return 0;
1759     }
1760
1761     length -= 6;
1762     while (sublen > 1) {
1763         alen = ATTRLEN(subattrs);
1764         sublen -= alen;
1765         length -= alen;
1766         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1767             memmove(subattrs, subattrs + alen, length);
1768             rmlen += alen;
1769         } else
1770             subattrs += alen;
1771     }
1772
1773     ATTRLEN(attrs) -= rmlen;
1774     return rmlen;
1775 }
1776
1777 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1778     uint8_t *attrs, alen;
1779     uint16_t len, rmlen = 0;
1780     
1781     if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1782         return;
1783
1784     len = RADLEN(buf) - 20;
1785     attrs = buf + 20;
1786     while (len > 1) {
1787         alen = ATTRLEN(attrs);
1788         len -= alen;
1789         if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1790             memmove(attrs, attrs + alen, len);
1791             rmlen += alen;
1792         } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1793             rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1794         else
1795             attrs += alen;
1796     }
1797     if (rmlen)
1798         ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1799 }
1800
1801 /* returns a pointer to the resized attribute value */
1802 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1803     uint8_t *attrs, *attr, vallen;
1804     uint16_t len;
1805     unsigned char *new;
1806     
1807     len = RADLEN(*buf) - 20;
1808     attrs = *buf + 20;
1809
1810     attr = attrget(attrs, len, type);
1811     if (!attr)
1812         return NULL;
1813     
1814     vallen = ATTRVALLEN(attr);
1815     if (vallen == newvallen)
1816         return attr + 2;
1817
1818     len += newvallen - vallen;
1819     if (newvallen > vallen) {
1820         new = realloc(*buf, len + 20);
1821         if (!new) {
1822             debug(DBG_ERR, "resizeattr: malloc failed");
1823             return NULL;
1824         }
1825         if (new != *buf) {
1826             attr += new - *buf;
1827             attrs = new + 20;
1828             *buf = new;
1829         }
1830     }
1831     memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1832     attr[1] = newvallen + 2;
1833     ((uint16_t *)*buf)[1] = htons(len + 20);
1834     return attr + 2;
1835 }
1836                 
1837 int rewriteusername(struct request *rq, char *in) {
1838     size_t nmatch = 10, reslen = 0, start = 0;
1839     regmatch_t pmatch[10], *pfield;
1840     int i;
1841     unsigned char *result;
1842     char *out = rq->from->conf->rewriteattrreplacement;
1843     
1844     if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1845         debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1846         return 1;
1847     }
1848     
1849     rq->origusername = stringcopy(in, 0);
1850     if (!rq->origusername)
1851         return 0;
1852     
1853     for (i = start; out[i]; i++) {
1854         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1855             pfield = &pmatch[out[i + 1] - '0'];
1856             if (pfield->rm_so >= 0) {
1857                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1858                 start = i + 2;
1859             }
1860             i++;
1861         }
1862     }
1863     reslen += i - start;
1864
1865     result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1866     if (!result)
1867         return 0;
1868     
1869     start = 0;
1870     reslen = 0;
1871     for (i = start; out[i]; i++) {
1872         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1873             pfield = &pmatch[out[i + 1] - '0'];
1874             if (pfield->rm_so >= 0) {
1875                 memcpy(result + reslen, out + start, i - start);
1876                 reslen += i - start;
1877                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1878                 reslen += pfield->rm_eo - pfield->rm_so;
1879                 start = i + 2;
1880             }
1881             i++;
1882         }
1883     }
1884
1885     memcpy(result + reslen, out + start, i - start);
1886     reslen += i - start;
1887     memcpy(in, result, reslen);
1888     in[reslen] = '\0';
1889     return 1;
1890 }
1891
1892 const char *radmsgtype2string(uint8_t code) {
1893     static const char *rad_msg_names[] = {
1894         "", "Access-Request", "Access-Accept", "Access-Reject",
1895         "Accounting-Request", "Accounting-Response", "", "",
1896         "", "", "", "Access-Challenge",
1897         "Status-Server", "Status-Client"
1898     };
1899     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1900 }
1901
1902 void char2hex(char *h, unsigned char c) {
1903     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1904                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1905     h[0] = hexdigits[c / 16];
1906     h[1] = hexdigits[c % 16];
1907     return;
1908 }
1909
1910 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1911     int i, l;
1912     char *s, *d;
1913
1914     if (!attr || len == 1) {
1915         *ascii = '\0';
1916         return ascii;
1917     }
1918
1919     l = ATTRVALLEN(attr);
1920     s = (char *)ATTRVAL(attr);
1921     d = ascii;
1922
1923     for (i = 0; i < l; i++) {
1924         if (s[i] > 31 && s[i] < 127) {
1925             *d++ = s[i];
1926             if (d - ascii == len - 1)
1927                 break;
1928         } else {
1929             if (d - ascii > len - 4)
1930                 break;
1931             *d++ = '%';
1932             char2hex(d, s[i]);
1933             d += 2;
1934             if (d - ascii == len - 1)
1935                 break;
1936         }
1937     }
1938     *d = '\0';
1939     return ascii;
1940 }
1941
1942 void acclog(unsigned char *attrs, int length, char *host) {
1943     unsigned char *attr;
1944     char username[760];
1945     
1946     attr = attrget(attrs, length, RAD_Attr_User_Name);
1947     if (!attr) {
1948         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1949         return;
1950     }
1951     radattr2ascii(username, sizeof(username), attr);
1952     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1953 }
1954         
1955 void respondaccounting(struct request *rq) {
1956     unsigned char *resp;
1957
1958     resp = malloc(20);
1959     if (!resp) {
1960         debug(DBG_ERR, "respondaccounting: malloc failed");
1961         return;
1962     }
1963     memcpy(resp, rq->buf, 20);
1964     resp[0] = RAD_Accounting_Response;
1965     resp[2] = 0;
1966     resp[3] = 20;
1967     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1968     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1969 }
1970
1971 void respondstatusserver(struct request *rq) {
1972     unsigned char *resp;
1973
1974     resp = malloc(20);
1975     if (!resp) {
1976         debug(DBG_ERR, "respondstatusserver: malloc failed");
1977         return;
1978     }
1979     memcpy(resp, rq->buf, 20);
1980     resp[0] = RAD_Access_Accept;
1981     resp[2] = 0;
1982     resp[3] = 20;
1983     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1984     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1985 }
1986
1987 void respondreject(struct request *rq, char *message) {
1988     unsigned char *resp;
1989     int len = 20;
1990
1991     if (message && *message)
1992         len += 2 + strlen(message);
1993     
1994     resp = malloc(len);
1995     if (!resp) {
1996         debug(DBG_ERR, "respondreject: malloc failed");
1997         return;
1998     }
1999     memcpy(resp, rq->buf, 20);
2000     resp[0] = RAD_Access_Reject;
2001     *(uint16_t *)(resp + 2) = htons(len);
2002     if (message && *message) {
2003         resp[20] = RAD_Attr_Reply_Message;
2004         resp[21] = len - 20;
2005         memcpy(resp + 22, message, len - 22);
2006     }
2007     sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2008 }
2009
2010 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2011     struct list_node *entry;
2012     struct clsrvconf *server, *best = NULL, *first = NULL;
2013
2014     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2015         server = (struct clsrvconf *)entry->data;
2016         if (!server->servers)
2017             return server;
2018         if (!first)
2019             first = server;
2020         if (!server->servers->connectionok)
2021             continue;
2022         if (!server->servers->lostrqs)
2023             return server;
2024         if (!best) {
2025             best = server;
2026             continue;
2027         }
2028         if (server->servers->lostrqs < best->servers->lostrqs)
2029             best = server;
2030     }
2031     return best ? best : first;
2032 }
2033
2034 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2035     struct clsrvconf *srvconf;
2036     
2037     *realm = id2realm(realms, id);
2038     if (!*realm)
2039         return NULL;
2040     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2041     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2042     if (!srvconf)
2043         return NULL;
2044     if (!acc && !srvconf->servers)
2045         adddynamicrealmserver(*realm, srvconf, id);
2046     return srvconf->servers;
2047 }
2048                           
2049 void radsrv(struct request *rq) {
2050     uint8_t code, id, *auth, *attrs, *attr;
2051     uint16_t len;
2052     struct server *to = NULL;
2053     char username[254], userascii[760];
2054     unsigned char newauth[16];
2055     struct realm *realm = NULL;
2056     
2057     code = *(uint8_t *)rq->buf;
2058     id = *(uint8_t *)(rq->buf + 1);
2059     len = RADLEN(rq->buf);
2060     auth = (uint8_t *)(rq->buf + 4);
2061
2062     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2063     
2064     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2065         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2066         goto exit;
2067     }
2068
2069     len -= 20;
2070     attrs = rq->buf + 20;
2071
2072     if (!attrvalidate(attrs, len)) {
2073         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2074         goto exit;
2075     }
2076
2077     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2078     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2079         debug(DBG_WARN, "radsrv: message authentication failed");
2080         goto exit;
2081     }
2082
2083     if (code == RAD_Status_Server) {
2084         respondstatusserver(rq);
2085         goto exit;
2086     }
2087     
2088     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2089
2090     if (code == RAD_Accounting_Request) {
2091         memset(newauth, 0, 16);
2092         if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2093             debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2094             goto exit;
2095         }
2096     }
2097     
2098     if (rq->from->conf->rewrite) {
2099         dorewrite(rq->buf, rq->from->conf->rewrite);
2100         len = RADLEN(rq->buf) - 20;
2101     }
2102     
2103     attr = attrget(attrs, len, RAD_Attr_User_Name);
2104     if (!attr) {
2105         if (code == RAD_Accounting_Request) {
2106             acclog(attrs, len, rq->from->conf->host);
2107             respondaccounting(rq);
2108         } else
2109             debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2110         goto exit;
2111     }
2112     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2113     username[ATTRVALLEN(attr)] = '\0';
2114     radattr2ascii(userascii, sizeof(userascii), attr);
2115
2116     if (rq->from->conf->rewriteattrregex) {
2117         if (!rewriteusername(rq, username)) {
2118             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2119             goto exit;
2120         }
2121         len = RADLEN(rq->buf) - 20;
2122         auth = (uint8_t *)(rq->buf + 4);
2123         attrs = rq->buf + 20;
2124     }
2125
2126     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2127     
2128     to = findserver(&realm, username, code == RAD_Accounting_Request);
2129     if (!realm) {
2130         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2131         goto exit;
2132     }
2133     if (!to) {
2134         if (realm->message && code == RAD_Access_Request) {
2135             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2136             respondreject(rq, realm->message);
2137         } else if (realm->accresp && code == RAD_Accounting_Request) {
2138             acclog(attrs, len, rq->from->conf->host);
2139             respondaccounting(rq);
2140         }
2141         goto exit;
2142     }
2143     
2144     if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2145         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2146               rq->from->conf->name, to->conf->name);
2147         goto exit;
2148     }
2149
2150     if (rqinqueue(to, rq->from, id, code)) {
2151         debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2152               radmsgtype2string(code), rq->from->conf->host, id);
2153         goto exit;
2154     }
2155     
2156     if (code != RAD_Accounting_Request) {
2157         if (!RAND_bytes(newauth, 16)) {
2158             debug(DBG_WARN, "radsrv: failed to generate random auth");
2159             goto exit;
2160         }
2161     }
2162
2163 #ifdef DEBUG
2164     printfchars(NULL, "auth", "%02x ", auth, 16);
2165 #endif
2166
2167     attr = attrget(attrs, len, RAD_Attr_User_Password);
2168     if (attr) {
2169         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2170         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2171             goto exit;
2172     }
2173     
2174     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2175     if (attr) {
2176         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2177         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2178             goto exit;
2179     }
2180
2181     rq->origid = id;
2182     memcpy(rq->origauth, auth, 16);
2183     memcpy(auth, newauth, 16);
2184     sendrq(to, rq);
2185     return;
2186     
2187  exit:
2188     freerqdata(rq);
2189 }
2190
2191 int replyh(struct server *server, unsigned char *buf) {
2192     struct client *from;
2193     struct request *rq;
2194     int i, len, sublen;
2195     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2196     struct sockaddr_storage fromsa;
2197     char tmp[760], stationid[760];
2198     
2199     server->connectionok = 1;
2200     server->lostrqs = 0;
2201         
2202     i = buf[1]; /* i is the id */
2203
2204     if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2205         && *buf != RAD_Accounting_Response) {
2206         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2207         return 0;
2208     }
2209     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2210
2211     rq = server->requests + i;
2212
2213     pthread_mutex_lock(&server->newrq_mutex);
2214     if (!rq->buf || !rq->tries) {
2215         pthread_mutex_unlock(&server->newrq_mutex);
2216         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2217         return 0;
2218     }
2219
2220     if (rq->received) {
2221         pthread_mutex_unlock(&server->newrq_mutex);
2222         debug(DBG_INFO, "replyh: already received, ignoring reply");
2223         return 0;
2224     }
2225         
2226     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2227         pthread_mutex_unlock(&server->newrq_mutex);
2228         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2229         return 0;
2230     }
2231         
2232     len = RADLEN(buf) - 20;
2233     attrs = buf + 20;
2234
2235     if (!attrvalidate(attrs, len)) {
2236         pthread_mutex_unlock(&server->newrq_mutex);
2237         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2238         return 0;
2239     }
2240         
2241     /* Message Authenticator */
2242     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2243     if (messageauth) {
2244         if (ATTRVALLEN(messageauth) != 16) {
2245             pthread_mutex_unlock(&server->newrq_mutex);
2246             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2247             return 0;
2248         }
2249         memcpy(tmp, buf + 4, 16);
2250         memcpy(buf + 4, rq->buf + 4, 16);
2251         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2252             pthread_mutex_unlock(&server->newrq_mutex);
2253             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2254             return 0;
2255         }
2256         memcpy(buf + 4, tmp, 16);
2257         debug(DBG_DBG, "replyh: message auth ok");
2258     }
2259         
2260     if (*rq->buf == RAD_Status_Server) {
2261         rq->received = 1;
2262         pthread_mutex_unlock(&server->newrq_mutex);
2263         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2264         return 0;
2265     }
2266
2267     gettimeofday(&server->lastreply, NULL);
2268     
2269     from = rq->from;
2270     if (!from) {
2271         pthread_mutex_unlock(&server->newrq_mutex);
2272         debug(DBG_INFO, "replyh: client gone, ignoring reply");
2273         return 0;
2274     }
2275         
2276     if (server->conf->rewrite) {
2277         dorewrite(buf, server->conf->rewrite);
2278         len = RADLEN(buf) - 20;
2279     }
2280     
2281     /* MS MPPE */
2282     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2283         if (ATTRVALLEN(attr) <= 4)
2284             break;
2285             
2286         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
2287             continue;
2288             
2289         sublen = ATTRVALLEN(attr) - 4;
2290         subattrs = ATTRVAL(attr) + 4;  
2291         if (!attrvalidate(subattrs, sublen) ||
2292             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2293                     rq, server->conf->secret, from->conf->secret) ||
2294             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2295                     rq, server->conf->secret, from->conf->secret))
2296             break;
2297     }
2298     if (attr) {
2299         pthread_mutex_unlock(&server->newrq_mutex);
2300         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2301         return 0;
2302     }
2303         
2304     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2305         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2306         if (attr) {
2307             radattr2ascii(tmp, sizeof(tmp), attr);
2308             attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2309             if (attr) {
2310                 radattr2ascii(stationid, sizeof(stationid), attr);
2311                 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2312                       radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2313             } else
2314                 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2315         }
2316     }
2317         
2318     buf[1] = (char)rq->origid;
2319     memcpy(buf + 4, rq->origauth, 16);
2320 #ifdef DEBUG    
2321     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2322 #endif
2323
2324     if (rq->origusername) {
2325         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2326         if (!username) {
2327             pthread_mutex_unlock(&server->newrq_mutex);
2328             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2329             return 0;
2330         }
2331         memcpy(username, rq->origusername, strlen(rq->origusername));
2332         len = RADLEN(buf) - 20;
2333         attrs = buf + 20;
2334         if (messageauth)
2335             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2336     }
2337         
2338     if (messageauth) {
2339         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2340             pthread_mutex_unlock(&server->newrq_mutex);
2341             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2342             return 0;
2343         }
2344         debug(DBG_DBG, "replyh: computed messageauthattr");
2345     }
2346
2347     fromsa = rq->fromsa; /* only needed for UDP */
2348     /* once we set received = 1, rq may be reused */
2349     rq->received = 1;
2350
2351     debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2352     sendreply(from, buf, &fromsa, rq->fromudpsock);
2353     pthread_mutex_unlock(&server->newrq_mutex);
2354     return 1;
2355 }
2356
2357 void *udpclientrd(void *arg) {
2358     struct server *server;
2359     unsigned char *buf;
2360     int *s = (int *)arg;
2361     
2362     for (;;) {
2363         server = NULL;
2364         buf = radudpget(*s, NULL, &server, NULL);
2365         if (!replyh(server, buf))
2366             free(buf);
2367     }
2368 }
2369
2370 void *tlsclientrd(void *arg) {
2371     struct server *server = (struct server *)arg;
2372     unsigned char *buf;
2373     struct timeval now, lastconnecttry;
2374     
2375     for (;;) {
2376         /* yes, lastconnecttry is really necessary */
2377         lastconnecttry = server->lastconnecttry;
2378         buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2379         if (!buf) {
2380             if (server->dynamiclookuparg)
2381                 break;
2382             tlsconnect(server, &lastconnecttry, 0, "clientrd");
2383             continue;
2384         }
2385
2386         if (!replyh(server, buf))
2387             free(buf);
2388         if (server->dynamiclookuparg) {
2389             gettimeofday(&now, NULL);
2390             if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2391                 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2392                 break;
2393             }
2394         }
2395     }
2396     server->clientrdgone = 1;
2397     return NULL;
2398 }
2399
2400 /* code for removing state not finished */
2401 void *clientwr(void *arg) {
2402     struct server *server = (struct server *)arg;
2403     struct request *rq;
2404     pthread_t tlsclientrdth;
2405     int i, dynconffail = 0;
2406     uint8_t rnd;
2407     struct timeval now, lastsend;
2408     struct timespec timeout;
2409     struct request statsrvrq;
2410     unsigned char statsrvbuf[38];
2411     struct clsrvconf *conf;
2412     
2413     conf = server->conf;
2414     
2415     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2416         dynconffail = 1;
2417         goto errexit;
2418     }
2419     
2420     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2421         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2422         goto errexit;
2423     }
2424
2425     memset(&timeout, 0, sizeof(struct timespec));
2426     
2427     if (conf->statusserver) {
2428         memset(&statsrvrq, 0, sizeof(struct request));
2429         memset(statsrvbuf, 0, sizeof(statsrvbuf));
2430         statsrvbuf[0] = RAD_Status_Server;
2431         statsrvbuf[3] = 38;
2432         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2433         statsrvbuf[21] = 18;
2434         gettimeofday(&lastsend, NULL);
2435     }
2436     
2437     if (conf->type == RAD_UDP) {
2438         server->connectionok = 1;
2439     } else {
2440         if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2441             goto errexit;
2442         server->connectionok = 1;
2443         if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2444             debug(DBG_ERR, "clientwr: pthread_create failed");
2445             goto errexit;
2446         }
2447     }
2448
2449     for (;;) {
2450         pthread_mutex_lock(&server->newrq_mutex);
2451         if (!server->newrq) {
2452             gettimeofday(&now, NULL);
2453             /* random 0-7 seconds */
2454             RAND_bytes(&rnd, 1);
2455             rnd /= 32;
2456             if (conf->statusserver) {
2457                 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2458                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2459             } else {
2460                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2461                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2462             }
2463 #if 0       
2464             if (timeout.tv_sec > now.tv_sec)
2465                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2466 #endif      
2467             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2468             timeout.tv_sec = 0;
2469         }
2470         if (server->newrq) {
2471             debug(DBG_DBG, "clientwr: got new request");
2472             server->newrq = 0;
2473         }
2474 #if 0   
2475         else
2476             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2477 #endif  
2478         pthread_mutex_unlock(&server->newrq_mutex);
2479
2480         for (i = 0; i < MAX_REQUESTS; i++) {
2481             if (server->clientrdgone) {
2482                 pthread_join(tlsclientrdth, NULL);
2483                 goto errexit;
2484             }
2485             pthread_mutex_lock(&server->newrq_mutex);
2486             while (i < MAX_REQUESTS && !server->requests[i].buf)
2487                 i++;
2488             if (i == MAX_REQUESTS) {
2489                 pthread_mutex_unlock(&server->newrq_mutex);
2490                 break;
2491             }
2492             rq = server->requests + i;
2493
2494             if (rq->received) {
2495                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2496                 if (rq->buf) {
2497                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2498                     freerqdata(rq);
2499                     /* setting this to NULL means that it can be reused */
2500                     rq->buf = NULL;
2501                 }
2502                 pthread_mutex_unlock(&server->newrq_mutex);
2503                 continue;
2504             }
2505             
2506             gettimeofday(&now, NULL);
2507             if (now.tv_sec < rq->expiry.tv_sec) {
2508                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2509                     timeout.tv_sec = rq->expiry.tv_sec;
2510                 pthread_mutex_unlock(&server->newrq_mutex);
2511                 continue;
2512             }
2513
2514             if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2515                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2516                 if (conf->statusserver) {
2517                     if (*rq->buf == RAD_Status_Server) {
2518                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2519                         if (server->lostrqs < 255)
2520                             server->lostrqs++;
2521                     }
2522                 } else {
2523                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2524                     if (server->lostrqs < 255)
2525                         server->lostrqs++;
2526                 }
2527                 freerqdata(rq);
2528                 /* setting this to NULL means that it can be reused */
2529                 rq->buf = NULL;
2530                 pthread_mutex_unlock(&server->newrq_mutex);
2531                 continue;
2532             }
2533             pthread_mutex_unlock(&server->newrq_mutex);
2534
2535             rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2536             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2537                 timeout.tv_sec = rq->expiry.tv_sec;
2538             rq->tries++;
2539             clientradput(server, server->requests[i].buf);
2540             gettimeofday(&lastsend, NULL);
2541         }
2542         if (conf->statusserver) {
2543             gettimeofday(&now, NULL);
2544             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2545                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2546                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2547                     continue;
2548                 }
2549                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2550                 if (!statsrvrq.buf) {
2551                     debug(DBG_ERR, "clientwr: malloc failed");
2552                     continue;
2553                 }
2554                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2555                 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2556                 lastsend.tv_sec = now.tv_sec;
2557                 sendrq(server, &statsrvrq);
2558             }
2559         }
2560     }
2561  errexit:
2562     conf->servers = NULL;
2563     if (server->dynamiclookuparg) {
2564         removeserversubrealms(realms, conf);
2565         if (dynconffail)
2566             free(conf);
2567         else
2568             freeclsrvconf(conf);
2569     }
2570     freeserver(server, 1);
2571     return NULL;
2572 }
2573
2574 void *udpserverwr(void *arg) {
2575     struct replyq *replyq = udp_server_replyq;
2576     struct reply *reply;
2577     
2578     for (;;) {
2579         pthread_mutex_lock(&replyq->mutex);
2580         while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2581             debug(DBG_DBG, "udp server writer, waiting for signal");
2582             pthread_cond_wait(&replyq->cond, &replyq->mutex);
2583             debug(DBG_DBG, "udp server writer, got signal");
2584         }
2585         pthread_mutex_unlock(&replyq->mutex);
2586
2587         if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2588                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2589             debug(DBG_WARN, "sendudp: send failed");
2590         free(reply->buf);
2591         free(reply);
2592     }
2593 }
2594
2595 void *udpserverrd(void *arg) {
2596     struct request rq;
2597     struct listenerarg *larg = (struct listenerarg *)arg;
2598     
2599     for (;;) {
2600         memset(&rq, 0, sizeof(struct request));
2601         rq.buf = radudpget(larg->s, &rq.from, NULL, &rq.fromsa);
2602         if (larg->acconly && *rq.buf != RAD_Accounting_Request) {
2603             debug(DBG_INFO, "udpserverrd: got something other than accounting-request, ignoring");
2604             freerqdata(&rq);
2605             continue;
2606         }
2607         rq.fromudpsock = larg->s;
2608         radsrv(&rq);
2609     }
2610 }
2611
2612 void *tlsserverwr(void *arg) {
2613     int cnt;
2614     unsigned long error;
2615     struct client *client = (struct client *)arg;
2616     struct replyq *replyq;
2617     struct reply *reply;
2618     
2619     debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2620     replyq = client->replyq;
2621     for (;;) {
2622         pthread_mutex_lock(&replyq->mutex);
2623         while (!list_first(replyq->replies)) {
2624             if (client->ssl) {      
2625                 debug(DBG_DBG, "tls server writer, waiting for signal");
2626                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2627                 debug(DBG_DBG, "tls server writer, got signal");
2628             }
2629             if (!client->ssl) {
2630                 /* ssl might have changed while waiting */
2631                 pthread_mutex_unlock(&replyq->mutex);
2632                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2633                 pthread_exit(NULL);
2634             }
2635         }
2636         reply = (struct reply *)list_shift(replyq->replies);
2637         pthread_mutex_unlock(&replyq->mutex);
2638         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2639         if (cnt > 0)
2640             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2641                   cnt, RADLEN(reply->buf));
2642         else
2643             while ((error = ERR_get_error()))
2644                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2645         free(reply->buf);
2646         free(reply);
2647     }
2648 }
2649
2650 void tlsserverrd(struct client *client) {
2651     struct request rq;
2652     pthread_t tlsserverwrth;
2653     
2654     debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2655     
2656     if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2657         debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2658         return;
2659     }
2660
2661     for (;;) {
2662         memset(&rq, 0, sizeof(struct request));
2663         rq.buf = radtlsget(client->ssl, 0);
2664         if (!rq.buf)
2665             break;
2666         debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2667         rq.from = client;
2668         radsrv(&rq);
2669     }
2670     
2671     debug(DBG_ERR, "tlsserverrd: connection lost");
2672     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2673     client->ssl = NULL;
2674     pthread_mutex_lock(&client->replyq->mutex);
2675     pthread_cond_signal(&client->replyq->cond);
2676     pthread_mutex_unlock(&client->replyq->mutex);
2677     debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2678     pthread_join(tlsserverwrth, NULL);
2679     removeclientrqs(client);
2680     debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2681 }
2682
2683 void *tlsservernew(void *arg) {
2684     int s;
2685     struct sockaddr_storage from;
2686     size_t fromlen = sizeof(from);
2687     struct clsrvconf *conf;
2688     struct list_node *cur = NULL;
2689     SSL *ssl = NULL;
2690     X509 *cert = NULL;
2691     unsigned long error;
2692     struct client *client;
2693
2694     s = *(int *)arg;
2695     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2696         debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2697         goto exit;
2698     }
2699     debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2700
2701     conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2702     if (conf) {
2703         ssl = SSL_new(conf->ssl_ctx);
2704         SSL_set_fd(ssl, s);
2705
2706         if (SSL_accept(ssl) <= 0) {
2707             while ((error = ERR_get_error()))
2708                 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2709             debug(DBG_ERR, "SSL_accept failed");
2710             goto exit;
2711         }
2712         cert = verifytlscert(ssl);
2713         if (!cert)
2714             goto exit;
2715     }
2716     
2717     while (conf) {
2718         if (verifyconfcert(cert, conf)) {
2719             X509_free(cert);
2720             client = addclient(conf);
2721             if (client) {
2722                 client->ssl = ssl;
2723                 tlsserverrd(client);
2724                 removeclient(client);
2725             } else
2726                 debug(DBG_WARN, "Failed to create new client instance");
2727             goto exit;
2728         }
2729         conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2730     }
2731     debug(DBG_WARN, "ignoring request, no matching TLS client");
2732     if (cert)
2733         X509_free(cert);
2734
2735  exit:
2736     SSL_free(ssl);
2737     shutdown(s, SHUT_RDWR);
2738     close(s);
2739     pthread_exit(NULL);
2740 }
2741
2742 void *tlslistener(void *arg) {
2743     pthread_t tlsserverth;
2744     int s;
2745     struct sockaddr_storage from;
2746     size_t fromlen = sizeof(from);
2747     struct listenerarg *larg = (struct listenerarg *)arg;
2748
2749     listen(larg->s, 0);
2750
2751     for (;;) {
2752         s = accept(larg->s, (struct sockaddr *)&from, &fromlen);
2753         if (s < 0) {
2754             debug(DBG_WARN, "accept failed");
2755             continue;
2756         }
2757         if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2758             debug(DBG_ERR, "tlslistener: pthread_create failed");
2759             shutdown(s, SHUT_RDWR);
2760             close(s);
2761             continue;
2762         }
2763         pthread_detach(tlsserverth);
2764     }
2765     return NULL;
2766 }
2767
2768 void createlistener(uint8_t type, char *arg, uint8_t acconly) {
2769     pthread_t th;
2770     struct clsrvconf *listenres;
2771     struct addrinfo *res;
2772     struct listenerarg *larg = NULL;
2773     int s = -1, on = 1;
2774     
2775     listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2776     if (!listenres)
2777         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2778     
2779     for (res = listenres->addrinfo; res; res = res->ai_next) {
2780         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2781         if (s < 0) {
2782             debug(DBG_WARN, "createlistener: socket failed");
2783             continue;
2784         }
2785         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2786 #ifdef IPV6_V6ONLY
2787         if (res->ai_family == AF_INET6)
2788             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2789 #endif          
2790         if (bind(s, res->ai_addr, res->ai_addrlen)) {
2791             debug(DBG_WARN, "createlistener: bind failed");
2792             close(s);
2793             s = -1;
2794             continue;
2795         }
2796
2797         larg = malloc(sizeof(struct listenerarg));
2798         if (!larg)
2799             debugx(1, DBG_ERR, "malloc failed");
2800         larg->s = s;
2801         larg->acconly = acconly;
2802         if (pthread_create(&th, NULL, type == RAD_UDP ? udpserverrd : tlslistener, (void *)larg))
2803             debugx(1, DBG_ERR, "pthread_create failed");
2804         pthread_detach(th);
2805     }
2806     if (!larg)
2807         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2808     
2809     debug(DBG_WARN, "createlistener: listening for %s%s on %s:%s",
2810           type == RAD_UDP ? "UDP" : "TCP", acconly ? " accounting" : "",
2811           listenres->host ? listenres->host : "*", listenres->port);
2812     freeclsrvres(listenres);
2813 }
2814
2815 void createlisteners(uint8_t type, char **args, uint8_t acconly) {
2816     int i;
2817
2818     if (args)
2819         for (i = 0; args[i]; i++)
2820             createlistener(type, args[i], acconly);
2821     else
2822         createlistener(type, NULL, acconly);
2823 }
2824
2825 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
2826     struct tls *new;
2827     SSL_CTX *ctx;
2828     STACK_OF(X509_NAME) *calist;
2829     X509_STORE *x509_s;
2830     int i;
2831     unsigned long error;
2832     
2833     if (!certfile || !certkeyfile)
2834         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2835
2836     if (!cacertfile && !cacertpath)
2837         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2838
2839     if (!ssl_locks) {
2840         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2841         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2842         for (i = 0; i < CRYPTO_num_locks(); i++) {
2843             ssl_lock_count[i] = 0;
2844             pthread_mutex_init(&ssl_locks[i], NULL);
2845         }
2846         CRYPTO_set_id_callback(ssl_thread_id);
2847         CRYPTO_set_locking_callback(ssl_locking_callback);
2848
2849         SSL_load_error_strings();
2850         SSL_library_init();
2851
2852         while (!RAND_status()) {
2853             time_t t = time(NULL);
2854             pid_t pid = getpid();
2855             RAND_seed((unsigned char *)&t, sizeof(time_t));
2856             RAND_seed((unsigned char *)&pid, sizeof(pid));
2857         }
2858     }
2859     ctx = SSL_CTX_new(TLSv1_method());
2860     if (certkeypwd) {
2861         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2862         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2863     }
2864     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2865         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2866         !SSL_CTX_check_private_key(ctx) ||
2867         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2868         while ((error = ERR_get_error()))
2869             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2870         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2871     }
2872
2873     calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2874     if (!cacertfile || calist) {
2875         if (cacertpath) {
2876             if (!calist)
2877                 calist = sk_X509_NAME_new_null();
2878             if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2879                 sk_X509_NAME_free(calist);
2880                 calist = NULL;
2881             }
2882         }
2883     }
2884     if (!calist) {
2885         while ((error = ERR_get_error()))
2886             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2887         debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2888     }
2889     SSL_CTX_set_client_CA_list(ctx, calist);
2890     
2891     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2892     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2893
2894     if (crlcheck) {
2895         x509_s = SSL_CTX_get_cert_store(ctx);
2896         X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2897     }
2898
2899     new = malloc(sizeof(struct tls));
2900     if (!new || !list_push(tlsconfs, new))
2901         debugx(1, DBG_ERR, "malloc failed");
2902
2903     memset(new, 0, sizeof(struct tls));
2904     new->name = stringcopy(value, 0);
2905     if (!new->name)
2906         debugx(1, DBG_ERR, "malloc failed");
2907     new->ctx = ctx;
2908     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2909 }
2910
2911 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2912     struct list_node *entry;
2913     struct tls *t, *t1 = NULL, *t2 = NULL;
2914     
2915     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2916         t = (struct tls *)entry->data;
2917         if (!strcasecmp(t->name, alt1)) {
2918             t1 = t;
2919             break;
2920         }
2921         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2922             t2 = t;
2923     }
2924
2925     t = (t1 ? t1 : t2);
2926     if (!t)
2927         return NULL;
2928     return t->ctx;
2929 }
2930
2931 struct list *addsrvconfs(char *value, char **names) {
2932     struct list *conflist;
2933     int n;
2934     struct list_node *entry;
2935     struct clsrvconf *conf = NULL;
2936     
2937     if (!names || !*names)
2938         return NULL;
2939     
2940     conflist = list_create();
2941     if (!conflist) {
2942         debug(DBG_ERR, "malloc failed");
2943         return NULL;
2944     }
2945
2946     for (n = 0; names[n]; n++) {
2947         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2948             conf = (struct clsrvconf *)entry->data;
2949             if (!strcasecmp(names[n], conf->name))
2950                 break;
2951         }
2952         if (!entry) {
2953             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2954             list_destroy(conflist);
2955             return NULL;
2956         }
2957         if (!list_push(conflist, conf)) {
2958             debug(DBG_ERR, "malloc failed");
2959             list_destroy(conflist);
2960             return NULL;
2961         }
2962         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2963     }
2964     return conflist;
2965 }
2966
2967 void freerealm(struct realm *realm) {
2968     if (!realm)
2969         return;
2970     free(realm->name);
2971     free(realm->message);
2972     regfree(&realm->regex);
2973     pthread_mutex_destroy(&realm->subrealms_mutex);
2974     if (realm->subrealms)
2975         list_destroy(realm->subrealms);
2976     if (realm->srvconfs) {
2977         /* emptying list without freeing data */
2978         while (list_shift(realm->srvconfs));
2979         list_destroy(realm->srvconfs);
2980     }
2981     if (realm->accsrvconfs) {
2982         /* emptying list without freeing data */
2983         while (list_shift(realm->accsrvconfs));
2984         list_destroy(realm->accsrvconfs);
2985     }
2986     free(realm);
2987 }
2988
2989 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2990     int n;
2991     struct realm *realm;
2992     char *s, *regex = NULL;
2993     
2994     if (*value == '/') {
2995         /* regexp, remove optional trailing / if present */
2996         if (value[strlen(value) - 1] == '/')
2997             value[strlen(value) - 1] = '\0';
2998     } else {
2999         /* not a regexp, let us make it one */
3000         if (*value == '*' && !value[1])
3001             regex = stringcopy(".*", 0);
3002         else {
3003             for (n = 0, s = value; *s;)
3004                 if (*s++ == '.')
3005                     n++;
3006             regex = malloc(strlen(value) + n + 3);
3007             if (regex) {
3008                 regex[0] = '@';
3009                 for (n = 1, s = value; *s; s++) {
3010                     if (*s == '.')
3011                         regex[n++] = '\\';
3012                     regex[n++] = *s;
3013                 }
3014                 regex[n++] = '$';
3015                 regex[n] = '\0';
3016             }
3017         }
3018         if (!regex) {
3019             debug(DBG_ERR, "malloc failed");
3020             realm = NULL;
3021             goto exit;
3022         }
3023         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3024     }
3025
3026     realm = malloc(sizeof(struct realm));
3027     if (!realm) {
3028         debug(DBG_ERR, "malloc failed");
3029         goto exit;
3030     }
3031     memset(realm, 0, sizeof(struct realm));
3032     
3033     if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3034         debug(DBG_ERR, "mutex init failed");
3035         free(realm);
3036         realm = NULL;
3037         goto exit;
3038     }
3039
3040     realm->name = stringcopy(value, 0);
3041     if (!realm->name) {
3042         debug(DBG_ERR, "malloc failed");
3043         goto errexit;
3044     }
3045     if (message && strlen(message) > 253) {
3046         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3047         goto errexit;
3048     }
3049     realm->message = message;
3050     realm->accresp = accresp;
3051     
3052     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3053         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3054         goto errexit;
3055     }
3056     
3057     if (servers && *servers) {
3058         realm->srvconfs = addsrvconfs(value, servers);
3059         if (!realm->srvconfs)
3060             goto errexit;
3061     }
3062     
3063     if (accservers && *accservers) {
3064         realm->accsrvconfs = addsrvconfs(value, accservers);
3065         if (!realm->accsrvconfs)
3066             goto errexit;
3067     }
3068
3069     if (!list_push(realmlist, realm)) {
3070         debug(DBG_ERR, "malloc failed");
3071         pthread_mutex_destroy(&realm->subrealms_mutex);
3072         goto errexit;
3073     }
3074     
3075     debug(DBG_DBG, "addrealm: added realm %s", value);
3076     goto exit;
3077
3078  errexit:
3079     freerealm(realm);
3080     realm = NULL;
3081     
3082  exit:
3083     free(regex);
3084     if (servers) {
3085         for (n = 0; servers[n]; n++)
3086             free(servers[n]);
3087         free(servers);
3088     }
3089     if (accservers) {
3090         for (n = 0; accservers[n]; n++)
3091             free(accservers[n]);
3092         free(accservers);
3093     }
3094     return realm;
3095 }
3096
3097 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3098     struct clsrvconf *srvconf;
3099     struct realm *newrealm = NULL;
3100     char *realmname, *s;
3101     pthread_t clientth;
3102     
3103     if (!conf->dynamiclookupcommand)
3104         return;
3105
3106     /* create dynamic for the realm (string after last @, exit if nothing after @ */
3107     realmname = strrchr(id, '@');
3108     if (!realmname)
3109         return;
3110     realmname++;
3111     if (!*realmname)
3112         return;
3113     for (s = realmname; *s; s++)
3114         if (*s != '.' && *s != '-' && !isalnum((int)*s))
3115             return;
3116     
3117     pthread_mutex_lock(&realm->subrealms_mutex);
3118     /* exit if we now already got a matching subrealm */
3119     if (id2realm(realm->subrealms, id))
3120         goto exit;
3121     srvconf = malloc(sizeof(struct clsrvconf));
3122     if (!srvconf) {
3123         debug(DBG_ERR, "malloc failed");
3124         goto exit;
3125     }
3126     *srvconf = *conf;
3127     if (!addserver(srvconf))
3128         goto errexit;
3129
3130     if (!realm->subrealms)
3131         realm->subrealms = list_create();
3132     if (!realm->subrealms)
3133         goto errexit;
3134     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3135     if (!newrealm)
3136         goto errexit;
3137
3138     /* add server and accserver to newrealm */
3139     newrealm->srvconfs = list_create();
3140     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3141         debug(DBG_ERR, "malloc failed");
3142         goto errexit;
3143     }
3144     newrealm->accsrvconfs = list_create();
3145     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3146         debug(DBG_ERR, "malloc failed");
3147         goto errexit;
3148     }
3149
3150     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3151
3152     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3153         debug(DBG_ERR, "pthread_create failed");
3154         goto errexit;
3155     }
3156     pthread_detach(clientth);
3157     goto exit;
3158     
3159  errexit:
3160     if (newrealm) {
3161         list_removedata(realm->subrealms, newrealm);
3162         freerealm(newrealm);
3163         if (!list_first(realm->subrealms)) {
3164             list_destroy(realm->subrealms);
3165             realm->subrealms = NULL;
3166         }
3167     }
3168     freeserver(srvconf->servers, 1);
3169     free(srvconf);
3170     debug(DBG_ERR, "failed to create dynamic server");
3171
3172  exit:
3173     pthread_mutex_unlock(&realm->subrealms_mutex);
3174 }
3175
3176 int dynamicconfig(struct server *server) {
3177     int ok, fd[2], status;
3178     pid_t pid;
3179     struct clsrvconf *conf = server->conf;
3180     struct gconffile *cf = NULL;
3181     
3182     /* for now we only learn hostname/address */
3183     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3184
3185     if (pipe(fd) > 0) {
3186         debug(DBG_ERR, "dynamicconfig: pipe error");
3187         goto errexit;
3188     }
3189     pid = fork();
3190     if (pid < 0) {
3191         debug(DBG_ERR, "dynamicconfig: fork error");
3192         close(fd[0]);
3193         close(fd[1]);
3194         goto errexit;
3195     } else if (pid == 0) {
3196         /* child */
3197         close(fd[0]);
3198         if (fd[1] != STDOUT_FILENO) {
3199             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3200                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3201             close(fd[1]);
3202         }
3203         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3204             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3205     }
3206
3207     close(fd[1]);
3208     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3209     ok = getgenericconfig(&cf, NULL,
3210                           "Server", CONF_CBK, confserver_cb, (void *)conf,
3211                           NULL
3212                           );
3213     freegconf(&cf);
3214         
3215     if (waitpid(pid, &status, 0) < 0) {
3216         debug(DBG_ERR, "dynamicconfig: wait error");
3217         goto errexit;
3218     }
3219     
3220     if (status) {
3221         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3222         goto errexit;
3223     }
3224
3225     if (ok)
3226         return 1;
3227
3228  errexit:    
3229     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3230     return 0;
3231 }
3232
3233 int addmatchcertattr(struct clsrvconf *conf) {
3234     char *v;
3235     regex_t **r;
3236     
3237     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3238         r = &conf->certcnregex;
3239         v = conf->matchcertattr + 4;
3240     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3241         r = &conf->certuriregex;
3242         v = conf->matchcertattr + 20;
3243     } else
3244         return 0;
3245     if (!*v)
3246         return 0;
3247     /* regexp, remove optional trailing / if present */
3248     if (v[strlen(v) - 1] == '/')
3249         v[strlen(v) - 1] = '\0';
3250     if (!*v)
3251         return 0;
3252
3253     *r = malloc(sizeof(regex_t));
3254     if (!*r) {
3255         debug(DBG_ERR, "malloc failed");
3256         return 0;
3257     }
3258     if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3259         free(*r);
3260         *r = NULL;
3261         debug(DBG_ERR, "failed to compile regular expression %s", v);
3262         return 0;
3263     }
3264     return 1;
3265 }
3266
3267 int addrewriteattr(struct clsrvconf *conf) {
3268     char *v, *w;
3269     
3270     v = conf->rewriteattr + 11;
3271     if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3272         return 0;
3273     /* regexp, remove optional trailing / if present */
3274     if (v[strlen(v) - 1] == '/')
3275         v[strlen(v) - 1] = '\0';
3276
3277     w = strchr(v, '/');
3278     if (!*w)
3279         return 0;
3280     *w = '\0';
3281     w++;
3282     
3283     conf->rewriteattrregex = malloc(sizeof(regex_t));
3284     if (!conf->rewriteattrregex) {
3285         debug(DBG_ERR, "malloc failed");
3286         return 0;
3287     }
3288
3289     conf->rewriteattrreplacement = stringcopy(w, 0);
3290     if (!conf->rewriteattrreplacement) {
3291         free(conf->rewriteattrregex);
3292         conf->rewriteattrregex = NULL;
3293         return 0;
3294     }
3295     
3296     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3297         free(conf->rewriteattrregex);
3298         conf->rewriteattrregex = NULL;
3299         free(conf->rewriteattrreplacement);
3300         conf->rewriteattrreplacement = NULL;
3301         debug(DBG_ERR, "failed to compile regular expression %s", v);
3302         return 0;
3303     }
3304
3305     return 1;
3306 }
3307
3308 /* should accept both names and numeric values, only numeric right now */
3309 uint8_t attrname2val(char *attrname) {
3310     int val = 0;
3311     
3312     val = atoi(attrname);
3313     return val > 0 && val < 256 ? val : 0;
3314 }
3315
3316 /* should accept both names and numeric values, only numeric right now */
3317 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3318     char *s;
3319     
3320     *vendor = atoi(attrname);
3321     s = strchr(attrname, ':');
3322     if (!s) {
3323         *type = -1;
3324         return 1;
3325     }
3326     *type = atoi(s + 1);
3327     return *type >= 0 && *type < 256;
3328 }
3329
3330 struct rewrite *getrewrite(char *alt1, char *alt2) {
3331     struct list_node *entry;
3332     struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3333     
3334     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3335         r = (struct rewriteconf *)entry->data;
3336         if (!strcasecmp(r->name, alt1)) {
3337             r1 = r;
3338             break;
3339         }
3340         if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3341             r2 = r;
3342     }
3343
3344     r = (r1 ? r1 : r2);
3345     if (!r)
3346         return NULL;
3347     return r->rewrite;
3348 }
3349
3350 void addrewrite(char *value, char **attrs, char **vattrs) {
3351     struct rewriteconf *new;
3352     struct rewrite *rewrite = NULL;
3353     int i, n;
3354     uint8_t *a = NULL;
3355     uint32_t *p, *va = NULL;
3356
3357     if (attrs) {
3358         n = 0;
3359         for (; attrs[n]; n++);
3360         a = malloc((n + 1) * sizeof(uint8_t));
3361         if (!a)
3362             debugx(1, DBG_ERR, "malloc failed");
3363     
3364         for (i = 0; i < n; i++) {
3365             if (!(a[i] = attrname2val(attrs[i])))
3366                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3367             free(attrs[i]);
3368         }
3369         free(attrs);
3370         a[i] = 0;
3371     }
3372     
3373     if (vattrs) {
3374         n = 0;
3375         for (; vattrs[n]; n++);
3376         va = malloc((2 * n + 1) * sizeof(uint32_t));
3377         if (!va)
3378             debugx(1, DBG_ERR, "malloc failed");
3379     
3380         for (p = va, i = 0; i < n; i++, p += 2) {
3381             if (!vattrname2val(vattrs[i], p, p + 1))
3382                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3383             free(vattrs[i]);
3384         }
3385         free(vattrs);
3386         *p = 0;
3387     }
3388     
3389     if (a || va) {
3390         rewrite = malloc(sizeof(struct rewrite));
3391         if (!rewrite)
3392             debugx(1, DBG_ERR, "malloc failed");
3393         rewrite->removeattrs = a;
3394         rewrite->removevendorattrs = va;
3395     }
3396     
3397     new = malloc(sizeof(struct rewriteconf));
3398     if (!new || !list_push(rewriteconfs, new))
3399         debugx(1, DBG_ERR, "malloc failed");
3400
3401     memset(new, 0, sizeof(struct rewriteconf));
3402     new->name = stringcopy(value, 0);
3403     if (!new->name)
3404         debugx(1, DBG_ERR, "malloc failed");
3405         
3406     new->rewrite = rewrite;
3407     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3408 }
3409
3410 void freeclsrvconf(struct clsrvconf *conf) {
3411     free(conf->name);
3412     free(conf->host);
3413     free(conf->port);
3414     free(conf->secret);
3415     free(conf->tls);
3416     free(conf->matchcertattr);
3417     if (conf->certcnregex)
3418         regfree(conf->certcnregex);
3419     if (conf->certuriregex)
3420         regfree(conf->certuriregex);
3421     free(conf->confrewrite);
3422     free(conf->rewriteattr);
3423     if (conf->rewriteattrregex)
3424         regfree(conf->rewriteattrregex);
3425     free(conf->rewriteattrreplacement);
3426     free(conf->dynamiclookupcommand);
3427     free(conf->rewrite);
3428     if (conf->addrinfo)
3429         freeaddrinfo(conf->addrinfo);
3430     /* not touching ssl_ctx, clients and servers */
3431     free(conf);
3432 }
3433
3434 int mergeconfstring(char **dst, char **src) {
3435     char *t;
3436     
3437     if (*src) {
3438         *dst = *src;
3439         *src = NULL;
3440         return 1;
3441     }
3442     if (*dst) {
3443         t = stringcopy(*dst, 0);
3444         if (!t) {
3445             debug(DBG_ERR, "malloc failed");
3446             return 0;
3447         }
3448         *dst = t;
3449     }
3450     return 1;
3451 }
3452
3453 /* assumes dst is a shallow copy */
3454 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3455     if (!mergeconfstring(&dst->name, &src->name) ||
3456         !mergeconfstring(&dst->host, &src->host) ||
3457         !mergeconfstring(&dst->port, &src->port) ||
3458         !mergeconfstring(&dst->secret, &src->secret) ||
3459         !mergeconfstring(&dst->tls, &src->tls) ||
3460         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3461         !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3462         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3463         return 0;
3464     if (src->pdef)
3465         dst->pdef = src->pdef;
3466     dst->statusserver = src->statusserver;
3467     dst->certnamecheck = src->certnamecheck;
3468     if (src->retryinterval != 255)
3469         dst->retryinterval = src->retryinterval;
3470     if (src->retrycount != 255)
3471         dst->retrycount = src->retrycount;
3472     return 1;
3473 }
3474
3475 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3476     struct clsrvconf *conf;
3477     char *conftype = NULL;
3478     
3479     debug(DBG_DBG, "confclient_cb called for %s", block);
3480
3481     conf = malloc(sizeof(struct clsrvconf));
3482     if (!conf || !list_push(clconfs, conf))
3483         debugx(1, DBG_ERR, "malloc failed");
3484     memset(conf, 0, sizeof(struct clsrvconf));
3485     conf->certnamecheck = 1;
3486     
3487     if (!getgenericconfig(cf, block,
3488                      "type", CONF_STR, &conftype,
3489                      "host", CONF_STR, &conf->host,
3490                      "secret", CONF_STR, &conf->secret,
3491                      "tls", CONF_STR, &conf->tls,
3492                      "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3493                      "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3494                      "rewrite", CONF_STR, &conf->confrewrite,
3495                      "rewriteattribute", CONF_STR, &conf->rewriteattr,
3496                      NULL
3497                           ))
3498         debugx(1, DBG_ERR, "configuration error");
3499     
3500     conf->name = stringcopy(val, 0);
3501     if (!conf->host)
3502         conf->host = stringcopy(val, 0);
3503
3504     if (!conftype)
3505         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3506     conf->type = protoname2int(conftype);
3507     conf->pdef = &protodefs[conf->type];
3508     if (!conf->pdef->name)
3509         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3510     free(conftype);
3511     
3512     if (conf->type == RAD_TLS) {
3513         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3514         if (!conf->ssl_ctx)
3515             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3516         if (conf->matchcertattr && !addmatchcertattr(conf))
3517             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3518     }
3519     
3520     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3521     
3522     if (conf->rewriteattr) {
3523         if (!addrewriteattr(conf))
3524             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3525     }
3526     
3527     if (!resolvepeer(conf, 0))
3528         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3529     
3530     if (!conf->secret) {
3531         if (!conf->pdef->secretdefault)
3532             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3533         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3534         if (!conf->secret)
3535             debugx(1, DBG_ERR, "malloc failed");
3536     }
3537     return 1;
3538 }
3539
3540 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3541     if (conf->type == RAD_TLS) {
3542         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3543         if (!conf->ssl_ctx) {
3544             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3545             return 0;
3546         }
3547         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3548             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3549             return 0;
3550         }
3551     }
3552
3553     if (!conf->port) {
3554         conf->port = stringcopy(conf->pdef->portdefault, 0);
3555         if (!conf->port) {
3556             debug(DBG_ERR, "malloc failed");
3557             return 0;
3558         }
3559     }
3560     
3561     if (conf->retryinterval == 255)
3562         conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3563     if (conf->retrycount == 255)
3564         conf->retrycount = protodefs[conf->type].retrycountdefault;
3565     
3566     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3567
3568     if (!conf->secret) {
3569         if (!conf->pdef->secretdefault) {
3570             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3571             return 0;
3572         }
3573         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3574         if (!conf->secret) {
3575             debug(DBG_ERR, "malloc failed");
3576             return 0;
3577         }
3578     }
3579     
3580     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3581         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3582         return 0;
3583     }
3584     return 1;
3585 }
3586                         
3587 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3588     struct clsrvconf *conf, *resconf;
3589     char *conftype = NULL;
3590     long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3591     
3592     debug(DBG_DBG, "confserver_cb called for %s", block);
3593
3594     conf = malloc(sizeof(struct clsrvconf));
3595     if (!conf) {
3596         debug(DBG_ERR, "malloc failed");
3597         return 0;
3598     }
3599     memset(conf, 0, sizeof(struct clsrvconf));
3600     resconf = (struct clsrvconf *)arg;
3601     if (resconf) {
3602         conf->statusserver = resconf->statusserver;
3603         conf->certnamecheck = resconf->certnamecheck;
3604     } else
3605         conf->certnamecheck = 1;
3606
3607     if (!getgenericconfig(cf, block,
3608                           "type", CONF_STR, &conftype,
3609                           "host", CONF_STR, &conf->host,
3610                           "port", CONF_STR, &conf->port,
3611                           "secret", CONF_STR, &conf->secret,
3612                           "tls", CONF_STR, &conf->tls,
3613                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3614                           "rewrite", CONF_STR, &conf->confrewrite,
3615                           "StatusServer", CONF_BLN, &conf->statusserver,
3616                           "RetryInterval", CONF_LINT, &retryinterval,
3617                           "RetryCount", CONF_LINT, &retrycount,
3618                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3619                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3620                           NULL
3621                           )) {
3622         debug(DBG_ERR, "configuration error");
3623         goto errexit;
3624     }
3625     
3626     conf->name = stringcopy(val, 0);
3627     if (!conf->name) {
3628         debug(DBG_ERR, "malloc failed");
3629         goto errexit;
3630     }
3631     if (!conf->host) {
3632         conf->host = stringcopy(val, 0);
3633         if (!conf->host) {
3634             debug(DBG_ERR, "malloc failed");
3635             goto errexit;
3636         }
3637     }
3638
3639     if (!conftype)
3640         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3641     conf->type = protoname2int(conftype);
3642     conf->pdef = &protodefs[conf->type];
3643     if (!conf->pdef->name) {
3644         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3645         free(conftype);
3646         goto errexit;
3647     }
3648     free(conftype);
3649             
3650     if (retryinterval != LONG_MIN) {
3651         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3652             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3653             goto errexit;
3654         }
3655         conf->retryinterval = (uint8_t)retryinterval;
3656     } else
3657         conf->retryinterval = 255;
3658     
3659     if (retrycount != LONG_MIN) {
3660         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3661             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3662             goto errexit;
3663         }
3664         conf->retrycount = (uint8_t)retrycount;
3665     } else
3666         conf->retrycount = 255;
3667     
3668     if (resconf) {
3669         if (!mergesrvconf(resconf, conf))
3670             goto errexit;
3671         free(conf);
3672         conf = resconf;
3673         if (conf->dynamiclookupcommand) {
3674             free(conf->dynamiclookupcommand);
3675             conf->dynamiclookupcommand = NULL;
3676         }
3677     }
3678
3679     if (resconf || !conf->dynamiclookupcommand) {
3680         if (!compileserverconfig(conf, block))
3681             goto errexit;
3682     }
3683     
3684     if (resconf)
3685         return 1;
3686         
3687     if (!list_push(srvconfs, conf)) {
3688         debug(DBG_ERR, "malloc failed");
3689         goto errexit;
3690     }
3691     return 1;
3692
3693  errexit:    
3694     freeclsrvconf(conf);
3695     return 0;
3696 }
3697
3698 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3699     char **servers = NULL, **accservers = NULL, *msg = NULL;
3700     uint8_t accresp = 0;
3701     
3702     debug(DBG_DBG, "confrealm_cb called for %s", block);
3703     
3704     if (!getgenericconfig(cf, block,
3705                      "server", CONF_MSTR, &servers,
3706                      "accountingServer", CONF_MSTR, &accservers,
3707                      "ReplyMessage", CONF_STR, &msg,
3708                      "AccountingResponse", CONF_BLN, &accresp,
3709                      NULL
3710                           ))
3711         debugx(1, DBG_ERR, "configuration error");
3712
3713     addrealm(realms, val, servers, accservers, msg, accresp);
3714     return 1;
3715 }
3716
3717 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3718     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3719     uint8_t crlcheck = 0;
3720     
3721     debug(DBG_DBG, "conftls_cb called for %s", block);
3722     
3723     if (!getgenericconfig(cf, block,
3724                      "CACertificateFile", CONF_STR, &cacertfile,
3725                      "CACertificatePath", CONF_STR, &cacertpath,
3726                      "CertificateFile", CONF_STR, &certfile,
3727                      "CertificateKeyFile", CONF_STR, &certkeyfile,
3728                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
3729                      "CRLCheck", CONF_BLN, &crlcheck,
3730                      NULL
3731                           ))
3732         debugx(1, DBG_ERR, "configuration error");
3733     
3734     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
3735     free(cacertfile);
3736     free(cacertpath);
3737     free(certfile);
3738     free(certkeyfile);
3739     free(certkeypwd);
3740     return 1;
3741 }
3742
3743 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3744     char **attrs = NULL, **vattrs = NULL;
3745     
3746     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3747     
3748     if (!getgenericconfig(cf, block,
3749                      "removeAttribute", CONF_MSTR, &attrs,
3750                      "removeVendorAttribute", CONF_MSTR, &vattrs,
3751                      NULL
3752                           ))
3753         debugx(1, DBG_ERR, "configuration error");
3754     addrewrite(val, attrs, vattrs);
3755     return 1;
3756 }
3757
3758 void getmainconfig(const char *configfile) {
3759     long int loglevel = LONG_MIN;
3760     struct gconffile *cfs;
3761
3762     cfs = openconfigfile(configfile);
3763     memset(&options, 0, sizeof(options));
3764     
3765     clconfs = list_create();
3766     if (!clconfs)
3767         debugx(1, DBG_ERR, "malloc failed");
3768     
3769     srvconfs = list_create();
3770     if (!srvconfs)
3771         debugx(1, DBG_ERR, "malloc failed");
3772     
3773     realms = list_create();
3774     if (!realms)
3775         debugx(1, DBG_ERR, "malloc failed");    
3776  
3777     tlsconfs = list_create();
3778     if (!tlsconfs)
3779         debugx(1, DBG_ERR, "malloc failed");
3780     
3781     rewriteconfs = list_create();
3782     if (!rewriteconfs)
3783         debugx(1, DBG_ERR, "malloc failed");    
3784  
3785     if (!getgenericconfig(&cfs, NULL,
3786                           "ListenUDP", CONF_MSTR, &options.listenudp,
3787                           "ListenTCP", CONF_MSTR, &options.listentcp,
3788                           "ListenTLS", CONF_MSTR, &options.listentls,
3789                           "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3790                           "SourceUDP", CONF_STR, &options.sourceudp,
3791                           "SourceTCP", CONF_STR, &options.sourcetcp,
3792                           "LogLevel", CONF_LINT, &loglevel,
3793                           "LogDestination", CONF_STR, &options.logdestination,
3794                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3795                           "Client", CONF_CBK, confclient_cb, NULL,
3796                           "Server", CONF_CBK, confserver_cb, NULL,
3797                           "Realm", CONF_CBK, confrealm_cb, NULL,
3798                           "TLS", CONF_CBK, conftls_cb, NULL,
3799                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3800                           NULL
3801                           ))
3802         debugx(1, DBG_ERR, "configuration error");
3803     
3804     if (loglevel != LONG_MIN) {
3805         if (loglevel < 1 || loglevel > 4)
3806             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3807         options.loglevel = (uint8_t)loglevel;
3808     }
3809 }
3810
3811 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3812     int c;
3813
3814     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3815         switch (c) {
3816         case 'c':
3817             *configfile = optarg;
3818             break;
3819         case 'd':
3820             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3821                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3822             *loglevel = *optarg - '0';
3823             break;
3824         case 'f':
3825             *foreground = 1;
3826             break;
3827         case 'p':
3828             *pretend = 1;
3829             break;
3830         case 'v':
3831                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3832         default:
3833             goto usage;
3834         }
3835     }
3836     if (!(argc - optind))
3837         return;
3838
3839  usage:
3840     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3841 }
3842
3843 #ifdef SYS_SOLARIS9
3844 int daemon(int a, int b) {
3845     int i;
3846
3847     if (fork())
3848         exit(0);
3849
3850     setsid();
3851
3852     for (i = 0; i < 3; i++) {
3853         close(i);
3854         open("/dev/null", O_RDWR);
3855     }
3856     return 1;
3857 }
3858 #endif
3859
3860 void *sighandler(void *arg) {
3861     sigset_t sigset;
3862     int sig;
3863
3864     for(;;) {
3865         sigemptyset(&sigset);
3866         sigaddset(&sigset, SIGPIPE);
3867         sigwait(&sigset, &sig);
3868         /* only get SIGPIPE right now, so could simplify below code */
3869         switch (sig) {
3870         case 0:
3871             /* completely ignoring this */
3872             break;
3873         case SIGPIPE:
3874             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3875             break;
3876         default:
3877             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3878         }
3879     }
3880 }
3881
3882 int main(int argc, char **argv) {
3883     pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
3884     sigset_t sigset;
3885     struct list_node *entry;
3886     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3887     char *configfile = NULL;
3888     struct clsrvconf *srvconf;
3889     
3890     debug_init("radsecproxy");
3891     debug_set_level(DEBUG_LEVEL);
3892     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3893     if (loglevel)
3894         debug_set_level(loglevel);
3895     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3896     if (loglevel)
3897         options.loglevel = loglevel;
3898     else if (options.loglevel)
3899         debug_set_level(options.loglevel);
3900     if (!foreground)
3901         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3902     free(options.logdestination);
3903
3904     if (!list_first(clconfs))
3905         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3906     if (!list_first(srvconfs))
3907         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3908     if (!list_first(realms))
3909         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3910
3911     if (pretend)
3912         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3913
3914     if (!foreground && (daemon(0, 0) < 0))
3915         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3916     
3917     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3918
3919     sigemptyset(&sigset);
3920     /* exit on all but SIGPIPE, ignore more? */
3921     sigaddset(&sigset, SIGPIPE);
3922     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3923     pthread_create(&sigth, NULL, sighandler, NULL);
3924
3925     if (find_conf_type(RAD_UDP, clconfs, NULL)) {
3926         udp_server_replyq = newreplyq();
3927         if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
3928             debugx(1, DBG_ERR, "pthread_create failed");
3929         createlisteners(RAD_UDP, options.listenudp, 0);
3930         if (options.listenaccudp)
3931             createlisteners(RAD_UDP, options.listenaccudp, 1);
3932     }
3933     
3934     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3935         srvconf = (struct clsrvconf *)entry->data;
3936         if (srvconf->dynamiclookupcommand)
3937             continue;
3938         if (!addserver(srvconf))
3939             debugx(1, DBG_ERR, "failed to add server");
3940         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3941                            (void *)(srvconf->servers)))
3942             debugx(1, DBG_ERR, "pthread_create failed");
3943     }
3944     /* srcudpres no longer needed, while srctcpres is needed later */
3945     if (srcudpres) {
3946         freeaddrinfo(srcudpres);
3947         srcudpres = NULL;
3948     }
3949     if (udp_client4_sock >= 0)
3950         if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3951             debugx(1, DBG_ERR, "pthread_create failed");
3952     if (udp_client6_sock >= 0)
3953         if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3954             debugx(1, DBG_ERR, "pthread_create failed");
3955     
3956     if (find_conf_type(RAD_TLS, clconfs, NULL))
3957         createlisteners(RAD_TLS, options.listentls, 0);
3958     
3959     /* just hang around doing nothing, anything to do here? */
3960     for (;;)
3961         sleep(1000);
3962 }