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