split clientrd into udpclientrd and tlsclientrd
[radsecproxy.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006, 2007 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 <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netdb.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <arpa/inet.h>
40 #include <regex.h>
41 #include <libgen.h>
42 #include <pthread.h>
43 #include <openssl/ssl.h>
44 #include <openssl/rand.h>
45 #include <openssl/err.h>
46 #include <openssl/md5.h>
47 #include <openssl/hmac.h>
48 #include <openssl/x509v3.h>
49 #include "debug.h"
50 #include "list.h"
51 #include "radsecproxy.h"
52
53 static struct options options;
54 struct list *clconfs, *srvconfs, *realms, *tlsconfs;
55
56 static int client_udp_count = 0;
57 static int client_tls_count = 0;
58 static int server_udp_count = 0;
59 static int server_tls_count = 0;
60
61 static struct clsrvconf *tcp_server_listen;
62 static struct clsrvconf *udp_server_listen;
63 static struct clsrvconf *udp_accserver_listen;
64 static struct replyq *udp_server_replyq = NULL;
65 static int udp_server_sock = -1;
66 static int udp_accserver_sock = -1;
67 static pthread_mutex_t *ssl_locks;
68 static long *ssl_lock_count;
69 extern int optind;
70 extern char *optarg;
71
72 /* callbacks for making OpenSSL thread safe */
73 unsigned long ssl_thread_id() {
74         return (unsigned long)pthread_self();
75 }
76
77 void ssl_locking_callback(int mode, int type, const char *file, int line) {
78     if (mode & CRYPTO_LOCK) {
79         pthread_mutex_lock(&ssl_locks[type]);
80         ssl_lock_count[type]++;
81     } else
82         pthread_mutex_unlock(&ssl_locks[type]);
83 }
84
85 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
86     int pwdlen = strlen(userdata);
87     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
88         return 0;
89     memcpy(buf, userdata, pwdlen);
90     return pwdlen;
91 }
92
93 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
94   char buf[256];
95   X509 *err_cert;
96   int err, depth;
97
98   err_cert = X509_STORE_CTX_get_current_cert(ctx);
99   err = X509_STORE_CTX_get_error(ctx);
100   depth = X509_STORE_CTX_get_error_depth(ctx);
101
102   if (depth > MAX_CERT_DEPTH) {
103       ok = 0;
104       err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
105       X509_STORE_CTX_set_error(ctx, err);
106   }
107
108   if (!ok) {
109       X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
110       debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
111
112       switch (err) {
113       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
114           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
115           debug(DBG_WARN, "\tIssuer=%s", buf);
116           break;
117       case X509_V_ERR_CERT_NOT_YET_VALID:
118       case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
119           debug(DBG_WARN, "\tCertificate not yet valid");
120           break;
121       case X509_V_ERR_CERT_HAS_EXPIRED:
122           debug(DBG_WARN, "Certificate has expired");
123           break;
124       case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
125           debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
126           break;
127       }
128   }
129 #ifdef DEBUG  
130   printf("certificate verify returns %d\n", ok);
131 #endif  
132   return ok;
133 }
134
135 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
136     struct addrinfo hints, *addrinfo;
137     char *slash, *s;
138     int plen;
139
140     slash = conf->host ? strchr(conf->host, '/') : NULL;
141     if (slash) {
142         s = slash + 1;
143         if (!*s) {
144             debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
145             return 0;
146         }
147         for (; *s; s++)
148             if (*s < '0' || *s > '9') {
149                 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
150                 return 0;
151             }
152         plen = atoi(slash + 1);
153         if (plen < 0 || plen > 128) {
154             debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
155             return 0;
156         }
157         *slash = '\0';
158     }
159     memset(&hints, 0, sizeof(hints));
160     hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
161     hints.ai_family = AF_UNSPEC;
162     hints.ai_flags = ai_flags;
163     if (slash)
164         hints.ai_flags |= AI_NUMERICHOST;
165     if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
166         debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
167         return 0;
168     }
169
170     if (slash) {
171         *slash = '/';
172         switch (addrinfo->ai_family) {
173         case AF_INET:
174             if (plen > 32) {
175                 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
176                 freeaddrinfo(addrinfo);
177                 return 0;
178             }
179             break;
180         case AF_INET6:
181             break;
182         default:
183             debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
184             freeaddrinfo(addrinfo);
185             return 0;
186         }
187         conf->prefixlen = plen;
188     } else
189         conf->prefixlen = 255;
190
191     if (conf->addrinfo)
192         freeaddrinfo(conf->addrinfo);
193     conf->addrinfo = addrinfo;
194     return 1;
195 }         
196
197 int connecttoserver(struct addrinfo *addrinfo) {
198     int s;
199     struct addrinfo *res;
200
201     s = -1;
202     for (res = addrinfo; res; res = res->ai_next) {
203         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
204         if (s < 0) {
205             debug(DBG_WARN, "connecttoserver: socket failed");
206             continue;
207         }
208         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
209             break;
210         debug(DBG_WARN, "connecttoserver: connect failed");
211         close(s);
212         s = -1;
213     }
214     return s;
215 }         
216
217 int bindtoaddr(struct addrinfo *addrinfo) {
218     int s, on = 1;
219     struct addrinfo *res;
220     
221     for (res = addrinfo; res; res = res->ai_next) {
222         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
223         if (s < 0) {
224             debug(DBG_WARN, "bindtoaddr: socket failed");
225             continue;
226         }
227         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
228         if (!bind(s, res->ai_addr, res->ai_addrlen))
229             return s;
230         debug(DBG_WARN, "bindtoaddr: bind failed");
231         close(s);
232     }
233     return -1;
234 }         
235
236 /* returns 1 if the len first bits are equal, else 0 */
237 int prefixmatch(void *a1, void *a2, uint8_t len) {
238     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
239     int r, l = len / 8;
240     if (l && memcmp(a1, a2, l))
241         return 0;
242     r = len % 8;
243     if (!r)
244         return 1;
245     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
246 }
247
248 /* returns the config with matching address, or NULL */
249 /* if conf argument is not NULL, we only check that one */
250 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
251     struct sockaddr_in6 *sa6 = NULL;
252     struct in_addr *a4 = NULL;
253     struct addrinfo *res;
254     struct list_node *entry;
255     
256     if (addr->sa_family == AF_INET6) {
257         sa6 = (struct sockaddr_in6 *)addr;
258         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
259             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
260             sa6 = NULL;
261         }
262     } else
263         a4 = &((struct sockaddr_in *)addr)->sin_addr;
264
265     if (conf) {
266         if (conf->type == type) {
267             if (conf->prefixlen == 255) {
268                 for (res = conf->addrinfo; res; res = res->ai_next)
269                     if ((a4 && res->ai_family == AF_INET &&
270                          !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
271                         (sa6 && res->ai_family == AF_INET6 &&
272                          !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
273                         return conf;
274             } else {
275                 res = conf->addrinfo;
276                 if (res &&
277                     ((a4 && res->ai_family == AF_INET &&
278                       prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
279                      (sa6 && res->ai_family == AF_INET6 &&
280                       prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
281                     return conf;
282             }
283         }
284         return NULL;
285     }
286
287     for (entry = list_first(confs); entry; entry = list_next(entry)) {  
288         conf = (struct clsrvconf *)entry->data;
289         if (conf->type == type) {
290             if (conf->prefixlen == 255) {
291                 for (res = conf->addrinfo; res; res = res->ai_next)
292                     if ((a4 && res->ai_family == AF_INET &&
293                          !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
294                         (sa6 && res->ai_family == AF_INET6 &&
295                          !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
296                         return conf;
297             } else {
298                 res = conf->addrinfo;
299                 if (res &&
300                     ((a4 && res->ai_family == AF_INET &&
301                       prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
302                      (sa6 && res->ai_family == AF_INET6 &&
303                       prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
304                     return conf;
305             }
306         }
307     }    
308     return NULL;
309 }
310
311 struct replyq *newreplyq() {
312     struct replyq *replyq;
313     
314     replyq = malloc(sizeof(struct replyq));
315     if (!replyq)
316         debugx(1, DBG_ERR, "malloc failed");
317     replyq->replies = list_create();
318     if (!replyq->replies)
319         debugx(1, DBG_ERR, "malloc failed");
320     pthread_mutex_init(&replyq->mutex, NULL);
321     pthread_cond_init(&replyq->cond, NULL);
322     return replyq;
323 }
324
325 struct client *addclient(struct clsrvconf *conf) {
326     struct client *new = malloc(sizeof(struct client));
327     
328     if (!new) {
329         debug(DBG_ERR, "malloc failed");
330         return NULL;
331     }
332     if (!conf->clients) {
333         conf->clients = list_create();
334         if (!conf->clients) {
335             debug(DBG_ERR, "malloc failed");
336             return NULL;
337         }
338     }
339     
340     memset(new, 0, sizeof(struct client));
341     new->conf = conf;
342     new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
343
344     list_push(conf->clients, new);
345     return new;
346 }
347
348 void removeclient(struct client *client) {
349     if (!client || !client->conf->clients)
350         return;
351
352     list_removedata(client->conf->clients, client);
353     free(client);
354 }
355
356 void addserver(struct clsrvconf *conf) {
357     if (conf->servers)
358         debugx(1, DBG_ERR, "currently works with just one server per conf");
359     
360     conf->servers = malloc(sizeof(struct server));
361     if (!conf->servers)
362         debugx(1, DBG_ERR, "malloc failed");
363     memset(conf->servers, 0, sizeof(struct server));
364     conf->servers->conf = conf;
365
366     conf->servers->sock = -1;
367     pthread_mutex_init(&conf->servers->lock, NULL);
368     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
369     if (!conf->servers->requests)
370         debugx(1, DBG_ERR, "malloc failed");
371     conf->servers->newrq = 0;
372     pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
373     pthread_cond_init(&conf->servers->newrq_cond, NULL);
374 }
375
376 /* exactly one of client and server must be non-NULL */
377 /* should probably take peer list (client(s) or server(s)) as argument instead */
378 /* if *peer == NULL we return who we received from, else require it to be from peer */
379 /* return from in sa if not NULL */
380 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
381     int cnt, len;
382     unsigned char buf[65536], *rad;
383     struct sockaddr_storage from;
384     socklen_t fromlen = sizeof(from);
385     struct clsrvconf *p;
386     struct list_node *node;
387     
388     for (;;) {
389         cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
390         if (cnt == -1) {
391             debug(DBG_WARN, "radudpget: recv failed");
392             continue;
393         }
394         debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
395
396         if (cnt < 20) {
397             debug(DBG_WARN, "radudpget: packet too small");
398             continue;
399         }
400     
401         len = RADLEN(buf);
402         if (len < 20) {
403             debug(DBG_WARN, "radudpget: length too small");
404             continue;
405         }
406
407         if (cnt < len) {
408             debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
409             continue;
410         }
411         if (cnt > len)
412             debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
413
414         if (client)
415             if (*client)
416                 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
417             else
418                 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
419         else
420             if (*server)
421                 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
422             else
423                 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
424
425         if (!p) {
426             debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
427             continue;
428         }
429         
430         rad = malloc(len);
431         if (!rad) {
432             debug(DBG_ERR, "radudpget: malloc failed");
433             continue;
434         }
435         
436         if (client && !*client) {
437             node = list_first(p->clients);
438             *client = node ? (struct client *)node->data : addclient(p);
439             if (!*client) {
440                 free(rad);
441                 continue;
442             }
443         } else if (server && !*server)
444             *server = p->servers;
445         
446         break;
447     }
448     memcpy(rad, buf, len);
449     if (sa)
450         *sa = from;
451     return rad;
452 }
453
454 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
455     int loc, i, l, n, r = 0;
456     char *v;
457     X509_EXTENSION *ex;
458     STACK_OF(GENERAL_NAME) *alt;
459     GENERAL_NAME *gn;
460     
461     debug(DBG_DBG, "subjectaltnameaddr");
462     
463     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
464     if (loc < 0)
465         return r;
466     
467     ex = X509_get_ext(cert, loc);
468     alt = X509V3_EXT_d2i(ex);
469     if (!alt)
470         return r;
471     
472     n = sk_GENERAL_NAME_num(alt);
473     for (i = 0; i < n; i++) {
474         gn = sk_GENERAL_NAME_value(alt, i);
475         if (gn->type != GEN_IPADD)
476             continue;
477         r = -1;
478         v = (char *)ASN1_STRING_data(gn->d.ia5);
479         l = ASN1_STRING_length(gn->d.ia5);
480         if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
481             && !memcmp(v, &addr, l)) {
482             r = 1;
483             break;
484         }
485     }
486     GENERAL_NAMES_free(alt);
487     return r;
488 }
489
490 int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
491     int loc, i, l, n, r = 0;
492     char *s, *v;
493     X509_EXTENSION *ex;
494     STACK_OF(GENERAL_NAME) *alt;
495     GENERAL_NAME *gn;
496     
497     debug(DBG_DBG, "subjectaltnameregexp");
498     
499     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
500     if (loc < 0)
501         return r;
502     
503     ex = X509_get_ext(cert, loc);
504     alt = X509V3_EXT_d2i(ex);
505     if (!alt)
506         return r;
507     
508     n = sk_GENERAL_NAME_num(alt);
509     for (i = 0; i < n; i++) {
510         gn = sk_GENERAL_NAME_value(alt, i);
511         if (gn->type != type)
512             continue;
513         r = -1;
514         v = (char *)ASN1_STRING_data(gn->d.ia5);
515         l = ASN1_STRING_length(gn->d.ia5);
516         if (l <= 0)
517             continue;
518 #ifdef DEBUG
519         printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
520 #endif  
521         if (exact) {
522             if (memcmp(v, exact, l))
523                 continue;
524         } else {
525             s = stringcopy((char *)v, l);
526             if (!s) {
527                 debug(DBG_ERR, "malloc failed");
528                 continue;
529             }
530             if (regexec(regex, s, 0, NULL, 0)) {
531                 free(s);
532                 continue;
533             }
534             free(s);
535         }
536         r = 1;
537         break;
538     }
539     GENERAL_NAMES_free(alt);
540     return r;
541 }
542
543 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
544     int l, loc, r;
545     X509 *cert;
546     X509_NAME *nm;
547     X509_NAME_ENTRY *e;
548     ASN1_STRING *s;
549     char *v;
550     uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
551     unsigned long error;
552     struct in6_addr addr;
553     
554     if (SSL_get_verify_result(ssl) != X509_V_OK) {
555         debug(DBG_ERR, "tlsverifycert: basic validation failed");
556         while ((error = ERR_get_error()))
557             debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
558         return 0;
559     }
560
561     cert = SSL_get_peer_certificate(ssl);
562     if (!cert) {
563         debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
564         return 0;
565     }
566     
567     if (inet_pton(AF_INET, conf->host, &addr))
568         type = AF_INET;
569     else if (inet_pton(AF_INET6, conf->host, &addr))
570         type = AF_INET6;
571
572     r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
573     if (r) {
574         if (r < 0) {
575             X509_free(cert);
576             debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
577             return 0;
578         }
579         debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
580     } else {
581         nm = X509_get_subject_name(cert);
582         loc = -1;
583         for (;;) {
584             loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
585             if (loc == -1)
586                 break;
587             e = X509_NAME_get_entry(nm, loc);
588             s = X509_NAME_ENTRY_get_data(e);
589             v = (char *) ASN1_STRING_data(s);
590             l = ASN1_STRING_length(s);
591             if (l < 0)
592                 continue;
593 #ifdef DEBUG
594             printfchars(NULL, "cn", NULL, v, l);
595 #endif      
596             if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
597                 r = 1;
598                 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
599                 break;
600             }
601         }
602         if (!r) {
603             X509_free(cert);
604             debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
605             return 0;
606         }
607     }
608     if (conf->certuriregex) {
609         r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
610         if (r < 1) {
611             debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
612             X509_free(cert);
613             return 0;
614         }
615         debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
616     }
617     X509_free(cert);
618     return 1;
619 }
620
621 void tlsconnect(struct server *server, struct timeval *when, char *text) {
622     struct timeval now;
623     time_t elapsed;
624
625     debug(DBG_DBG, "tlsconnect called from %s", text);
626     pthread_mutex_lock(&server->lock);
627     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
628         /* already reconnected, nothing to do */
629         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
630         pthread_mutex_unlock(&server->lock);
631         return;
632     }
633
634     debug(DBG_DBG, "tlsconnect %s", text);
635
636     for (;;) {
637         gettimeofday(&now, NULL);
638         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
639         if (server->connectionok) {
640             server->connectionok = 0;
641             sleep(10);
642         } else if (elapsed < 5)
643             sleep(10);
644         else if (elapsed < 300) {
645             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
646             sleep(elapsed);
647         } else if (elapsed < 100000) {
648             debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
649             sleep(600);
650         } else
651             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
652         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
653         if (server->sock >= 0)
654             close(server->sock);
655         if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
656             debug(DBG_ERR, "tlsconnect: connecttoserver failed");
657             continue;
658         }
659         
660         SSL_free(server->ssl);
661         server->ssl = SSL_new(server->conf->ssl_ctx);
662         SSL_set_fd(server->ssl, server->sock);
663         if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
664             break;
665     }
666     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
667     gettimeofday(&server->lastconnecttry, NULL);
668     pthread_mutex_unlock(&server->lock);
669 }
670
671 unsigned char *radtlsget(SSL *ssl) {
672     int cnt, total, len;
673     unsigned char buf[4], *rad;
674
675     for (;;) {
676         for (total = 0; total < 4; total += cnt) {
677             cnt = SSL_read(ssl, buf + total, 4 - total);
678             if (cnt <= 0) {
679                 debug(DBG_ERR, "radtlsget: connection lost");
680                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
681                     /* remote end sent close_notify, send one back */
682                     SSL_shutdown(ssl);
683                 }
684                 return NULL;
685             }
686         }
687
688         len = RADLEN(buf);
689         rad = malloc(len);
690         if (!rad) {
691             debug(DBG_ERR, "radtlsget: malloc failed");
692             continue;
693         }
694         memcpy(rad, buf, 4);
695
696         for (; total < len; total += cnt) {
697             cnt = SSL_read(ssl, rad + total, len - total);
698             if (cnt <= 0) {
699                 debug(DBG_ERR, "radtlsget: connection lost");
700                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
701                     /* remote end sent close_notify, send one back */
702                     SSL_shutdown(ssl);
703                 }
704                 free(rad);
705                 return NULL;
706             }
707         }
708     
709         if (total >= 20)
710             break;
711         
712         free(rad);
713         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
714     }
715     
716     debug(DBG_DBG, "radtlsget: got %d bytes", total);
717     return rad;
718 }
719
720 int clientradput(struct server *server, unsigned char *rad) {
721     int cnt;
722     size_t len;
723     unsigned long error;
724     struct timeval lastconnecttry;
725     
726     len = RADLEN(rad);
727     if (server->conf->type == 'U') {
728         if (send(server->sock, rad, len, 0) >= 0) {
729             debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->conf->host, server->conf->port);
730             return 1;
731         }
732         debug(DBG_WARN, "clientradput: send failed");
733         return 0;
734     }
735
736     lastconnecttry = server->lastconnecttry;
737     while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
738         while ((error = ERR_get_error()))
739             debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
740         tlsconnect(server, &lastconnecttry, "clientradput");
741         lastconnecttry = server->lastconnecttry;
742     }
743
744     server->connectionok = 1;
745     debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
746            cnt, len, server->conf->host);
747     return 1;
748 }
749
750 int radsign(unsigned char *rad, unsigned char *sec) {
751     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
752     static unsigned char first = 1;
753     static EVP_MD_CTX mdctx;
754     unsigned int md_len;
755     int result;
756     
757     pthread_mutex_lock(&lock);
758     if (first) {
759         EVP_MD_CTX_init(&mdctx);
760         first = 0;
761     }
762
763     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
764         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
765         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
766         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
767         md_len == 16);
768     pthread_mutex_unlock(&lock);
769     return result;
770 }
771
772 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
773     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
774     static unsigned char first = 1;
775     static EVP_MD_CTX mdctx;
776     unsigned char hash[EVP_MAX_MD_SIZE];
777     unsigned int len;
778     int result;
779     
780     pthread_mutex_lock(&lock);
781     if (first) {
782         EVP_MD_CTX_init(&mdctx);
783         first = 0;
784     }
785
786     len = RADLEN(rad);
787     
788     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
789               EVP_DigestUpdate(&mdctx, rad, 4) &&
790               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
791               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
792               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
793               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
794               len == 16 &&
795               !memcmp(hash, rad + 4, 16));
796     pthread_mutex_unlock(&lock);
797     return result;
798 }
799               
800 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
801     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
802     static unsigned char first = 1;
803     static HMAC_CTX hmacctx;
804     unsigned int md_len;
805     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
806     
807     pthread_mutex_lock(&lock);
808     if (first) {
809         HMAC_CTX_init(&hmacctx);
810         first = 0;
811     }
812
813     memcpy(auth, authattr, 16);
814     memset(authattr, 0, 16);
815     md_len = 0;
816     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
817     HMAC_Update(&hmacctx, rad, RADLEN(rad));
818     HMAC_Final(&hmacctx, hash, &md_len);
819     memcpy(authattr, auth, 16);
820     if (md_len != 16) {
821         debug(DBG_WARN, "message auth computation failed");
822         pthread_mutex_unlock(&lock);
823         return 0;
824     }
825
826     if (memcmp(auth, hash, 16)) {
827         debug(DBG_WARN, "message authenticator, wrong value");
828         pthread_mutex_unlock(&lock);
829         return 0;
830     }   
831         
832     pthread_mutex_unlock(&lock);
833     return 1;
834 }
835
836 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
837     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
838     static unsigned char first = 1;
839     static HMAC_CTX hmacctx;
840     unsigned int md_len;
841
842     if (!authattrval)
843         return 1;
844     
845     pthread_mutex_lock(&lock);
846     if (first) {
847         HMAC_CTX_init(&hmacctx);
848         first = 0;
849     }
850
851     memset(authattrval, 0, 16);
852     md_len = 0;
853     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
854     HMAC_Update(&hmacctx, rad, RADLEN(rad));
855     HMAC_Final(&hmacctx, authattrval, &md_len);
856     if (md_len != 16) {
857         debug(DBG_WARN, "message auth computation failed");
858         pthread_mutex_unlock(&lock);
859         return 0;
860     }
861
862     pthread_mutex_unlock(&lock);
863     return 1;
864 }
865
866 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
867     while (length > 1) {
868         if (ATTRTYPE(attrs) == type)
869             return attrs;
870         length -= ATTRLEN(attrs);
871         attrs += ATTRLEN(attrs);
872     }
873     return NULL;
874 }
875
876 void freerqdata(struct request *rq) {
877     if (rq->origusername)
878         free(rq->origusername);
879     if (rq->buf)
880         free(rq->buf);
881 }
882
883 void sendrq(struct server *to, struct request *rq) {
884     int i;
885     uint8_t *attr;
886
887     pthread_mutex_lock(&to->newrq_mutex);
888     /* might simplify if only try nextid, might be ok */
889     for (i = to->nextid; i < MAX_REQUESTS; i++)
890         if (!to->requests[i].buf)
891             break;
892     if (i == MAX_REQUESTS) {
893         for (i = 0; i < to->nextid; i++)
894             if (!to->requests[i].buf)
895                 break;
896         if (i == to->nextid) {
897             debug(DBG_WARN, "No room in queue, dropping request");
898             freerqdata(rq);
899             pthread_mutex_unlock(&to->newrq_mutex);
900             return;
901         }
902     }
903     
904     rq->buf[1] = (char)i;
905
906     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
907     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
908         freerqdata(rq);
909         pthread_mutex_unlock(&to->newrq_mutex);
910         return;
911     }
912
913     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
914     to->requests[i] = *rq;
915     to->nextid = i + 1;
916
917     if (!to->newrq) {
918         to->newrq = 1;
919         debug(DBG_DBG, "signalling client writer");
920         pthread_cond_signal(&to->newrq_cond);
921     }
922     pthread_mutex_unlock(&to->newrq_mutex);
923 }
924
925 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
926     struct reply *reply;
927     uint8_t first;
928     
929     if (!radsign(buf, (unsigned char *)to->conf->secret)) {
930         free(buf);
931         debug(DBG_WARN, "sendreply: failed to sign message");
932         return;
933     }
934
935     reply = malloc(sizeof(struct reply));
936     if (!reply) {
937         free(buf);
938         debug(DBG_ERR, "sendreply: malloc failed");
939         return;
940     }
941     memset(reply, 0, sizeof(struct reply));
942     reply->buf = buf;
943     if (tosa)
944         reply->tosa = *tosa;
945     
946     pthread_mutex_lock(&to->replyq->mutex);
947
948     first = list_first(to->replyq->replies) == NULL;
949     
950     if (!list_push(to->replyq->replies, reply)) {
951         pthread_mutex_unlock(&to->replyq->mutex);
952         free(reply);
953         free(buf);
954         debug(DBG_ERR, "sendreply: malloc failed");
955         return;
956     }
957     
958     if (first) {
959         debug(DBG_DBG, "signalling server writer");
960         pthread_cond_signal(&to->replyq->cond);
961     }
962     pthread_mutex_unlock(&to->replyq->mutex);
963 }
964
965 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
966     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
967     static unsigned char first = 1;
968     static EVP_MD_CTX mdctx;
969     unsigned char hash[EVP_MAX_MD_SIZE], *input;
970     unsigned int md_len;
971     uint8_t i, offset = 0, out[128];
972     
973     pthread_mutex_lock(&lock);
974     if (first) {
975         EVP_MD_CTX_init(&mdctx);
976         first = 0;
977     }
978
979     input = auth;
980     for (;;) {
981         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
982             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
983             !EVP_DigestUpdate(&mdctx, input, 16) ||
984             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
985             md_len != 16) {
986             pthread_mutex_unlock(&lock);
987             return 0;
988         }
989         for (i = 0; i < 16; i++)
990             out[offset + i] = hash[i] ^ in[offset + i];
991         input = out + offset - 16;
992         offset += 16;
993         if (offset == len)
994             break;
995     }
996     memcpy(in, out, len);
997     pthread_mutex_unlock(&lock);
998     return 1;
999 }
1000
1001 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1002     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1003     static unsigned char first = 1;
1004     static EVP_MD_CTX mdctx;
1005     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1006     unsigned int md_len;
1007     uint8_t i, offset = 0, out[128];
1008     
1009     pthread_mutex_lock(&lock);
1010     if (first) {
1011         EVP_MD_CTX_init(&mdctx);
1012         first = 0;
1013     }
1014
1015     input = auth;
1016     for (;;) {
1017         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1018             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1019             !EVP_DigestUpdate(&mdctx, input, 16) ||
1020             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1021             md_len != 16) {
1022             pthread_mutex_unlock(&lock);
1023             return 0;
1024         }
1025         for (i = 0; i < 16; i++)
1026             out[offset + i] = hash[i] ^ in[offset + i];
1027         input = in + offset;
1028         offset += 16;
1029         if (offset == len)
1030             break;
1031     }
1032     memcpy(in, out, len);
1033     pthread_mutex_unlock(&lock);
1034     return 1;
1035 }
1036
1037 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1038     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1039     static unsigned char first = 1;
1040     static EVP_MD_CTX mdctx;
1041     unsigned char hash[EVP_MAX_MD_SIZE];
1042     unsigned int md_len;
1043     uint8_t i, offset;
1044     
1045     pthread_mutex_lock(&lock);
1046     if (first) {
1047         EVP_MD_CTX_init(&mdctx);
1048         first = 0;
1049     }
1050
1051 #if 0
1052     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1053     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1054     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1055 #endif
1056     
1057     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1058         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1059         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1060         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1061         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1062         pthread_mutex_unlock(&lock);
1063         return 0;
1064     }
1065
1066 #if 0    
1067     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1068 #endif
1069     
1070     for (i = 0; i < 16; i++)
1071         text[i] ^= hash[i];
1072     
1073     for (offset = 16; offset < len; offset += 16) {
1074 #if 0   
1075         printf("text + offset - 16 c(%d): ", offset / 16);
1076         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1077 #endif
1078         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1079             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1080             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1081             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1082             md_len != 16) {
1083             pthread_mutex_unlock(&lock);
1084             return 0;
1085         }
1086 #if 0
1087         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1088 #endif    
1089         
1090         for (i = 0; i < 16; i++)
1091             text[offset + i] ^= hash[i];
1092     }
1093     
1094 #if 0
1095     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1096 #endif
1097
1098     pthread_mutex_unlock(&lock);
1099     return 1;
1100 }
1101
1102 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1103     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1104     static unsigned char first = 1;
1105     static EVP_MD_CTX mdctx;
1106     unsigned char hash[EVP_MAX_MD_SIZE];
1107     unsigned int md_len;
1108     uint8_t i, offset;
1109     char plain[255];
1110     
1111     pthread_mutex_lock(&lock);
1112     if (first) {
1113         EVP_MD_CTX_init(&mdctx);
1114         first = 0;
1115     }
1116
1117 #if 0
1118     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1119     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1120     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1121 #endif
1122     
1123     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1124         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1125         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1126         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1127         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1128         pthread_mutex_unlock(&lock);
1129         return 0;
1130     }
1131
1132 #if 0    
1133     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1134 #endif
1135     
1136     for (i = 0; i < 16; i++)
1137         plain[i] = text[i] ^ hash[i];
1138     
1139     for (offset = 16; offset < len; offset += 16) {
1140 #if 0   
1141         printf("text + offset - 16 c(%d): ", offset / 16);
1142         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1143 #endif
1144         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1145             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1146             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1147             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1148             md_len != 16) {
1149             pthread_mutex_unlock(&lock);
1150             return 0;
1151         }
1152 #if 0
1153         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1154 #endif    
1155
1156         for (i = 0; i < 16; i++)
1157             plain[offset + i] = text[offset + i] ^ hash[i];
1158     }
1159
1160     memcpy(text, plain, len);
1161 #if 0
1162     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1163 #endif
1164
1165     pthread_mutex_unlock(&lock);
1166     return 1;
1167 }
1168
1169 struct realm *id2realm(char *id, uint8_t len) {
1170     struct list_node *entry;
1171     struct realm *realm;
1172     
1173     for (entry = list_first(realms); entry; entry = list_next(entry)) {
1174         realm = (struct realm *)entry->data;
1175         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1176             debug(DBG_DBG, "found matching realm: %s", realm->name);
1177             return realm;
1178         }
1179     }
1180     return NULL;
1181 }
1182
1183 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1184     int i;
1185     
1186     pthread_mutex_lock(&to->newrq_mutex);
1187     for (i = 0; i < MAX_REQUESTS; i++)
1188         if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1189             break;
1190     pthread_mutex_unlock(&to->newrq_mutex);
1191     
1192     return i < MAX_REQUESTS;
1193 }
1194
1195 int attrvalidate(unsigned char *attrs, int length) {
1196     while (length > 1) {
1197         if (ATTRLEN(attrs) < 2) {
1198             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1199             return 0;
1200         }
1201         length -= ATTRLEN(attrs);
1202         if (length < 0) {
1203             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1204             return 0;
1205         }
1206         attrs += ATTRLEN(attrs);
1207     }
1208     if (length)
1209         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1210     return 1;
1211 }
1212
1213 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1214     if (len < 16 || len > 128 || len % 16) {
1215         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1216         return 0;
1217     }
1218         
1219     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1220         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1221         return 0;
1222     }
1223 #ifdef DEBUG
1224     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1225 #endif  
1226     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1227         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1228         return 0;
1229     }
1230     return 1;
1231 }
1232
1233 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1234     if (len < 18)
1235         return 0;
1236     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1237         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1238         return 0;
1239     }
1240     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1241         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1242         return 0;
1243     }
1244     return 1;
1245 }
1246
1247 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1248            char *oldsecret, char *newsecret) {
1249     unsigned char *attr;
1250     
1251     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1252         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1253         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1254             return 0;
1255     }
1256     return 1;
1257 }
1258
1259 /* returns a pointer to the resized attribute value */
1260 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1261     uint8_t *attrs, *attr, vallen;
1262     uint16_t len;
1263     unsigned char *new;
1264     
1265     len = RADLEN(*buf) - 20;
1266     attrs = *buf + 20;
1267
1268     attr = attrget(attrs, len, type);
1269     if (!attr)
1270         return NULL;
1271     
1272     vallen = ATTRVALLEN(attr);
1273     if (vallen == newvallen)
1274         return attr + 2;
1275
1276     len += newvallen - vallen;
1277     if (newvallen > vallen) {
1278         new = realloc(*buf, len);
1279         if (!new) {
1280             debug(DBG_ERR, "resizeattr: malloc failed");
1281             return NULL;
1282         }
1283         if (new != *buf) {
1284             attr += new - *buf;
1285             attrs = new + 20;
1286             *buf = new;
1287         }
1288     }
1289     memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1290     attr[1] = newvallen + 2;
1291     ((uint16_t *)*buf)[1] = htons(len + 20);
1292     return attr + 2;
1293 }
1294                 
1295 int rewriteusername(struct request *rq, char *in) {
1296     size_t nmatch = 10, reslen = 0, start = 0;
1297     regmatch_t pmatch[10], *pfield;
1298     int i;
1299     unsigned char *result;
1300     char *out = rq->from->conf->rewriteattrreplacement;
1301     
1302     if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1303         debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1304         return 1;
1305     }
1306     
1307     rq->origusername = stringcopy(in, 0);
1308     if (!rq->origusername)
1309         return 0;
1310     
1311     for (i = start; out[i]; i++) {
1312         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1313             pfield = &pmatch[out[i + 1] - '0'];
1314             if (pfield->rm_so >= 0) {
1315                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1316                 start = i + 2;
1317             }
1318             i++;
1319         }
1320     }
1321     reslen += i - start;
1322
1323     result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1324     if (!result)
1325         return 0;
1326     
1327     start = 0;
1328     reslen = 0;
1329     for (i = start; out[i]; i++) {
1330         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1331             pfield = &pmatch[out[i + 1] - '0'];
1332             if (pfield->rm_so >= 0) {
1333                 memcpy(result + reslen, out + start, i - start);
1334                 reslen += i - start;
1335                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1336                 reslen += pfield->rm_eo - pfield->rm_so;
1337                 start = i + 2;
1338             }
1339             i++;
1340         }
1341     }
1342
1343     memcpy(result + reslen, out + start, i - start);
1344     reslen += i - start;
1345     memcpy(in, result, reslen);
1346     in[reslen] = '\0';
1347     return 1;
1348 }
1349                  
1350 void acclog(unsigned char *attrs, int length, char *host) {
1351     unsigned char *attr;
1352     char username[256];
1353     
1354     attr = attrget(attrs, length, RAD_Attr_User_Name);
1355     if (!attr) {
1356         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1357         return;
1358     }
1359     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1360     username[ATTRVALLEN(attr)] = '\0';
1361     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1362 }
1363         
1364 void respondaccounting(struct request *rq) {
1365     unsigned char *resp;
1366
1367     resp = malloc(20);
1368     if (!resp) {
1369         debug(DBG_ERR, "respondstatusserver: malloc failed");
1370         return;
1371     }
1372     memcpy(resp, rq->buf, 20);
1373     resp[0] = RAD_Accounting_Response;
1374     resp[2] = 0;
1375     resp[3] = 20;
1376     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1377     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1378 }
1379
1380 void respondstatusserver(struct request *rq) {
1381     unsigned char *resp;
1382
1383     resp = malloc(20);
1384     if (!resp) {
1385         debug(DBG_ERR, "respondstatusserver: malloc failed");
1386         return;
1387     }
1388     memcpy(resp, rq->buf, 20);
1389     resp[0] = RAD_Access_Accept;
1390     resp[2] = 0;
1391     resp[3] = 20;
1392     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1393     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1394 }
1395
1396 void respondreject(struct request *rq, char *message) {
1397     unsigned char *resp;
1398     int len = 20;
1399
1400     if (message && *message)
1401         len += 2 + strlen(message);
1402     
1403     resp = malloc(len);
1404     if (!resp) {
1405         debug(DBG_ERR, "respondreject: malloc failed");
1406         return;
1407     }
1408     memcpy(resp, rq->buf, 20);
1409     resp[0] = RAD_Access_Reject;
1410     *(uint16_t *)(resp + 2) = htons(len);
1411     if (message && *message) {
1412         resp[20] = RAD_Attr_Reply_Message;
1413         resp[21] = len - 20;
1414         memcpy(resp + 22, message, len - 22);
1415     }
1416     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1417 }
1418
1419 struct server *realm2server(struct realm *realm) {
1420     struct list_node *entry;
1421     struct server *server, *best = NULL;
1422     
1423     for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1424         server = ((struct clsrvconf *)entry->data)->servers;
1425         if (!server->connectionok)
1426             continue;
1427         if (!server->loststatsrv)
1428             return server;
1429         if (!best) {
1430             best = server;
1431             continue;
1432         }
1433         if (server->loststatsrv < best->loststatsrv)
1434             best = server;
1435     }
1436     return best;
1437 }
1438
1439 void radsrv(struct request *rq) {
1440     uint8_t code, id, *auth, *attrs, *attr;
1441     uint16_t len;
1442     struct server *to = NULL;
1443     char username[256];
1444     unsigned char newauth[16];
1445     struct realm *realm = NULL;
1446     
1447     code = *(uint8_t *)rq->buf;
1448     id = *(uint8_t *)(rq->buf + 1);
1449     len = RADLEN(rq->buf);
1450     auth = (uint8_t *)(rq->buf + 4);
1451
1452     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1453     
1454     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1455         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1456         freerqdata(rq);
1457         return;
1458     }
1459
1460     len -= 20;
1461     attrs = rq->buf + 20;
1462
1463     if (!attrvalidate(attrs, len)) {
1464         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1465         freerqdata(rq);
1466         return;
1467     }
1468
1469     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1470     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1471         debug(DBG_WARN, "radsrv: message authentication failed");
1472         freerqdata(rq);
1473         return;
1474     }
1475
1476     if (code != RAD_Access_Request) {
1477         switch (code) {
1478         case RAD_Accounting_Request:
1479             acclog(attrs, len, rq->from->conf->host);
1480             respondaccounting(rq);
1481             break;
1482         case RAD_Status_Server:
1483             respondstatusserver(rq);
1484             break;
1485         }
1486         freerqdata(rq);
1487         return;
1488     }
1489
1490     /* code == RAD_Access_Request */
1491     attr = attrget(attrs, len, RAD_Attr_User_Name);
1492     if (!attr) {
1493         debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1494         freerqdata(rq);
1495         return;
1496     }
1497     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1498     username[ATTRVALLEN(attr)] = '\0';
1499
1500     if (rq->from->conf->rewriteattrregex) {
1501         if (!rewriteusername(rq, username)) {
1502             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1503             freerqdata(rq);
1504             return;
1505         }
1506         len = RADLEN(rq->buf) - 20;
1507         auth = (uint8_t *)(rq->buf + 4);
1508         attrs = rq->buf + 20;
1509     }
1510
1511     if (rq->origusername)
1512         debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1513     else
1514         debug(DBG_DBG, "Access Request with username: %s", username);
1515         
1516     realm = id2realm(username, strlen(username));
1517     if (!realm) {
1518         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1519         freerqdata(rq);
1520         return;
1521     }
1522         
1523     to = realm2server(realm);
1524     if (to && rqinqueue(to, rq->from, id)) {
1525         debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1526         freerqdata(rq);
1527         return;
1528     }
1529
1530     if (!to) {
1531         if (realm->message) {
1532             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1533             respondreject(rq, realm->message);
1534         }
1535         freerqdata(rq);
1536         return;
1537     }
1538     
1539     if (!RAND_bytes(newauth, 16)) {
1540         debug(DBG_WARN, "radsrv: failed to generate random auth");
1541         freerqdata(rq);
1542         return;
1543     }
1544
1545 #ifdef DEBUG
1546     printfchars(NULL, "auth", "%02x ", auth, 16);
1547 #endif
1548
1549     attr = attrget(attrs, len, RAD_Attr_User_Password);
1550     if (attr) {
1551         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1552         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1553             freerqdata(rq);
1554             return;
1555         }
1556     }
1557     
1558     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1559     if (attr) {
1560         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1561         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1562             freerqdata(rq);
1563             return;
1564         }
1565     }
1566
1567     rq->origid = id;
1568     memcpy(rq->origauth, auth, 16);
1569     memcpy(auth, newauth, 16);
1570     sendrq(to, rq);
1571 }
1572
1573 int replyh(struct server *server, unsigned char *buf) {
1574     struct client *from;
1575     struct request *rq;
1576     int i, len, sublen;
1577     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1578     struct sockaddr_storage fromsa;
1579     char tmp[256];
1580     
1581     server->connectionok = 1;
1582     server->loststatsrv = 0;
1583         
1584     i = buf[1]; /* i is the id */
1585
1586     switch (*buf) {
1587     case RAD_Access_Accept:
1588         debug(DBG_DBG, "got Access Accept with id %d", i);
1589         break;
1590     case RAD_Access_Reject:
1591         debug(DBG_DBG, "got Access Reject with id %d", i);
1592         break;
1593     case RAD_Access_Challenge:
1594         debug(DBG_DBG, "got Access Challenge with id %d", i);
1595         break;
1596     default:
1597         debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1598         return 0;
1599     }
1600
1601     rq = server->requests + i;
1602         
1603     pthread_mutex_lock(&server->newrq_mutex);
1604     if (!rq->buf || !rq->tries) {
1605         pthread_mutex_unlock(&server->newrq_mutex);
1606         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1607         return 0;
1608     }
1609
1610     if (rq->received) {
1611         pthread_mutex_unlock(&server->newrq_mutex);
1612         debug(DBG_INFO, "replyh: already received, ignoring reply");
1613         return 0;
1614     }
1615         
1616     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1617         pthread_mutex_unlock(&server->newrq_mutex);
1618         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1619         return 0;
1620     }
1621         
1622     from = rq->from;
1623     len = RADLEN(buf) - 20;
1624     attrs = buf + 20;
1625
1626     if (!attrvalidate(attrs, len)) {
1627         pthread_mutex_unlock(&server->newrq_mutex);
1628         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1629         return 0;
1630     }
1631         
1632     /* Message Authenticator */
1633     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1634     if (messageauth) {
1635         if (ATTRVALLEN(messageauth) != 16) {
1636             pthread_mutex_unlock(&server->newrq_mutex);
1637             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1638             return 0;
1639         }
1640         memcpy(tmp, buf + 4, 16);
1641         memcpy(buf + 4, rq->buf + 4, 16);
1642         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1643             pthread_mutex_unlock(&server->newrq_mutex);
1644             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1645             return 0;
1646         }
1647         memcpy(buf + 4, tmp, 16);
1648         debug(DBG_DBG, "replyh: message auth ok");
1649     }
1650         
1651     if (*rq->buf == RAD_Status_Server) {
1652         rq->received = 1;
1653         pthread_mutex_unlock(&server->newrq_mutex);
1654         debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1655         return 0;
1656     }
1657
1658     /* MS MPPE */
1659     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1660         if (ATTRVALLEN(attr) <= 4)
1661             break;
1662             
1663         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
1664             continue;
1665             
1666         sublen = ATTRVALLEN(attr) - 4;
1667         subattrs = ATTRVAL(attr) + 4;  
1668         if (!attrvalidate(subattrs, sublen) ||
1669             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1670                     rq, server->conf->secret, from->conf->secret) ||
1671             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1672                     rq, server->conf->secret, from->conf->secret))
1673             break;
1674     }
1675     if (attr) {
1676         pthread_mutex_unlock(&server->newrq_mutex);
1677         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1678         return 0;
1679     }
1680         
1681     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1682         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1683         /* we know the attribute exists */
1684         memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1685         tmp[ATTRVALLEN(attr)] = '\0';
1686         switch (*buf) {
1687         case RAD_Access_Accept:
1688             if (rq->origusername)
1689                 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1690             else
1691                 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1692             break;
1693         case RAD_Access_Reject:
1694             if (rq->origusername)
1695                 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1696             else
1697                 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1698             break;
1699         }
1700     }
1701         
1702     buf[1] = (char)rq->origid;
1703     memcpy(buf + 4, rq->origauth, 16);
1704 #ifdef DEBUG    
1705     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1706 #endif
1707
1708     if (rq->origusername) {
1709         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1710         if (!username) {
1711             pthread_mutex_unlock(&server->newrq_mutex);
1712             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1713             return 0;
1714         }
1715         memcpy(username, rq->origusername, strlen(rq->origusername));
1716         len = RADLEN(buf) - 20;
1717         attrs = buf + 20;
1718         if (messageauth)
1719             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1720     }
1721         
1722     if (messageauth) {
1723         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1724             pthread_mutex_unlock(&server->newrq_mutex);
1725             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1726             return 0;
1727         }
1728         debug(DBG_DBG, "replyh: computed messageauthattr");
1729     }
1730
1731     if (from->conf->type == 'U')
1732         fromsa = rq->fromsa;
1733     /* once we set received = 1, rq may be reused */
1734     rq->received = 1;
1735     pthread_mutex_unlock(&server->newrq_mutex);
1736
1737     debug(DBG_DBG, "replyh: giving packet back to where it came from");
1738     sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1739     return 1;
1740 }
1741
1742 void *udpclientrd(void *arg) {
1743     struct server *server = (struct server *)arg;
1744     unsigned char *buf;
1745     
1746     for (;;) {
1747         buf = radudpget(server->sock, NULL, &server, NULL);
1748         if (!replyh(server, buf))
1749             free(buf);
1750     }
1751 }
1752
1753 void *tlsclientrd(void *arg) {
1754     struct server *server = (struct server *)arg;
1755     unsigned char *buf;
1756     struct timeval lastconnecttry;
1757     
1758     for (;;) {
1759         /* yes, lastconnecttry is really necessary */
1760         lastconnecttry = server->lastconnecttry;
1761         buf = radtlsget(server->ssl);
1762         if (!buf) {
1763             tlsconnect(server, &lastconnecttry, "clientrd");
1764             continue;
1765         }
1766
1767         if (!replyh(server, buf))
1768             free(buf);
1769     }
1770 }
1771
1772 void *clientwr(void *arg) {
1773     struct server *server = (struct server *)arg;
1774     struct request *rq;
1775     pthread_t clientrdth;
1776     int i;
1777     uint8_t rnd;
1778     struct timeval now, lastsend;
1779     struct timespec timeout;
1780     struct request statsrvrq;
1781     unsigned char statsrvbuf[38];
1782
1783     memset(&timeout, 0, sizeof(struct timespec));
1784     
1785     if (server->conf->statusserver) {
1786         memset(&statsrvrq, 0, sizeof(struct request));
1787         memset(statsrvbuf, 0, sizeof(statsrvbuf));
1788         statsrvbuf[0] = RAD_Status_Server;
1789         statsrvbuf[3] = 38;
1790         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1791         statsrvbuf[21] = 18;
1792         gettimeofday(&lastsend, NULL);
1793     }
1794     
1795     if (server->conf->type == 'U') {
1796         if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0)
1797             debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1798         server->connectionok = 1;
1799         if (pthread_create(&clientrdth, NULL, udpclientrd, (void *)server))
1800             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1801     } else {
1802         tlsconnect(server, NULL, "new client");
1803         server->connectionok = 1;
1804         if (pthread_create(&clientrdth, NULL, tlsclientrd, (void *)server))
1805             debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1806     }
1807     
1808     for (;;) {
1809         pthread_mutex_lock(&server->newrq_mutex);
1810         if (!server->newrq) {
1811             gettimeofday(&now, NULL);
1812             if (server->conf->statusserver) {
1813                 /* random 0-7 seconds */
1814                 RAND_bytes(&rnd, 1);
1815                 rnd /= 32;
1816                 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1817                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1818             }   
1819             if (timeout.tv_sec) {
1820                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1821                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1822                 timeout.tv_sec = 0;
1823             } else {
1824                 debug(DBG_DBG, "clientwr: waiting for new request");
1825                 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1826             }
1827         }
1828         if (server->newrq) {
1829             debug(DBG_DBG, "clientwr: got new request");
1830             server->newrq = 0;
1831         } else
1832             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1833         pthread_mutex_unlock(&server->newrq_mutex);
1834
1835         for (i = 0; i < MAX_REQUESTS; i++) {
1836             pthread_mutex_lock(&server->newrq_mutex);
1837             while (i < MAX_REQUESTS && !server->requests[i].buf)
1838                 i++;
1839             if (i == MAX_REQUESTS) {
1840                 pthread_mutex_unlock(&server->newrq_mutex);
1841                 break;
1842             }
1843             rq = server->requests + i;
1844
1845             if (rq->received) {
1846                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1847                 if (rq->buf) {
1848                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1849                     freerqdata(rq);
1850                     /* setting this to NULL means that it can be reused */
1851                     rq->buf = NULL;
1852                 }
1853                 pthread_mutex_unlock(&server->newrq_mutex);
1854                 continue;
1855             }
1856             
1857             gettimeofday(&now, NULL);
1858             if (now.tv_sec < rq->expiry.tv_sec) {
1859                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1860                     timeout.tv_sec = rq->expiry.tv_sec;
1861                 pthread_mutex_unlock(&server->newrq_mutex);
1862                 continue;
1863             }
1864
1865             if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1866                               ? 1 : REQUEST_RETRIES)) {
1867                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1868                 if (*rq->buf == RAD_Status_Server) {
1869                     debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1870                     if (server->loststatsrv < 255)
1871                         server->loststatsrv++;
1872                 }
1873                 freerqdata(rq);
1874                 /* setting this to NULL means that it can be reused */
1875                 rq->buf = NULL;
1876                 pthread_mutex_unlock(&server->newrq_mutex);
1877                 continue;
1878             }
1879             pthread_mutex_unlock(&server->newrq_mutex);
1880
1881             rq->expiry.tv_sec = now.tv_sec +
1882                 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1883                  ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1884             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1885                 timeout.tv_sec = rq->expiry.tv_sec;
1886             rq->tries++;
1887             clientradput(server, server->requests[i].buf);
1888             gettimeofday(&lastsend, NULL);
1889         }
1890         if (server->conf->statusserver) {
1891             gettimeofday(&now, NULL);
1892             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1893                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1894                     debug(DBG_WARN, "clientwr: failed to generate random auth");
1895                     continue;
1896                 }
1897                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1898                 if (!statsrvrq.buf) {
1899                     debug(DBG_ERR, "clientwr: malloc failed");
1900                     continue;
1901                 }
1902                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1903                 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1904                 lastsend.tv_sec = now.tv_sec;
1905                 sendrq(server, &statsrvrq);
1906             }
1907         }
1908     }
1909 }
1910
1911 void *udpserverwr(void *arg) {
1912     struct replyq *replyq = udp_server_replyq;
1913     struct reply *reply;
1914     
1915     for (;;) {
1916         pthread_mutex_lock(&replyq->mutex);
1917         while (!(reply = (struct reply *)list_shift(replyq->replies))) {
1918             debug(DBG_DBG, "udp server writer, waiting for signal");
1919             pthread_cond_wait(&replyq->cond, &replyq->mutex);
1920             debug(DBG_DBG, "udp server writer, got signal");
1921         }
1922         pthread_mutex_unlock(&replyq->mutex);
1923
1924         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1925                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1926             debug(DBG_WARN, "sendudp: send failed");
1927         free(reply->buf);
1928         free(reply);
1929     }
1930 }
1931
1932 void *udpserverrd(void *arg) {
1933     struct request rq;
1934     pthread_t udpserverwrth;
1935
1936     if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1937         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1938
1939     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1940           udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1941
1942     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1943         debugx(1, DBG_ERR, "pthread_create failed");
1944     
1945     for (;;) {
1946         memset(&rq, 0, sizeof(struct request));
1947         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1948         radsrv(&rq);
1949     }
1950 }
1951
1952 void *udpaccserverrd(void *arg) {
1953     struct request rq;
1954
1955     if ((udp_accserver_sock = bindtoaddr(udp_accserver_listen->addrinfo)) < 0)
1956         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1957
1958     debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
1959           udp_accserver_listen->host ? udp_accserver_listen->host : "*", udp_accserver_listen->port);
1960
1961     for (;;) {
1962         memset(&rq, 0, sizeof(struct request));
1963         rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
1964         if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
1965             radsrv(&rq);
1966             continue;
1967         }
1968         debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
1969         freerqdata(&rq);
1970     }
1971 }
1972
1973 void *tlsserverwr(void *arg) {
1974     int cnt;
1975     unsigned long error;
1976     struct client *client = (struct client *)arg;
1977     struct replyq *replyq;
1978     struct reply *reply;
1979     
1980     debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
1981     replyq = client->replyq;
1982     for (;;) {
1983         pthread_mutex_lock(&replyq->mutex);
1984         while (!list_first(replyq->replies)) {
1985             if (client->ssl) {      
1986                 debug(DBG_DBG, "tls server writer, waiting for signal");
1987                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1988                 debug(DBG_DBG, "tls server writer, got signal");
1989             }
1990             if (!client->ssl) {
1991                 /* ssl might have changed while waiting */
1992                 pthread_mutex_unlock(&replyq->mutex);
1993                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1994                 pthread_exit(NULL);
1995             }
1996         }
1997         reply = (struct reply *)list_shift(replyq->replies);
1998         pthread_mutex_unlock(&replyq->mutex);
1999         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2000         if (cnt > 0)
2001             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2002                   cnt, RADLEN(reply->buf));
2003         else
2004             while ((error = ERR_get_error()))
2005                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2006         free(reply->buf);
2007         free(reply);
2008     }
2009 }
2010
2011 void *tlsserverrd(void *arg) {
2012     struct request rq;
2013     unsigned long error;
2014     int s;
2015     struct client *client = (struct client *)arg;
2016     pthread_t tlsserverwrth;
2017     SSL *ssl;
2018     
2019     debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2020     ssl = client->ssl;
2021
2022     if (SSL_accept(ssl) <= 0) {
2023         while ((error = ERR_get_error()))
2024             debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2025         debug(DBG_ERR, "SSL_accept failed");
2026         goto errexit;
2027     }
2028     if (tlsverifycert(client->ssl, client->conf)) {
2029         if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2030             debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2031             goto errexit;
2032         }
2033         for (;;) {
2034             memset(&rq, 0, sizeof(struct request));
2035             rq.buf = radtlsget(client->ssl);
2036             if (!rq.buf)
2037                 break;
2038             debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2039             rq.from = client;
2040             radsrv(&rq);
2041         }
2042         debug(DBG_ERR, "tlsserverrd: connection lost");
2043         /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2044         client->ssl = NULL;
2045         pthread_mutex_lock(&client->replyq->mutex);
2046         pthread_cond_signal(&client->replyq->cond);
2047         pthread_mutex_unlock(&client->replyq->mutex);
2048         debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2049         pthread_join(tlsserverwrth, NULL);
2050     }
2051     
2052  errexit:
2053     s = SSL_get_fd(ssl);
2054     SSL_free(ssl);
2055     shutdown(s, SHUT_RDWR);
2056     close(s);
2057     debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2058     removeclient(client);
2059     pthread_exit(NULL);
2060 }
2061
2062 int tlslistener() {
2063     pthread_t tlsserverth;
2064     int s, snew;
2065     struct sockaddr_storage from;
2066     size_t fromlen = sizeof(from);
2067     struct clsrvconf *conf;
2068     struct client *client;
2069     
2070     if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
2071         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2072     
2073     listen(s, 0);
2074     debug(DBG_WARN, "listening for incoming TCP on %s:%s",
2075           tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
2076
2077     for (;;) {
2078         snew = accept(s, (struct sockaddr *)&from, &fromlen);
2079         if (snew < 0) {
2080             debug(DBG_WARN, "accept failed");
2081             continue;
2082         }
2083         debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2084
2085         conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2086         if (!conf) {
2087             debug(DBG_WARN, "ignoring request, not a known TLS client");
2088             shutdown(snew, SHUT_RDWR);
2089             close(snew);
2090             continue;
2091         }
2092
2093         client = addclient(conf);
2094
2095         if (!client) {
2096             debug(DBG_WARN, "Failed to create new client instance");
2097             shutdown(snew, SHUT_RDWR);
2098             close(snew);
2099             continue;
2100         }
2101         client->ssl = SSL_new(client->conf->ssl_ctx);
2102         SSL_set_fd(client->ssl, snew);
2103         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2104             debug(DBG_ERR, "tlslistener: pthread_create failed");
2105             SSL_free(client->ssl);
2106             removeclient(client);
2107             shutdown(snew, SHUT_RDWR);
2108             close(snew);
2109             continue;
2110         }
2111         pthread_detach(tlsserverth);
2112     }
2113     return 0;
2114 }
2115
2116 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2117     struct tls *new;
2118     SSL_CTX *ctx;
2119     int i;
2120     unsigned long error;
2121     
2122     if (!certfile || !certkeyfile)
2123         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2124
2125     if (!cacertfile && !cacertpath)
2126         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2127
2128     if (!ssl_locks) {
2129         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2130         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2131         for (i = 0; i < CRYPTO_num_locks(); i++) {
2132             ssl_lock_count[i] = 0;
2133             pthread_mutex_init(&ssl_locks[i], NULL);
2134         }
2135         CRYPTO_set_id_callback(ssl_thread_id);
2136         CRYPTO_set_locking_callback(ssl_locking_callback);
2137
2138         SSL_load_error_strings();
2139         SSL_library_init();
2140
2141         while (!RAND_status()) {
2142             time_t t = time(NULL);
2143             pid_t pid = getpid();
2144             RAND_seed((unsigned char *)&t, sizeof(time_t));
2145             RAND_seed((unsigned char *)&pid, sizeof(pid));
2146         }
2147     }
2148     ctx = SSL_CTX_new(TLSv1_method());
2149     if (certkeypwd) {
2150         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2151         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2152     }
2153     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2154         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2155         !SSL_CTX_check_private_key(ctx) ||
2156         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2157         while ((error = ERR_get_error()))
2158             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2159         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2160     }
2161     
2162     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2163     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2164
2165     new = malloc(sizeof(struct tls));
2166     if (!new || !list_push(tlsconfs, new))
2167         debugx(1, DBG_ERR, "malloc failed");
2168
2169     memset(new, 0, sizeof(struct tls));
2170     new->name = stringcopy(value, 0);
2171     if (!new->name)
2172         debugx(1, DBG_ERR, "malloc failed");
2173     new->ctx = ctx;
2174     new->count = 0;
2175     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2176 }
2177
2178 void tlsfree() {
2179     struct list_node *entry;
2180     struct tls *t;
2181     
2182     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2183         t = (struct tls *)entry->data;
2184         if (t->name)
2185             free(t->name);
2186         if (!t->count)
2187             SSL_CTX_free(t->ctx);
2188     }
2189     list_destroy(tlsconfs);
2190     tlsconfs = NULL;
2191 }
2192
2193 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2194     struct list_node *entry;
2195     struct tls *t, *t1 = NULL, *t2 = NULL;
2196     
2197     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2198         t = (struct tls *)entry->data;
2199         if (!strcasecmp(t->name, alt1)) {
2200             t1 = t;
2201             break;
2202         }
2203         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2204             t2 = t;
2205     }
2206
2207     t = (t1 ? t1 : t2);
2208     if (!t)
2209         return NULL;
2210     t->count++;
2211     return t->ctx;
2212 }
2213
2214 void addrealm(char *value, char **servers, char *message) {
2215     int n;
2216     struct realm *realm;
2217     char *s, *regex = NULL;
2218     struct list_node *entry;
2219     struct clsrvconf *conf;
2220     
2221     if (*value == '/') {
2222         /* regexp, remove optional trailing / if present */
2223         if (value[strlen(value) - 1] == '/')
2224             value[strlen(value) - 1] = '\0';
2225     } else {
2226         /* not a regexp, let us make it one */
2227         if (*value == '*' && !value[1])
2228             regex = stringcopy(".*", 0);
2229         else {
2230             for (n = 0, s = value; *s;)
2231                 if (*s++ == '.')
2232                     n++;
2233             regex = malloc(strlen(value) + n + 3);
2234             if (regex) {
2235                 regex[0] = '@';
2236                 for (n = 1, s = value; *s; s++) {
2237                     if (*s == '.')
2238                         regex[n++] = '\\';
2239                     regex[n++] = *s;
2240                 }
2241                 regex[n++] = '$';
2242                 regex[n] = '\0';
2243             }
2244         }
2245         if (!regex)
2246             debugx(1, DBG_ERR, "malloc failed");
2247         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2248     }
2249
2250     realm = malloc(sizeof(struct realm));
2251     if (!realm)
2252         debugx(1, DBG_ERR, "malloc failed");
2253     
2254     memset(realm, 0, sizeof(struct realm));
2255     realm->name = stringcopy(value, 0);
2256     if (!realm->name)
2257         debugx(1, DBG_ERR, "malloc failed");
2258     if (message && strlen(message) > 253)
2259         debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2260     realm->message = message;
2261     
2262     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2263         debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2264     if (regex)
2265         free(regex);
2266     
2267     if (servers && *servers) {
2268         realm->srvconfs = list_create();
2269         if (!realm->srvconfs)
2270             debugx(1, DBG_ERR, "malloc failed");
2271         for (n = 0; servers[n]; n++) {
2272             for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2273                 conf = (struct clsrvconf *)entry->data;
2274                 if (!strcasecmp(servers[n], conf->name))
2275                     break;
2276             }
2277             if (!entry)
2278                 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2279             if (!list_push(realm->srvconfs, conf))
2280                 debugx(1, DBG_ERR, "malloc failed");
2281             debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2282         }
2283     } else
2284         realm->srvconfs = NULL;
2285     
2286     if (!list_push(realms, realm))
2287         debugx(1, DBG_ERR, "malloc failed");
2288     debug(DBG_DBG, "addrealm: added realm %s", value);
2289 }
2290
2291 char *parsehostport(char *s, struct clsrvconf *conf) {
2292     char *p, *field;
2293     int ipv6 = 0;
2294
2295     p = s;
2296     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
2297     if (*p == '[') {
2298         p++;
2299         field = p;
2300         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2301         if (*p != ']')
2302             debugx(1, DBG_ERR, "no ] matching initial [");
2303         ipv6 = 1;
2304     } else {
2305         field = p;
2306         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2307     }
2308     if (field == p)
2309         debugx(1, DBG_ERR, "missing host/address");
2310
2311     conf->host = stringcopy(field, p - field);
2312     if (ipv6) {
2313         p++;
2314         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
2315             debugx(1, DBG_ERR, "unexpected character after ]");
2316     }
2317     if (*p == ':') {
2318             /* port number or service name is specified */;
2319             field = ++p;
2320             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2321             if (field == p)
2322                 debugx(1, DBG_ERR, "syntax error, : but no following port");
2323             conf->port = stringcopy(field, p - field);
2324     } else
2325         conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
2326     return p;
2327 }
2328
2329 FILE *openconfigfile(const char *filename) {
2330     FILE *f;
2331     char pathname[100], *base = NULL;
2332     
2333     f = fopen(filename, "r");
2334     if (f) {
2335         debug(DBG_DBG, "reading config file %s", filename);
2336         return f;
2337     }
2338
2339     if (strlen(filename) + 1 <= sizeof(pathname)) {
2340         /* basename() might modify the string */
2341         strcpy(pathname, filename);
2342         base = basename(pathname);
2343         f = fopen(base, "r");
2344     }
2345
2346     if (!f)
2347         debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2348     
2349     debug(DBG_DBG, "reading config file %s", base);
2350     return f;
2351 }
2352
2353 struct clsrvconf *server_create(char type, char *lconf) {
2354     struct clsrvconf *conf;
2355
2356     conf = malloc(sizeof(struct clsrvconf));
2357     if (!conf)
2358         debugx(1, DBG_ERR, "malloc failed");
2359     memset(conf, 0, sizeof(struct clsrvconf));
2360     conf->type = type;
2361     if (lconf) {
2362         parsehostport(lconf, conf);
2363         if (!strcmp(conf->host, "*")) {
2364             free(conf->host);
2365             conf->host = NULL;
2366         }
2367     } else
2368         conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
2369     if (!resolvepeer(conf, AI_PASSIVE))
2370         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2371     return conf;
2372 }
2373
2374 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2375 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2376     char *t = s, *q, *r;
2377
2378     if (!t || !token || !del)
2379         return NULL;
2380     while (*t && strchr(del, *t))
2381         t++;
2382     if (!*t || (comment && strchr(comment, *t))) {
2383         *token = NULL;
2384         return t + 1; /* needs to be non-NULL, but value doesn't matter */
2385     }
2386     if (quote && (q = strchr(quote, *t))) {
2387         t++;
2388         r = t;
2389         while (*t && *t != *q)
2390             t++;
2391         if (!*t || (t[1] && !strchr(del, t[1])))
2392             return NULL;
2393         *t = '\0';
2394         *token = r;
2395         return t + 1;
2396     }
2397     *token = t;
2398     t++;
2399     while (*t && !strchr(del, *t))
2400         t++;
2401     *t = '\0';
2402     return t + 1;
2403 }
2404
2405 /* Parses config with following syntax:
2406  * One of these:
2407  * option-name value
2408  * option-name = value
2409  * Or:
2410  * option-name value {
2411  *     option-name [=] value
2412  *     ...
2413  * }
2414  */
2415 void getgeneralconfig(FILE *f, char *block, ...) {
2416     va_list ap;
2417     char line[1024];
2418     /* initialise lots of stuff to avoid stupid compiler warnings */
2419     char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL, ***mstr = NULL;
2420     int type = 0, tcount, conftype = 0, n;
2421     void (*cbk)(FILE *, char *, char *, char *) = NULL;
2422         
2423     while (fgets(line, 1024, f)) {
2424         s = line;
2425         for (tcount = 0; tcount < 3; tcount++) {
2426             s = strtokenquote(s, &tokens[tcount], " \t\r\n", "\"'", tcount ? NULL : "#");
2427             if (!s)
2428                 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2429             if (!tokens[tcount])
2430                 break;
2431         }
2432         if (!tcount || **tokens == '#')
2433             continue;
2434
2435         if (**tokens == '}') {
2436             if (block)
2437                 return;
2438             debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2439         }
2440             
2441         switch (tcount) {
2442         case 2:
2443             opt = tokens[0];
2444             val = tokens[1];
2445             conftype = CONF_STR;
2446             break;
2447         case 3:
2448             if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2449                 opt = tokens[0];
2450                 val = tokens[2];
2451                 conftype = CONF_STR;
2452                 break;
2453             }
2454             if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2455                 opt = tokens[0];
2456                 val = tokens[1];
2457                 conftype = CONF_CBK;
2458                 break;
2459             }
2460             /* fall through */
2461         default:
2462             if (block)
2463                 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2464             debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2465         }
2466
2467         if (!*val)
2468             debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2469         
2470         va_start(ap, block);
2471         while ((word = va_arg(ap, char *))) {
2472             type = va_arg(ap, int);
2473             switch (type) {
2474             case CONF_STR:
2475                 str = va_arg(ap, char **);
2476                 if (!str)
2477                     debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2478                 break;
2479             case CONF_MSTR:
2480                 mstr = va_arg(ap, char ***);
2481                 if (!mstr)
2482                     debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2483                 break;
2484             case CONF_CBK:
2485                 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2486                 break;
2487             default:
2488                 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2489             }
2490             if (!strcasecmp(opt, word))
2491                 break;
2492         }
2493         va_end(ap);
2494         
2495         if (!word) {
2496             if (block)
2497                 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2498             debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2499         }
2500
2501         if (((type == CONF_STR || type == CONF_MSTR) && conftype != CONF_STR) ||
2502             (type == CONF_CBK && conftype != CONF_CBK)) {
2503             if (block)
2504                 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2505             debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2506         }
2507         
2508         switch (type) {
2509         case CONF_STR:
2510             if (block)
2511                 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2512             else 
2513                 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2514             *str = stringcopy(val, 0);
2515             if (!*str)
2516                 debugx(1, DBG_ERR, "malloc failed");
2517             break;
2518         case CONF_MSTR:
2519             if (block)
2520                 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2521             else 
2522                 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2523             if (*mstr)
2524                 for (n = 0; (*mstr)[n]; n++);
2525             else
2526                 n = 0;
2527             *mstr = realloc(*mstr, sizeof(char *) * (n + 2));
2528             if (!*mstr)
2529                 debugx(1, DBG_ERR, "malloc failed");
2530             (*mstr)[n] = stringcopy(val, 0);
2531             (*mstr)[n + 1] = NULL;
2532             break;
2533         case CONF_CBK:
2534             optval = malloc(strlen(opt) + strlen(val) + 2);
2535             if (!optval)
2536                 debugx(1, DBG_ERR, "malloc failed");
2537             sprintf(optval, "%s %s", opt, val);
2538             cbk(f, optval, opt, val);
2539             free(optval);
2540             break;
2541         default:
2542             debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2543         }
2544     }
2545 }
2546
2547 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2548     char *v;
2549     
2550     v = matchcertattr + 20;
2551     if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2552         return 0;
2553     /* regexp, remove optional trailing / if present */
2554     if (v[strlen(v) - 1] == '/')
2555         v[strlen(v) - 1] = '\0';
2556     if (!*v)
2557         return 0;
2558
2559     conf->certuriregex = malloc(sizeof(regex_t));
2560     if (!conf->certuriregex) {
2561         debug(DBG_ERR, "malloc failed");
2562         return 0;
2563     }
2564     if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2565         free(conf->certuriregex);
2566         conf->certuriregex = NULL;
2567         debug(DBG_ERR, "failed to compile regular expression %s", v);
2568         return 0;
2569     }
2570     return 1;
2571 }
2572
2573 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2574     char *v, *w;
2575     
2576     v = rewriteattr + 11;
2577     if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2578         return 0;
2579     /* regexp, remove optional trailing / if present */
2580     if (v[strlen(v) - 1] == '/')
2581         v[strlen(v) - 1] = '\0';
2582
2583     w = strchr(v, '/');
2584     if (!*w)
2585         return 0;
2586     *w = '\0';
2587     w++;
2588     
2589     conf->rewriteattrregex = malloc(sizeof(regex_t));
2590     if (!conf->rewriteattrregex) {
2591         debug(DBG_ERR, "malloc failed");
2592         return 0;
2593     }
2594
2595     conf->rewriteattrreplacement = stringcopy(w, 0);
2596     if (!conf->rewriteattrreplacement) {
2597         free(conf->rewriteattrregex);
2598         conf->rewriteattrregex = NULL;
2599         return 0;
2600     }
2601     
2602     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2603         free(conf->rewriteattrregex);
2604         conf->rewriteattrregex = NULL;
2605         free(conf->rewriteattrreplacement);
2606         conf->rewriteattrreplacement = NULL;
2607         debug(DBG_ERR, "failed to compile regular expression %s", v);
2608         return 0;
2609     }
2610
2611     return 1;
2612 }
2613
2614 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2615     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2616     struct clsrvconf *conf;
2617     
2618     debug(DBG_DBG, "confclient_cb called for %s", block);
2619
2620     conf = malloc(sizeof(struct clsrvconf));
2621     if (!conf || !list_push(clconfs, conf))
2622         debugx(1, DBG_ERR, "malloc failed");
2623     memset(conf, 0, sizeof(struct clsrvconf));
2624     
2625     getgeneralconfig(f, block,
2626                      "type", CONF_STR, &type,
2627                      "host", CONF_STR, &conf->host,
2628                      "secret", CONF_STR, &conf->secret,
2629                      "tls", CONF_STR, &tls,
2630                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2631                      "rewriteattribute", CONF_STR, &rewriteattr,
2632                      NULL
2633                      );
2634
2635     /* leave conf->name to be NULL for clients */
2636     if (!conf->host)
2637         conf->host = stringcopy(val, 0);
2638     
2639     if (type && !strcasecmp(type, "udp")) {
2640         conf->type = 'U';
2641         client_udp_count++;
2642     } else if (type && !strcasecmp(type, "tls")) {
2643         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2644         if (!conf->ssl_ctx)
2645             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2646         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2647             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2648         conf->type = 'T';
2649         client_tls_count++;
2650     } else
2651         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2652     free(type);
2653     if (tls)
2654         free(tls);
2655     if (matchcertattr)
2656         free(matchcertattr);
2657     
2658     if (rewriteattr) {
2659         if (!addrewriteattr(conf, rewriteattr))
2660             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2661         free(rewriteattr);
2662     }
2663     
2664     if (!resolvepeer(conf, 0))
2665         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2666     
2667     if (!conf->secret) {
2668         if (conf->type == 'U')
2669             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2670         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2671     }
2672 }
2673
2674 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2675     char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2676     struct clsrvconf *conf;
2677     
2678     debug(DBG_DBG, "confserver_cb called for %s", block);
2679
2680     conf = malloc(sizeof(struct clsrvconf));
2681     if (!conf || !list_push(srvconfs, conf))
2682         debugx(1, DBG_ERR, "malloc failed");
2683     memset(conf, 0, sizeof(struct clsrvconf));
2684     
2685     getgeneralconfig(f, block,
2686                      "type", CONF_STR, &type,
2687                      "host", CONF_STR, &conf->host,
2688                      "port", CONF_STR, &conf->port,
2689                      "secret", CONF_STR, &conf->secret,
2690                      "tls", CONF_STR, &tls,
2691                      "matchcertificateattribute", CONF_STR, &matchcertattr,
2692                      "StatusServer", CONF_STR, &statusserver,
2693                      NULL
2694                      );
2695
2696     conf->name = stringcopy(val, 0);
2697     if (!conf->host)
2698         conf->host = stringcopy(val, 0);
2699     
2700     if (type && !strcasecmp(type, "udp")) {
2701         conf->type = 'U';
2702         server_udp_count++;
2703         if (!conf->port)
2704             conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2705     } else if (type && !strcasecmp(type, "tls")) {
2706         conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2707         if (!conf->ssl_ctx)
2708             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2709         if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2710             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2711         if (!conf->port)
2712             conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2713         conf->type = 'T';
2714         server_tls_count++;
2715     } else
2716         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2717     free(type);
2718     if (tls)
2719         free(tls);
2720     if (matchcertattr)
2721         free(matchcertattr);
2722     
2723     if (!resolvepeer(conf, 0))
2724         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2725     
2726     if (!conf->secret) {
2727         if (conf->type == 'U')
2728             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2729         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2730     }
2731     
2732     if (statusserver) {
2733         if (!strcasecmp(statusserver, "on"))
2734             conf->statusserver = 1;
2735         else if (strcasecmp(statusserver, "off"))
2736             debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2737         free(statusserver);
2738     }
2739 }
2740
2741 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2742     char **servers = NULL, *msg = NULL;
2743     
2744     debug(DBG_DBG, "confrealm_cb called for %s", block);
2745     
2746     getgeneralconfig(f, block,
2747                      "server", CONF_MSTR, &servers,
2748                      "ReplyMessage", CONF_STR, &msg,
2749                      NULL
2750                      );
2751
2752     addrealm(val, servers, msg);
2753     free(servers);
2754 }
2755
2756 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2757     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2758     
2759     debug(DBG_DBG, "conftls_cb called for %s", block);
2760     
2761     getgeneralconfig(f, block,
2762                      "CACertificateFile", CONF_STR, &cacertfile,
2763                      "CACertificatePath", CONF_STR, &cacertpath,
2764                      "CertificateFile", CONF_STR, &certfile,
2765                      "CertificateKeyFile", CONF_STR, &certkeyfile,
2766                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
2767                      NULL
2768                      );
2769     
2770     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2771     free(cacertfile);
2772     free(cacertpath);
2773     free(certfile);
2774     free(certkeyfile);
2775     free(certkeypwd);
2776 }
2777
2778 void getmainconfig(const char *configfile) {
2779     FILE *f;
2780     char *loglevel = NULL;
2781
2782     f = openconfigfile(configfile);
2783     memset(&options, 0, sizeof(options));
2784     
2785     clconfs = list_create();
2786     if (!clconfs)
2787         debugx(1, DBG_ERR, "malloc failed");
2788     
2789     srvconfs = list_create();
2790     if (!srvconfs)
2791         debugx(1, DBG_ERR, "malloc failed");
2792     
2793     realms = list_create();
2794     if (!realms)
2795         debugx(1, DBG_ERR, "malloc failed");    
2796  
2797     tlsconfs = list_create();
2798     if (!tlsconfs)
2799         debugx(1, DBG_ERR, "malloc failed");    
2800  
2801     getgeneralconfig(f, NULL,
2802                      "ListenUDP", CONF_STR, &options.listenudp,
2803                      "ListenTCP", CONF_STR, &options.listentcp,
2804                      "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2805                      "LogLevel", CONF_STR, &loglevel,
2806                      "LogDestination", CONF_STR, &options.logdestination,
2807                      "Client", CONF_CBK, confclient_cb,
2808                      "Server", CONF_CBK, confserver_cb,
2809                      "Realm", CONF_CBK, confrealm_cb,
2810                      "TLS", CONF_CBK, conftls_cb,
2811                      NULL
2812                      );
2813     fclose(f);
2814     tlsfree();
2815     
2816     if (loglevel) {
2817         if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2818             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2819         options.loglevel = *loglevel - '0';
2820         free(loglevel);
2821     }
2822 }
2823
2824 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2825     int c;
2826
2827     while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2828         switch (c) {
2829         case 'c':
2830             *configfile = optarg;
2831             break;
2832         case 'd':
2833             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2834                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2835             *loglevel = *optarg - '0';
2836             break;
2837         case 'f':
2838             *foreground = 1;
2839             break;
2840         case 'v':
2841                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2842         default:
2843             goto usage;
2844         }
2845     }
2846     if (!(argc - optind))
2847         return;
2848
2849  usage:
2850     debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2851     exit(1);
2852 }
2853
2854 int main(int argc, char **argv) {
2855     pthread_t udpserverth, udpaccserverth;
2856     struct list_node *entry;
2857     uint8_t foreground = 0, loglevel = 0;
2858     char *configfile = NULL;
2859     
2860     debug_init("radsecproxy");
2861     debug_set_level(DEBUG_LEVEL);
2862     getargs(argc, argv, &foreground, &loglevel, &configfile);
2863     if (loglevel)
2864         debug_set_level(loglevel);
2865     getmainconfig(configfile ? configfile : CONFIG_MAIN);
2866     if (loglevel)
2867         options.loglevel = loglevel;
2868     else if (options.loglevel)
2869         debug_set_level(options.loglevel);
2870     if (foreground)
2871         options.logdestination = NULL;
2872     else {
2873         if (!options.logdestination)
2874             options.logdestination = "x-syslog:///";
2875         debug_set_destination(options.logdestination);
2876     }
2877
2878     if (!list_first(clconfs))
2879         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2880     if (!list_first(srvconfs))
2881         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2882     if (!list_first(realms))
2883         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2884
2885     if (!foreground && (daemon(0, 0) < 0))
2886         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2887     
2888     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2889
2890     if (client_udp_count) {
2891         udp_server_listen = server_create('U', options.listenudp);
2892         udp_server_replyq = newreplyq();
2893         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2894             debugx(1, DBG_ERR, "pthread_create failed");
2895         if (options.listenaccudp) {
2896             udp_accserver_listen = server_create('U', options.listenaccudp);
2897             if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2898                 debugx(1, DBG_ERR, "pthread_create failed");
2899         }
2900     }
2901     
2902     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2903         addserver((struct clsrvconf *)entry->data);
2904         if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2905                            (void *)((struct clsrvconf *)entry->data)->servers))
2906             debugx(1, DBG_ERR, "pthread_create failed");
2907     }
2908     
2909     if (client_tls_count) {
2910         tcp_server_listen = server_create('T', options.listentcp);
2911         return tlslistener();
2912     }
2913     
2914     /* just hang around doing nothing, anything to do here? */
2915     for (;;)
2916         sleep(1000);
2917 }