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