accountingresponse option for realms for sending accounting response when no accounti...
[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, total, 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", total);
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, "No room in queue, dropping request");
1251             freerqdata(rq);
1252             pthread_mutex_unlock(&to->newrq_mutex);
1253             return;
1254         }
1255     }
1256     
1257     rq->buf[1] = (char)i;
1258
1259     attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1260     if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1261         freerqdata(rq);
1262         pthread_mutex_unlock(&to->newrq_mutex);
1263         return;
1264     }
1265
1266     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1267     to->requests[i] = *rq;
1268     to->nextid = i + 1;
1269
1270     if (!to->newrq) {
1271         to->newrq = 1;
1272         debug(DBG_DBG, "signalling client writer");
1273         pthread_cond_signal(&to->newrq_cond);
1274     }
1275     pthread_mutex_unlock(&to->newrq_mutex);
1276 }
1277
1278 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1279     struct reply *reply;
1280     uint8_t first;
1281     
1282     if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1283         free(buf);
1284         debug(DBG_WARN, "sendreply: failed to sign message");
1285         return;
1286     }
1287
1288     reply = malloc(sizeof(struct reply));
1289     if (!reply) {
1290         free(buf);
1291         debug(DBG_ERR, "sendreply: malloc failed");
1292         return;
1293     }
1294     memset(reply, 0, sizeof(struct reply));
1295     reply->buf = buf;
1296     if (tosa)
1297         reply->tosa = *tosa;
1298     
1299     pthread_mutex_lock(&to->replyq->mutex);
1300
1301     first = list_first(to->replyq->replies) == NULL;
1302     
1303     if (!list_push(to->replyq->replies, reply)) {
1304         pthread_mutex_unlock(&to->replyq->mutex);
1305         free(reply);
1306         free(buf);
1307         debug(DBG_ERR, "sendreply: malloc failed");
1308         return;
1309     }
1310     
1311     if (first) {
1312         debug(DBG_DBG, "signalling server writer");
1313         pthread_cond_signal(&to->replyq->cond);
1314     }
1315     pthread_mutex_unlock(&to->replyq->mutex);
1316 }
1317
1318 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1319     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1320     static unsigned char first = 1;
1321     static EVP_MD_CTX mdctx;
1322     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1323     unsigned int md_len;
1324     uint8_t i, offset = 0, out[128];
1325     
1326     pthread_mutex_lock(&lock);
1327     if (first) {
1328         EVP_MD_CTX_init(&mdctx);
1329         first = 0;
1330     }
1331
1332     input = auth;
1333     for (;;) {
1334         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1335             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1336             !EVP_DigestUpdate(&mdctx, input, 16) ||
1337             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1338             md_len != 16) {
1339             pthread_mutex_unlock(&lock);
1340             return 0;
1341         }
1342         for (i = 0; i < 16; i++)
1343             out[offset + i] = hash[i] ^ in[offset + i];
1344         input = out + offset - 16;
1345         offset += 16;
1346         if (offset == len)
1347             break;
1348     }
1349     memcpy(in, out, len);
1350     pthread_mutex_unlock(&lock);
1351     return 1;
1352 }
1353
1354 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1355     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1356     static unsigned char first = 1;
1357     static EVP_MD_CTX mdctx;
1358     unsigned char hash[EVP_MAX_MD_SIZE], *input;
1359     unsigned int md_len;
1360     uint8_t i, offset = 0, out[128];
1361     
1362     pthread_mutex_lock(&lock);
1363     if (first) {
1364         EVP_MD_CTX_init(&mdctx);
1365         first = 0;
1366     }
1367
1368     input = auth;
1369     for (;;) {
1370         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1371             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1372             !EVP_DigestUpdate(&mdctx, input, 16) ||
1373             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1374             md_len != 16) {
1375             pthread_mutex_unlock(&lock);
1376             return 0;
1377         }
1378         for (i = 0; i < 16; i++)
1379             out[offset + i] = hash[i] ^ in[offset + i];
1380         input = in + offset;
1381         offset += 16;
1382         if (offset == len)
1383             break;
1384     }
1385     memcpy(in, out, len);
1386     pthread_mutex_unlock(&lock);
1387     return 1;
1388 }
1389
1390 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1391     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1392     static unsigned char first = 1;
1393     static EVP_MD_CTX mdctx;
1394     unsigned char hash[EVP_MAX_MD_SIZE];
1395     unsigned int md_len;
1396     uint8_t i, offset;
1397     
1398     pthread_mutex_lock(&lock);
1399     if (first) {
1400         EVP_MD_CTX_init(&mdctx);
1401         first = 0;
1402     }
1403
1404 #if 0
1405     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1406     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1407     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1408 #endif
1409     
1410     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1411         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1412         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1413         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1414         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1415         pthread_mutex_unlock(&lock);
1416         return 0;
1417     }
1418
1419 #if 0    
1420     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1421 #endif
1422     
1423     for (i = 0; i < 16; i++)
1424         text[i] ^= hash[i];
1425     
1426     for (offset = 16; offset < len; offset += 16) {
1427 #if 0   
1428         printf("text + offset - 16 c(%d): ", offset / 16);
1429         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1430 #endif
1431         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1432             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1433             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1434             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1435             md_len != 16) {
1436             pthread_mutex_unlock(&lock);
1437             return 0;
1438         }
1439 #if 0
1440         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1441 #endif    
1442         
1443         for (i = 0; i < 16; i++)
1444             text[offset + i] ^= hash[i];
1445     }
1446     
1447 #if 0
1448     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1449 #endif
1450
1451     pthread_mutex_unlock(&lock);
1452     return 1;
1453 }
1454
1455 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1456     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1457     static unsigned char first = 1;
1458     static EVP_MD_CTX mdctx;
1459     unsigned char hash[EVP_MAX_MD_SIZE];
1460     unsigned int md_len;
1461     uint8_t i, offset;
1462     char plain[255];
1463     
1464     pthread_mutex_lock(&lock);
1465     if (first) {
1466         EVP_MD_CTX_init(&mdctx);
1467         first = 0;
1468     }
1469
1470 #if 0
1471     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1472     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1473     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1474 #endif
1475     
1476     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1477         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1478         !EVP_DigestUpdate(&mdctx, auth, 16) ||
1479         !EVP_DigestUpdate(&mdctx, salt, 2) ||
1480         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1481         pthread_mutex_unlock(&lock);
1482         return 0;
1483     }
1484
1485 #if 0    
1486     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1487 #endif
1488     
1489     for (i = 0; i < 16; i++)
1490         plain[i] = text[i] ^ hash[i];
1491     
1492     for (offset = 16; offset < len; offset += 16) {
1493 #if 0   
1494         printf("text + offset - 16 c(%d): ", offset / 16);
1495         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1496 #endif
1497         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1498             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1499             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1500             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1501             md_len != 16) {
1502             pthread_mutex_unlock(&lock);
1503             return 0;
1504         }
1505 #if 0
1506         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1507 #endif    
1508
1509         for (i = 0; i < 16; i++)
1510             plain[offset + i] = text[offset + i] ^ hash[i];
1511     }
1512
1513     memcpy(text, plain, len);
1514 #if 0
1515     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1516 #endif
1517
1518     pthread_mutex_unlock(&lock);
1519     return 1;
1520 }
1521
1522 struct realm *id2realm(struct list *realmlist, char *id) {
1523     struct list_node *entry;
1524     struct realm *realm, *subrealm = NULL;
1525
1526     /* need to do locking for subrealms and check subrealm timers */
1527     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1528         realm = (struct realm *)entry->data;
1529         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1530             pthread_mutex_lock(&realm->subrealms_mutex);
1531             if (realm->subrealms)
1532                 subrealm = id2realm(realm->subrealms, id);
1533             pthread_mutex_unlock(&realm->subrealms_mutex);
1534             return subrealm ? subrealm : realm;
1535         }
1536     }
1537     return NULL;
1538 }
1539
1540 /* helper function, only used by removeserversubrealms() */
1541 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1542     struct list_node *entry;
1543     struct realm *realm;
1544     
1545     for (entry = list_first(realmlist); entry;) {
1546         realm = (struct realm *)entry->data;
1547         entry = list_next(entry);
1548         if (realm->srvconfs) {
1549             list_removedata(realm->srvconfs, srv);
1550             if (!list_first(realm->srvconfs)) {
1551                 list_destroy(realm->srvconfs);
1552                 realm->srvconfs = NULL;
1553             }
1554         }
1555         if (realm->accsrvconfs) {
1556             list_removedata(realm->accsrvconfs, srv);
1557             if (!list_first(realm->accsrvconfs)) {
1558                 list_destroy(realm->accsrvconfs);
1559                 realm->accsrvconfs = NULL;
1560             }
1561         }
1562
1563         /* remove subrealm if no servers */
1564         if (!realm->srvconfs && !realm->accsrvconfs) {
1565             list_removedata(realmlist, realm);
1566             freerealm(realm);
1567         }
1568     }
1569 }
1570
1571 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1572     struct list_node *entry;
1573     struct realm *realm;
1574     
1575     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1576         realm = (struct realm *)entry->data;
1577         pthread_mutex_lock(&realm->subrealms_mutex);
1578         if (realm->subrealms) {
1579             _internal_removeserversubrealms(realm->subrealms, srv);
1580             if (!list_first(realm->subrealms)) {
1581                 list_destroy(realm->subrealms);
1582                 realm->subrealms = NULL;
1583             }
1584         }
1585         pthread_mutex_unlock(&realm->subrealms_mutex);
1586     }
1587 }
1588                         
1589 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1590     struct request *rq = to->requests, *end;
1591     
1592     pthread_mutex_lock(&to->newrq_mutex);
1593     for (end = rq + MAX_REQUESTS; rq < end; rq++)
1594         if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1595             break;
1596     pthread_mutex_unlock(&to->newrq_mutex);
1597     
1598     return rq < end;
1599 }
1600
1601 int attrvalidate(unsigned char *attrs, int length) {
1602     while (length > 1) {
1603         if (ATTRLEN(attrs) < 2) {
1604             debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1605             return 0;
1606         }
1607         length -= ATTRLEN(attrs);
1608         if (length < 0) {
1609             debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1610             return 0;
1611         }
1612         attrs += ATTRLEN(attrs);
1613     }
1614     if (length)
1615         debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1616     return 1;
1617 }
1618
1619 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1620     if (len < 16 || len > 128 || len % 16) {
1621         debug(DBG_WARN, "pwdrecrypt: invalid password length");
1622         return 0;
1623     }
1624         
1625     if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1626         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1627         return 0;
1628     }
1629 #ifdef DEBUG
1630     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1631 #endif  
1632     if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1633         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1634         return 0;
1635     }
1636     return 1;
1637 }
1638
1639 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1640     if (len < 18)
1641         return 0;
1642     if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1643         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1644         return 0;
1645     }
1646     if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1647         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1648         return 0;
1649     }
1650     return 1;
1651 }
1652
1653 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1654            char *oldsecret, char *newsecret) {
1655     unsigned char *attr;
1656     
1657     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1658         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1659         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1660             return 0;
1661     }
1662     return 1;
1663 }
1664
1665 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1666     if (!attrs)
1667         return 0;
1668     
1669     for (; attrs[0]; attrs += 2)
1670         if (attrs[0] == vendor && attrs[1] == subattr)
1671             return 1;
1672     return 0;
1673 }
1674
1675 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1676     uint8_t alen, sublen, rmlen = 0;
1677     uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1678     uint8_t *subattrs;
1679     
1680     if (!removevendorattrs)
1681         return 0;
1682
1683     while (*removevendorattrs && *removevendorattrs != vendor)
1684         removevendorattrs += 2;
1685     if (!*removevendorattrs)
1686         return 0;
1687     
1688     alen = ATTRLEN(attrs);
1689
1690     if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1691         /* remove entire vendor attribute */
1692         memmove(attrs, attrs + alen, length - alen);
1693         return alen;
1694     }
1695
1696     sublen = alen - 4;
1697     subattrs = ATTRVAL(attrs) + 4;
1698     
1699     if (!attrvalidate(subattrs, sublen)) {
1700         debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1701         return 0;
1702     }
1703
1704     length -= 6;
1705     while (sublen > 1) {
1706         alen = ATTRLEN(subattrs);
1707         sublen -= alen;
1708         length -= alen;
1709         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1710             memmove(subattrs, subattrs + alen, length);
1711             rmlen += alen;
1712         } else
1713             subattrs += alen;
1714     }
1715
1716     ATTRLEN(attrs) -= rmlen;
1717     return rmlen;
1718 }
1719
1720 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1721     uint8_t *attrs, alen;
1722     uint16_t len, rmlen = 0;
1723     
1724     if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1725         return;
1726
1727     len = RADLEN(buf) - 20;
1728     attrs = buf + 20;
1729     while (len > 1) {
1730         alen = ATTRLEN(attrs);
1731         len -= alen;
1732         if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1733             memmove(attrs, attrs + alen, len);
1734             rmlen += alen;
1735         } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1736             rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1737         else
1738             attrs += alen;
1739     }
1740     if (rmlen)
1741         ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1742 }
1743
1744 /* returns a pointer to the resized attribute value */
1745 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1746     uint8_t *attrs, *attr, vallen;
1747     uint16_t len;
1748     unsigned char *new;
1749     
1750     len = RADLEN(*buf) - 20;
1751     attrs = *buf + 20;
1752
1753     attr = attrget(attrs, len, type);
1754     if (!attr)
1755         return NULL;
1756     
1757     vallen = ATTRVALLEN(attr);
1758     if (vallen == newvallen)
1759         return attr + 2;
1760
1761     len += newvallen - vallen;
1762     if (newvallen > vallen) {
1763         new = realloc(*buf, len + 20);
1764         if (!new) {
1765             debug(DBG_ERR, "resizeattr: malloc failed");
1766             return NULL;
1767         }
1768         if (new != *buf) {
1769             attr += new - *buf;
1770             attrs = new + 20;
1771             *buf = new;
1772         }
1773     }
1774     memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1775     attr[1] = newvallen + 2;
1776     ((uint16_t *)*buf)[1] = htons(len + 20);
1777     return attr + 2;
1778 }
1779                 
1780 int rewriteusername(struct request *rq, char *in) {
1781     size_t nmatch = 10, reslen = 0, start = 0;
1782     regmatch_t pmatch[10], *pfield;
1783     int i;
1784     unsigned char *result;
1785     char *out = rq->from->conf->rewriteattrreplacement;
1786     
1787     if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1788         debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1789         return 1;
1790     }
1791     
1792     rq->origusername = stringcopy(in, 0);
1793     if (!rq->origusername)
1794         return 0;
1795     
1796     for (i = start; out[i]; i++) {
1797         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1798             pfield = &pmatch[out[i + 1] - '0'];
1799             if (pfield->rm_so >= 0) {
1800                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1801                 start = i + 2;
1802             }
1803             i++;
1804         }
1805     }
1806     reslen += i - start;
1807
1808     result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1809     if (!result)
1810         return 0;
1811     
1812     start = 0;
1813     reslen = 0;
1814     for (i = start; out[i]; i++) {
1815         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1816             pfield = &pmatch[out[i + 1] - '0'];
1817             if (pfield->rm_so >= 0) {
1818                 memcpy(result + reslen, out + start, i - start);
1819                 reslen += i - start;
1820                 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1821                 reslen += pfield->rm_eo - pfield->rm_so;
1822                 start = i + 2;
1823             }
1824             i++;
1825         }
1826     }
1827
1828     memcpy(result + reslen, out + start, i - start);
1829     reslen += i - start;
1830     memcpy(in, result, reslen);
1831     in[reslen] = '\0';
1832     return 1;
1833 }
1834
1835 const char *radmsgtype2string(uint8_t code) {
1836     static const char *rad_msg_names[] = {
1837         "", "Access-Request", "Access-Accept", "Access-Reject",
1838         "Accounting-Request", "Accounting-Response", "", "",
1839         "", "", "", "Access-Challenge",
1840         "Status-Server", "Status-Client"
1841     };
1842     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1843 }
1844
1845 void char2hex(char *h, unsigned char c) {
1846     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1847                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1848     h[0] = hexdigits[c / 16];
1849     h[1] = hexdigits[c % 16];
1850     return;
1851 }
1852
1853 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1854     int i, l;
1855     char *s, *d;
1856
1857     if (!attr || len == 1) {
1858         *ascii = '\0';
1859         return ascii;
1860     }
1861
1862     l = ATTRVALLEN(attr);
1863     s = (char *)ATTRVAL(attr);
1864     d = ascii;
1865
1866     for (i = 0; i < l; i++) {
1867         if (s[i] > 31 && s[i] < 127) {
1868             *d++ = s[i];
1869             if (d - ascii == len - 1)
1870                 break;
1871         } else {
1872             if (d - ascii > len - 4)
1873                 break;
1874             *d++ = '%';
1875             char2hex(d, s[i]);
1876             d += 2;
1877             if (d - ascii == len - 1)
1878                 break;
1879         }
1880     }
1881     *d = '\0';
1882     return ascii;
1883 }
1884
1885 void acclog(unsigned char *attrs, int length, char *host) {
1886     unsigned char *attr;
1887     char username[760];
1888     
1889     attr = attrget(attrs, length, RAD_Attr_User_Name);
1890     if (!attr) {
1891         debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1892         return;
1893     }
1894     radattr2ascii(username, sizeof(username), attr);
1895     debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1896 }
1897         
1898 void respondaccounting(struct request *rq) {
1899     unsigned char *resp;
1900
1901     resp = malloc(20);
1902     if (!resp) {
1903         debug(DBG_ERR, "respondstatusserver: malloc failed");
1904         return;
1905     }
1906     memcpy(resp, rq->buf, 20);
1907     resp[0] = RAD_Accounting_Response;
1908     resp[2] = 0;
1909     resp[3] = 20;
1910     debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1911     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1912 }
1913
1914 void respondstatusserver(struct request *rq) {
1915     unsigned char *resp;
1916
1917     resp = malloc(20);
1918     if (!resp) {
1919         debug(DBG_ERR, "respondstatusserver: malloc failed");
1920         return;
1921     }
1922     memcpy(resp, rq->buf, 20);
1923     resp[0] = RAD_Access_Accept;
1924     resp[2] = 0;
1925     resp[3] = 20;
1926     debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1927     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1928 }
1929
1930 void respondreject(struct request *rq, char *message) {
1931     unsigned char *resp;
1932     int len = 20;
1933
1934     if (message && *message)
1935         len += 2 + strlen(message);
1936     
1937     resp = malloc(len);
1938     if (!resp) {
1939         debug(DBG_ERR, "respondreject: malloc failed");
1940         return;
1941     }
1942     memcpy(resp, rq->buf, 20);
1943     resp[0] = RAD_Access_Reject;
1944     *(uint16_t *)(resp + 2) = htons(len);
1945     if (message && *message) {
1946         resp[20] = RAD_Attr_Reply_Message;
1947         resp[21] = len - 20;
1948         memcpy(resp + 22, message, len - 22);
1949     }
1950     sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1951 }
1952
1953 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1954     struct list_node *entry;
1955     struct clsrvconf *server, *best = NULL, *first = NULL;
1956
1957     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1958         server = (struct clsrvconf *)entry->data;
1959         if (!server->servers)
1960             return server;
1961         if (!first)
1962             first = server;
1963         if (!server->servers->connectionok)
1964             continue;
1965         if (!server->servers->lostrqs)
1966             return server;
1967         if (!best) {
1968             best = server;
1969             continue;
1970         }
1971         if (server->servers->lostrqs < best->servers->lostrqs)
1972             best = server;
1973     }
1974     return best ? best : first;
1975 }
1976
1977 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1978     struct clsrvconf *srvconf;
1979     
1980     *realm = id2realm(realms, id);
1981     if (!*realm)
1982         return NULL;
1983     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1984     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1985     if (!srvconf)
1986         return NULL;
1987     if (!acc && !srvconf->servers)
1988         adddynamicrealmserver(*realm, srvconf, id);
1989     return srvconf->servers;
1990 }
1991                           
1992 void radsrv(struct request *rq) {
1993     uint8_t code, id, *auth, *attrs, *attr;
1994     uint16_t len;
1995     struct server *to = NULL;
1996     char username[254], userascii[760];
1997     unsigned char newauth[16];
1998     struct realm *realm = NULL;
1999     
2000     code = *(uint8_t *)rq->buf;
2001     id = *(uint8_t *)(rq->buf + 1);
2002     len = RADLEN(rq->buf);
2003     auth = (uint8_t *)(rq->buf + 4);
2004
2005     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2006     
2007     if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2008         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2009         goto exit;
2010     }
2011
2012     len -= 20;
2013     attrs = rq->buf + 20;
2014
2015     if (!attrvalidate(attrs, len)) {
2016         debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2017         goto exit;
2018     }
2019
2020     attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2021     if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2022         debug(DBG_WARN, "radsrv: message authentication failed");
2023         goto exit;
2024     }
2025
2026     if (code == RAD_Status_Server) {
2027         respondstatusserver(rq);
2028         goto exit;
2029     }
2030     
2031     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2032
2033     if (code == RAD_Accounting_Request) {
2034         memset(newauth, 0, 16);
2035         if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2036             debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2037             goto exit;
2038         }
2039     }
2040     
2041     if (rq->from->conf->rewrite) {
2042         dorewrite(rq->buf, rq->from->conf->rewrite);
2043         len = RADLEN(rq->buf) - 20;
2044     }
2045     
2046     attr = attrget(attrs, len, RAD_Attr_User_Name);
2047     if (!attr) {
2048         if (code == RAD_Accounting_Request) {
2049             acclog(attrs, len, rq->from->conf->host);
2050             respondaccounting(rq);
2051         } else
2052             debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2053         goto exit;
2054     }
2055     memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2056     username[ATTRVALLEN(attr)] = '\0';
2057     radattr2ascii(userascii, sizeof(userascii), attr);
2058
2059     if (rq->from->conf->rewriteattrregex) {
2060         if (!rewriteusername(rq, username)) {
2061             debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2062             goto exit;
2063         }
2064         len = RADLEN(rq->buf) - 20;
2065         auth = (uint8_t *)(rq->buf + 4);
2066         attrs = rq->buf + 20;
2067     }
2068
2069     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2070     
2071     to = findserver(&realm, username, code == RAD_Accounting_Request);
2072     if (!realm) {
2073         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2074         goto exit;
2075     }
2076     if (!to) {
2077         if (realm->message && code == RAD_Access_Request) {
2078             debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2079             respondreject(rq, realm->message);
2080         } else if (realm->accresp && code == RAD_Accounting_Request) {
2081             acclog(attrs, len, rq->from->conf->host);
2082             respondaccounting(rq);
2083         }
2084         goto exit;
2085     }
2086     
2087     if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2088         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2089               rq->from->conf->name, to->conf->name);
2090         goto exit;
2091     }
2092
2093     if (rqinqueue(to, rq->from, id, code)) {
2094         debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2095               radmsgtype2string(code), rq->from->conf->host, id);
2096         goto exit;
2097     }
2098     
2099     if (code != RAD_Accounting_Request) {
2100         if (!RAND_bytes(newauth, 16)) {
2101             debug(DBG_WARN, "radsrv: failed to generate random auth");
2102             goto exit;
2103         }
2104     }
2105
2106 #ifdef DEBUG
2107     printfchars(NULL, "auth", "%02x ", auth, 16);
2108 #endif
2109
2110     attr = attrget(attrs, len, RAD_Attr_User_Password);
2111     if (attr) {
2112         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2113         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2114             goto exit;
2115     }
2116     
2117     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2118     if (attr) {
2119         debug(DBG_DBG, "radsrv: found tunnelpwdattr 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     rq->origid = id;
2125     memcpy(rq->origauth, auth, 16);
2126     if (code == RAD_Accounting_Request) {
2127         if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
2128             debug(DBG_WARN, "radsrv: failed to sign Accounting-Request message");
2129             goto exit;
2130         }
2131     } else
2132         memcpy(auth, newauth, 16);
2133     sendrq(to, rq);
2134     return;
2135     
2136  exit:
2137     freerqdata(rq);
2138 }
2139
2140 int replyh(struct server *server, unsigned char *buf) {
2141     struct client *from;
2142     struct request *rq;
2143     int i, len, sublen;
2144     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2145     struct sockaddr_storage fromsa;
2146     char tmp[760], stationid[760];
2147     
2148     server->connectionok = 1;
2149     server->lostrqs = 0;
2150         
2151     i = buf[1]; /* i is the id */
2152
2153     if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2154         && *buf != RAD_Accounting_Response) {
2155         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2156         return 0;
2157     }
2158     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2159
2160     rq = server->requests + i;
2161
2162     pthread_mutex_lock(&server->newrq_mutex);
2163     if (!rq->buf || !rq->tries) {
2164         pthread_mutex_unlock(&server->newrq_mutex);
2165         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2166         return 0;
2167     }
2168
2169     if (rq->received) {
2170         pthread_mutex_unlock(&server->newrq_mutex);
2171         debug(DBG_INFO, "replyh: already received, ignoring reply");
2172         return 0;
2173     }
2174         
2175     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2176         pthread_mutex_unlock(&server->newrq_mutex);
2177         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2178         return 0;
2179     }
2180         
2181     len = RADLEN(buf) - 20;
2182     attrs = buf + 20;
2183
2184     if (!attrvalidate(attrs, len)) {
2185         pthread_mutex_unlock(&server->newrq_mutex);
2186         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2187         return 0;
2188     }
2189         
2190     /* Message Authenticator */
2191     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2192     if (messageauth) {
2193         if (ATTRVALLEN(messageauth) != 16) {
2194             pthread_mutex_unlock(&server->newrq_mutex);
2195             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2196             return 0;
2197         }
2198         memcpy(tmp, buf + 4, 16);
2199         memcpy(buf + 4, rq->buf + 4, 16);
2200         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2201             pthread_mutex_unlock(&server->newrq_mutex);
2202             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2203             return 0;
2204         }
2205         memcpy(buf + 4, tmp, 16);
2206         debug(DBG_DBG, "replyh: message auth ok");
2207     }
2208         
2209     if (*rq->buf == RAD_Status_Server) {
2210         rq->received = 1;
2211         pthread_mutex_unlock(&server->newrq_mutex);
2212         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2213         return 0;
2214     }
2215
2216     gettimeofday(&server->lastreply, NULL);
2217     
2218     from = rq->from;
2219     if (!from) {
2220         pthread_mutex_unlock(&server->newrq_mutex);
2221         debug(DBG_INFO, "replyh: client gone, ignoring reply");
2222         return 0;
2223     }
2224         
2225     if (server->conf->rewrite) {
2226         dorewrite(buf, server->conf->rewrite);
2227         len = RADLEN(buf) - 20;
2228     }
2229     
2230     /* MS MPPE */
2231     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2232         if (ATTRVALLEN(attr) <= 4)
2233             break;
2234             
2235         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
2236             continue;
2237             
2238         sublen = ATTRVALLEN(attr) - 4;
2239         subattrs = ATTRVAL(attr) + 4;  
2240         if (!attrvalidate(subattrs, sublen) ||
2241             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2242                     rq, server->conf->secret, from->conf->secret) ||
2243             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2244                     rq, server->conf->secret, from->conf->secret))
2245             break;
2246     }
2247     if (attr) {
2248         pthread_mutex_unlock(&server->newrq_mutex);
2249         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2250         return 0;
2251     }
2252         
2253     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2254         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2255         if (attr) {
2256             radattr2ascii(tmp, sizeof(tmp), attr);
2257             attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2258             if (attr) {
2259                 radattr2ascii(stationid, sizeof(stationid), attr);
2260                 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2261                       radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2262             } else
2263                 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2264         }
2265     }
2266         
2267     buf[1] = (char)rq->origid;
2268     memcpy(buf + 4, rq->origauth, 16);
2269 #ifdef DEBUG    
2270     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2271 #endif
2272
2273     if (rq->origusername) {
2274         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2275         if (!username) {
2276             pthread_mutex_unlock(&server->newrq_mutex);
2277             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2278             return 0;
2279         }
2280         memcpy(username, rq->origusername, strlen(rq->origusername));
2281         len = RADLEN(buf) - 20;
2282         attrs = buf + 20;
2283         if (messageauth)
2284             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2285     }
2286         
2287     if (messageauth) {
2288         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2289             pthread_mutex_unlock(&server->newrq_mutex);
2290             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2291             return 0;
2292         }
2293         debug(DBG_DBG, "replyh: computed messageauthattr");
2294     }
2295
2296     if (from->conf->type == 'U')
2297         fromsa = rq->fromsa;
2298     /* once we set received = 1, rq may be reused */
2299     rq->received = 1;
2300
2301     debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2302     sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2303     pthread_mutex_unlock(&server->newrq_mutex);
2304     return 1;
2305 }
2306
2307 void *udpclientrd(void *arg) {
2308     struct server *server;
2309     unsigned char *buf;
2310     int *s = (int *)arg;
2311     
2312     for (;;) {
2313         server = NULL;
2314         buf = radudpget(*s, NULL, &server, NULL);
2315         if (!replyh(server, buf))
2316             free(buf);
2317     }
2318 }
2319
2320 void *tlsclientrd(void *arg) {
2321     struct server *server = (struct server *)arg;
2322     unsigned char *buf;
2323     struct timeval now, lastconnecttry;
2324     
2325     for (;;) {
2326         /* yes, lastconnecttry is really necessary */
2327         lastconnecttry = server->lastconnecttry;
2328         buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2329         if (!buf) {
2330             if (server->dynamiclookuparg)
2331                 break;
2332             tlsconnect(server, &lastconnecttry, 0, "clientrd");
2333             continue;
2334         }
2335
2336         if (!replyh(server, buf))
2337             free(buf);
2338         if (server->dynamiclookuparg) {
2339             gettimeofday(&now, NULL);
2340             if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2341                 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2342                 break;
2343             }
2344         }
2345     }
2346     server->clientrdgone = 1;
2347     return NULL;
2348 }
2349
2350 /* code for removing state not finished */
2351 void *clientwr(void *arg) {
2352     struct server *server = (struct server *)arg;
2353     struct request *rq;
2354     pthread_t tlsclientrdth;
2355     int i, dynconffail = 0;
2356     uint8_t rnd;
2357     struct timeval now, lastsend;
2358     struct timespec timeout;
2359     struct request statsrvrq;
2360     unsigned char statsrvbuf[38];
2361     struct clsrvconf *conf;
2362     
2363     conf = server->conf;
2364     
2365     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2366         dynconffail = 1;
2367         goto errexit;
2368     }
2369     
2370     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2371         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2372         goto errexit;
2373     }
2374
2375     memset(&timeout, 0, sizeof(struct timespec));
2376     
2377     if (conf->statusserver) {
2378         memset(&statsrvrq, 0, sizeof(struct request));
2379         memset(statsrvbuf, 0, sizeof(statsrvbuf));
2380         statsrvbuf[0] = RAD_Status_Server;
2381         statsrvbuf[3] = 38;
2382         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2383         statsrvbuf[21] = 18;
2384         gettimeofday(&lastsend, NULL);
2385     }
2386     
2387     if (conf->type == 'U') {
2388         server->connectionok = 1;
2389     } else {
2390         if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2391             goto errexit;
2392         server->connectionok = 1;
2393         if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2394             debug(DBG_ERR, "clientwr: pthread_create failed");
2395             goto errexit;
2396         }
2397     }
2398
2399     for (;;) {
2400         pthread_mutex_lock(&server->newrq_mutex);
2401         if (!server->newrq) {
2402             gettimeofday(&now, NULL);
2403             /* random 0-7 seconds */
2404             RAND_bytes(&rnd, 1);
2405             rnd /= 32;
2406             if (conf->statusserver) {
2407                 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2408                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2409             } else {
2410                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2411                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2412             }
2413 #if 0       
2414             if (timeout.tv_sec > now.tv_sec)
2415                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2416 #endif      
2417             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2418             timeout.tv_sec = 0;
2419         }
2420         if (server->newrq) {
2421             debug(DBG_DBG, "clientwr: got new request");
2422             server->newrq = 0;
2423         }
2424 #if 0   
2425         else
2426             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2427 #endif  
2428         pthread_mutex_unlock(&server->newrq_mutex);
2429
2430         for (i = 0; i < MAX_REQUESTS; i++) {
2431             if (server->clientrdgone) {
2432                 pthread_join(tlsclientrdth, NULL);
2433                 goto errexit;
2434             }
2435             pthread_mutex_lock(&server->newrq_mutex);
2436             while (i < MAX_REQUESTS && !server->requests[i].buf)
2437                 i++;
2438             if (i == MAX_REQUESTS) {
2439                 pthread_mutex_unlock(&server->newrq_mutex);
2440                 break;
2441             }
2442             rq = server->requests + i;
2443
2444             if (rq->received) {
2445                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2446                 if (rq->buf) {
2447                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2448                     freerqdata(rq);
2449                     /* setting this to NULL means that it can be reused */
2450                     rq->buf = NULL;
2451                 }
2452                 pthread_mutex_unlock(&server->newrq_mutex);
2453                 continue;
2454             }
2455             
2456             gettimeofday(&now, NULL);
2457             if (now.tv_sec < rq->expiry.tv_sec) {
2458                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2459                     timeout.tv_sec = rq->expiry.tv_sec;
2460                 pthread_mutex_unlock(&server->newrq_mutex);
2461                 continue;
2462             }
2463
2464             if (rq->tries == (*rq->buf == RAD_Status_Server || conf->type == 'T'
2465                               ? 1 : conf->retrycount + 1)) {
2466                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2467                 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2468                 if (server->lostrqs < 255)
2469                     server->lostrqs++;
2470                 freerqdata(rq);
2471                 /* setting this to NULL means that it can be reused */
2472                 rq->buf = NULL;
2473                 pthread_mutex_unlock(&server->newrq_mutex);
2474                 continue;
2475             }
2476             pthread_mutex_unlock(&server->newrq_mutex);
2477
2478             rq->expiry.tv_sec = now.tv_sec +
2479                 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2480                  ? conf->retrydelay * (conf->retrycount + 1) : conf->retrydelay);
2481             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2482                 timeout.tv_sec = rq->expiry.tv_sec;
2483             rq->tries++;
2484             clientradput(server, server->requests[i].buf);
2485             gettimeofday(&lastsend, NULL);
2486         }
2487         if (conf->statusserver) {
2488             gettimeofday(&now, NULL);
2489             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2490                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2491                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2492                     continue;
2493                 }
2494                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2495                 if (!statsrvrq.buf) {
2496                     debug(DBG_ERR, "clientwr: malloc failed");
2497                     continue;
2498                 }
2499                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2500                 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2501                 lastsend.tv_sec = now.tv_sec;
2502                 sendrq(server, &statsrvrq);
2503             }
2504         }
2505     }
2506  errexit:
2507     conf->servers = NULL;
2508     if (server->dynamiclookuparg) {
2509         removeserversubrealms(realms, conf);
2510         if (dynconffail)
2511             free(conf);
2512         else
2513             freeclsrvconf(conf);
2514     }
2515     freeserver(server, 1);
2516     return NULL;
2517 }
2518
2519 void *udpserverwr(void *arg) {
2520     struct replyq *replyq = udp_server_replyq;
2521     struct reply *reply;
2522     
2523     for (;;) {
2524         pthread_mutex_lock(&replyq->mutex);
2525         while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2526             debug(DBG_DBG, "udp server writer, waiting for signal");
2527             pthread_cond_wait(&replyq->cond, &replyq->mutex);
2528             debug(DBG_DBG, "udp server writer, got signal");
2529         }
2530         pthread_mutex_unlock(&replyq->mutex);
2531
2532         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2533                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2534             debug(DBG_WARN, "sendudp: send failed");
2535         free(reply->buf);
2536         free(reply);
2537     }
2538 }
2539
2540 void *udpserverrd(void *arg) {
2541     struct request rq;
2542     pthread_t udpserverwrth;
2543     struct clsrvconf *listenres;
2544
2545     listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2546     if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2547         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2548
2549     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2550           listenres->host ? listenres->host : "*", listenres->port);
2551     freeclsrvres(listenres);
2552     
2553     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2554         debugx(1, DBG_ERR, "pthread_create failed");
2555     
2556     for (;;) {
2557         memset(&rq, 0, sizeof(struct request));
2558         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2559         radsrv(&rq);
2560     }
2561 }
2562
2563 void *udpaccserverrd(void *arg) {
2564     struct request rq;
2565     struct clsrvconf *listenres;
2566     
2567     listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2568     if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2569         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2570
2571     debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2572           listenres->host ? listenres->host : "*", listenres->port);
2573     freeclsrvres(listenres);
2574     
2575     for (;;) {
2576         memset(&rq, 0, sizeof(struct request));
2577         rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2578         if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2579             radsrv(&rq);
2580             continue;
2581         }
2582         debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2583         freerqdata(&rq);
2584     }
2585 }
2586
2587 void *tlsserverwr(void *arg) {
2588     int cnt;
2589     unsigned long error;
2590     struct client *client = (struct client *)arg;
2591     struct replyq *replyq;
2592     struct reply *reply;
2593     
2594     debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2595     replyq = client->replyq;
2596     for (;;) {
2597         pthread_mutex_lock(&replyq->mutex);
2598         while (!list_first(replyq->replies)) {
2599             if (client->ssl) {      
2600                 debug(DBG_DBG, "tls server writer, waiting for signal");
2601                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2602                 debug(DBG_DBG, "tls server writer, got signal");
2603             }
2604             if (!client->ssl) {
2605                 /* ssl might have changed while waiting */
2606                 pthread_mutex_unlock(&replyq->mutex);
2607                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2608                 pthread_exit(NULL);
2609             }
2610         }
2611         reply = (struct reply *)list_shift(replyq->replies);
2612         pthread_mutex_unlock(&replyq->mutex);
2613         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2614         if (cnt > 0)
2615             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2616                   cnt, RADLEN(reply->buf));
2617         else
2618             while ((error = ERR_get_error()))
2619                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2620         free(reply->buf);
2621         free(reply);
2622     }
2623 }
2624
2625 void tlsserverrd(struct client *client) {
2626     struct request rq;
2627     pthread_t tlsserverwrth;
2628     
2629     debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2630     
2631     if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2632         debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2633         return;
2634     }
2635
2636     for (;;) {
2637         memset(&rq, 0, sizeof(struct request));
2638         rq.buf = radtlsget(client->ssl, 0);
2639         if (!rq.buf)
2640             break;
2641         debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2642         rq.from = client;
2643         radsrv(&rq);
2644     }
2645     
2646     debug(DBG_ERR, "tlsserverrd: connection lost");
2647     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2648     client->ssl = NULL;
2649     pthread_mutex_lock(&client->replyq->mutex);
2650     pthread_cond_signal(&client->replyq->cond);
2651     pthread_mutex_unlock(&client->replyq->mutex);
2652     debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2653     pthread_join(tlsserverwrth, NULL);
2654     removeclientrqs(client);
2655     debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2656 }
2657
2658 void *tlsservernew(void *arg) {
2659     int s;
2660     struct sockaddr_storage from;
2661     size_t fromlen = sizeof(from);
2662     struct clsrvconf *conf;
2663     struct list_node *cur = NULL;
2664     SSL *ssl = NULL;
2665     X509 *cert = NULL;
2666     unsigned long error;
2667     struct client *client;
2668
2669     s = *(int *)arg;
2670     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2671         debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2672         goto exit;
2673     }
2674     debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2675
2676     conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2677     if (conf) {
2678         ssl = SSL_new(conf->ssl_ctx);
2679         SSL_set_fd(ssl, s);
2680
2681         if (SSL_accept(ssl) <= 0) {
2682             while ((error = ERR_get_error()))
2683                 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2684             debug(DBG_ERR, "SSL_accept failed");
2685             goto exit;
2686         }
2687         cert = verifytlscert(ssl);
2688         if (!cert)
2689             goto exit;
2690     }
2691     
2692     while (conf) {
2693         if (verifyconfcert(cert, conf)) {
2694             X509_free(cert);
2695             client = addclient(conf);
2696             if (client) {
2697                 client->ssl = ssl;
2698                 tlsserverrd(client);
2699                 removeclient(client);
2700             } else
2701                 debug(DBG_WARN, "Failed to create new client instance");
2702             goto exit;
2703         }
2704         conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2705     }
2706     debug(DBG_WARN, "ignoring request, no matching TLS client");
2707     if (cert)
2708         X509_free(cert);
2709
2710  exit:
2711     SSL_free(ssl);
2712     shutdown(s, SHUT_RDWR);
2713     close(s);
2714     pthread_exit(NULL);
2715 }
2716
2717 int tlslistener() {
2718     pthread_t tlsserverth;
2719     int s, snew;
2720     struct sockaddr_storage from;
2721     size_t fromlen = sizeof(from);
2722     struct clsrvconf *listenres;
2723
2724     listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2725     if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2726         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2727
2728     debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2729     freeclsrvres(listenres);
2730     listen(s, 0);
2731
2732     for (;;) {
2733         snew = accept(s, (struct sockaddr *)&from, &fromlen);
2734         if (snew < 0) {
2735             debug(DBG_WARN, "accept failed");
2736             continue;
2737         }
2738         if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2739             debug(DBG_ERR, "tlslistener: pthread_create failed");
2740             shutdown(snew, SHUT_RDWR);
2741             close(snew);
2742             continue;
2743         }
2744         pthread_detach(tlsserverth);
2745     }
2746     return 0;
2747 }
2748
2749 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2750     struct tls *new;
2751     SSL_CTX *ctx;
2752     STACK_OF(X509_NAME) *calist;
2753     int i;
2754     unsigned long error;
2755     
2756     if (!certfile || !certkeyfile)
2757         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2758
2759     if (!cacertfile && !cacertpath)
2760         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2761
2762     if (!ssl_locks) {
2763         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2764         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2765         for (i = 0; i < CRYPTO_num_locks(); i++) {
2766             ssl_lock_count[i] = 0;
2767             pthread_mutex_init(&ssl_locks[i], NULL);
2768         }
2769         CRYPTO_set_id_callback(ssl_thread_id);
2770         CRYPTO_set_locking_callback(ssl_locking_callback);
2771
2772         SSL_load_error_strings();
2773         SSL_library_init();
2774
2775         while (!RAND_status()) {
2776             time_t t = time(NULL);
2777             pid_t pid = getpid();
2778             RAND_seed((unsigned char *)&t, sizeof(time_t));
2779             RAND_seed((unsigned char *)&pid, sizeof(pid));
2780         }
2781     }
2782     ctx = SSL_CTX_new(TLSv1_method());
2783     if (certkeypwd) {
2784         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2785         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2786     }
2787     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2788         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2789         !SSL_CTX_check_private_key(ctx) ||
2790         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2791         while ((error = ERR_get_error()))
2792             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2793         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2794     }
2795
2796     calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2797     if (!cacertfile || calist) {
2798         if (cacertpath) {
2799             if (!calist)
2800                 calist = sk_X509_NAME_new_null();
2801             if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2802                 sk_X509_NAME_free(calist);
2803                 calist = NULL;
2804             }
2805         }
2806     }
2807     if (!calist) {
2808         while ((error = ERR_get_error()))
2809             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2810         debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2811     }
2812     SSL_CTX_set_client_CA_list(ctx, calist);
2813     
2814     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2815     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2816
2817     new = malloc(sizeof(struct tls));
2818     if (!new || !list_push(tlsconfs, new))
2819         debugx(1, DBG_ERR, "malloc failed");
2820
2821     memset(new, 0, sizeof(struct tls));
2822     new->name = stringcopy(value, 0);
2823     if (!new->name)
2824         debugx(1, DBG_ERR, "malloc failed");
2825     new->ctx = ctx;
2826     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2827 }
2828
2829 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2830     struct list_node *entry;
2831     struct tls *t, *t1 = NULL, *t2 = NULL;
2832     
2833     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2834         t = (struct tls *)entry->data;
2835         if (!strcasecmp(t->name, alt1)) {
2836             t1 = t;
2837             break;
2838         }
2839         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2840             t2 = t;
2841     }
2842
2843     t = (t1 ? t1 : t2);
2844     if (!t)
2845         return NULL;
2846     return t->ctx;
2847 }
2848
2849 struct list *addsrvconfs(char *value, char **names) {
2850     struct list *conflist;
2851     int n;
2852     struct list_node *entry;
2853     struct clsrvconf *conf = NULL;
2854     
2855     if (!names || !*names)
2856         return NULL;
2857     
2858     conflist = list_create();
2859     if (!conflist) {
2860         debug(DBG_ERR, "malloc failed");
2861         return NULL;
2862     }
2863
2864     for (n = 0; names[n]; n++) {
2865         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2866             conf = (struct clsrvconf *)entry->data;
2867             if (!strcasecmp(names[n], conf->name))
2868                 break;
2869         }
2870         if (!entry) {
2871             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2872             list_destroy(conflist);
2873             return NULL;
2874         }
2875         if (!list_push(conflist, conf)) {
2876             debug(DBG_ERR, "malloc failed");
2877             list_destroy(conflist);
2878             return NULL;
2879         }
2880         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2881     }
2882     return conflist;
2883 }
2884
2885 void freerealm(struct realm *realm) {
2886     if (!realm)
2887         return;
2888     free(realm->name);
2889     free(realm->message);
2890     regfree(&realm->regex);
2891     pthread_mutex_destroy(&realm->subrealms_mutex);
2892     if (realm->subrealms)
2893         list_destroy(realm->subrealms);
2894     if (realm->srvconfs) {
2895         /* emptying list without freeing data */
2896         while (list_shift(realm->srvconfs));
2897         list_destroy(realm->srvconfs);
2898     }
2899     if (realm->accsrvconfs) {
2900         /* emptying list without freeing data */
2901         while (list_shift(realm->accsrvconfs));
2902         list_destroy(realm->accsrvconfs);
2903     }
2904     free(realm);
2905 }
2906
2907 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2908     int n;
2909     struct realm *realm;
2910     char *s, *regex = NULL;
2911     
2912     if (*value == '/') {
2913         /* regexp, remove optional trailing / if present */
2914         if (value[strlen(value) - 1] == '/')
2915             value[strlen(value) - 1] = '\0';
2916     } else {
2917         /* not a regexp, let us make it one */
2918         if (*value == '*' && !value[1])
2919             regex = stringcopy(".*", 0);
2920         else {
2921             for (n = 0, s = value; *s;)
2922                 if (*s++ == '.')
2923                     n++;
2924             regex = malloc(strlen(value) + n + 3);
2925             if (regex) {
2926                 regex[0] = '@';
2927                 for (n = 1, s = value; *s; s++) {
2928                     if (*s == '.')
2929                         regex[n++] = '\\';
2930                     regex[n++] = *s;
2931                 }
2932                 regex[n++] = '$';
2933                 regex[n] = '\0';
2934             }
2935         }
2936         if (!regex) {
2937             debug(DBG_ERR, "malloc failed");
2938             realm = NULL;
2939             goto exit;
2940         }
2941         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2942     }
2943
2944     realm = malloc(sizeof(struct realm));
2945     if (!realm) {
2946         debug(DBG_ERR, "malloc failed");
2947         goto exit;
2948     }
2949     memset(realm, 0, sizeof(struct realm));
2950     
2951     if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2952         debug(DBG_ERR, "mutex init failed");
2953         free(realm);
2954         realm = NULL;
2955         goto exit;
2956     }
2957
2958     realm->name = stringcopy(value, 0);
2959     if (!realm->name) {
2960         debug(DBG_ERR, "malloc failed");
2961         goto errexit;
2962     }
2963     if (message && strlen(message) > 253) {
2964         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2965         goto errexit;
2966     }
2967     realm->message = message;
2968     realm->accresp = accresp;
2969     
2970     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2971         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2972         goto errexit;
2973     }
2974     
2975     if (servers && *servers) {
2976         realm->srvconfs = addsrvconfs(value, servers);
2977         if (!realm->srvconfs)
2978             goto errexit;
2979     }
2980     
2981     if (accservers && *accservers) {
2982         realm->accsrvconfs = addsrvconfs(value, accservers);
2983         if (!realm->accsrvconfs)
2984             goto errexit;
2985     }
2986
2987     if (!list_push(realmlist, realm)) {
2988         debug(DBG_ERR, "malloc failed");
2989         pthread_mutex_destroy(&realm->subrealms_mutex);
2990         goto errexit;
2991     }
2992     
2993     debug(DBG_DBG, "addrealm: added realm %s", value);
2994     goto exit;
2995
2996  errexit:
2997     freerealm(realm);
2998     realm = NULL;
2999     
3000  exit:
3001     free(regex);
3002     if (servers) {
3003         for (n = 0; servers[n]; n++)
3004             free(servers[n]);
3005         free(servers);
3006     }
3007     if (accservers) {
3008         for (n = 0; accservers[n]; n++)
3009             free(accservers[n]);
3010         free(accservers);
3011     }
3012     return realm;
3013 }
3014
3015 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3016     struct clsrvconf *srvconf;
3017     struct realm *newrealm = NULL;
3018     char *realmname, *s;
3019     pthread_t clientth;
3020     
3021     if (!conf->dynamiclookupcommand)
3022         return;
3023
3024     /* create dynamic for the realm (string after last @, exit if nothing after @ */
3025     realmname = strrchr(id, '@');
3026     if (!realmname)
3027         return;
3028     realmname++;
3029     if (!*realmname)
3030         return;
3031     for (s = realmname; *s; s++)
3032         if (*s != '.' && *s != '-' && !isalnum((int)*s))
3033             return;
3034     
3035     pthread_mutex_lock(&realm->subrealms_mutex);
3036     /* exit if we now already got a matching subrealm */
3037     if (id2realm(realm->subrealms, id))
3038         goto exit;
3039     srvconf = malloc(sizeof(struct clsrvconf));
3040     if (!srvconf) {
3041         debug(DBG_ERR, "malloc failed");
3042         goto exit;
3043     }
3044     *srvconf = *conf;
3045     if (!addserver(srvconf))
3046         goto errexit;
3047
3048     if (!realm->subrealms)
3049         realm->subrealms = list_create();
3050     if (!realm->subrealms)
3051         goto errexit;
3052     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3053     if (!newrealm)
3054         goto errexit;
3055
3056     /* add server and accserver to newrealm */
3057     newrealm->srvconfs = list_create();
3058     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3059         debug(DBG_ERR, "malloc failed");
3060         goto errexit;
3061     }
3062     newrealm->accsrvconfs = list_create();
3063     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3064         debug(DBG_ERR, "malloc failed");
3065         goto errexit;
3066     }
3067
3068     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3069
3070     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3071         debug(DBG_ERR, "pthread_create failed");
3072         goto errexit;
3073     }
3074     pthread_detach(clientth);
3075     goto exit;
3076     
3077  errexit:
3078     if (newrealm) {
3079         list_removedata(realm->subrealms, newrealm);
3080         freerealm(newrealm);
3081         if (!list_first(realm->subrealms)) {
3082             list_destroy(realm->subrealms);
3083             realm->subrealms = NULL;
3084         }
3085     }
3086     freeserver(srvconf->servers, 1);
3087     free(srvconf);
3088     debug(DBG_ERR, "failed to create dynamic server");
3089
3090  exit:
3091     pthread_mutex_unlock(&realm->subrealms_mutex);
3092 }
3093
3094 int dynamicconfig(struct server *server) {
3095     int ok, fd[2], status;
3096     pid_t pid;
3097     struct clsrvconf *conf = server->conf;
3098     struct gconffile *cf = NULL;
3099     
3100     /* for now we only learn hostname/address */
3101     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3102
3103     if (pipe(fd) > 0) {
3104         debug(DBG_ERR, "dynamicconfig: pipe error");
3105         goto errexit;
3106     }
3107     pid = fork();
3108     if (pid < 0) {
3109         debug(DBG_ERR, "dynamicconfig: fork error");
3110         close(fd[0]);
3111         close(fd[1]);
3112         goto errexit;
3113     } else if (pid == 0) {
3114         /* child */
3115         close(fd[0]);
3116         if (fd[1] != STDOUT_FILENO) {
3117             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3118                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3119             close(fd[1]);
3120         }
3121         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3122             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3123     }
3124
3125     close(fd[1]);
3126     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3127     ok = getgenericconfig(&cf, NULL,
3128                           "Server", CONF_CBK, confserver_cb, (void *)conf,
3129                           NULL
3130                           );
3131     freegconf(&cf);
3132         
3133     if (waitpid(pid, &status, 0) < 0) {
3134         debug(DBG_ERR, "dynamicconfig: wait error");
3135         goto errexit;
3136     }
3137     
3138     if (status) {
3139         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3140         goto errexit;
3141     }
3142
3143     if (ok)
3144         return 1;
3145
3146  errexit:    
3147     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3148     return 0;
3149 }
3150
3151 int addmatchcertattr(struct clsrvconf *conf) {
3152     char *v;
3153     regex_t **r;
3154     
3155     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3156         r = &conf->certcnregex;
3157         v = conf->matchcertattr + 4;
3158     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3159         r = &conf->certuriregex;
3160         v = conf->matchcertattr + 20;
3161     } else
3162         return 0;
3163     if (!*v)
3164         return 0;
3165     /* regexp, remove optional trailing / if present */
3166     if (v[strlen(v) - 1] == '/')
3167         v[strlen(v) - 1] = '\0';
3168     if (!*v)
3169         return 0;
3170
3171     *r = malloc(sizeof(regex_t));
3172     if (!*r) {
3173         debug(DBG_ERR, "malloc failed");
3174         return 0;
3175     }
3176     if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3177         free(*r);
3178         *r = NULL;
3179         debug(DBG_ERR, "failed to compile regular expression %s", v);
3180         return 0;
3181     }
3182     return 1;
3183 }
3184
3185 int addrewriteattr(struct clsrvconf *conf) {
3186     char *v, *w;
3187     
3188     v = conf->rewriteattr + 11;
3189     if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3190         return 0;
3191     /* regexp, remove optional trailing / if present */
3192     if (v[strlen(v) - 1] == '/')
3193         v[strlen(v) - 1] = '\0';
3194
3195     w = strchr(v, '/');
3196     if (!*w)
3197         return 0;
3198     *w = '\0';
3199     w++;
3200     
3201     conf->rewriteattrregex = malloc(sizeof(regex_t));
3202     if (!conf->rewriteattrregex) {
3203         debug(DBG_ERR, "malloc failed");
3204         return 0;
3205     }
3206
3207     conf->rewriteattrreplacement = stringcopy(w, 0);
3208     if (!conf->rewriteattrreplacement) {
3209         free(conf->rewriteattrregex);
3210         conf->rewriteattrregex = NULL;
3211         return 0;
3212     }
3213     
3214     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3215         free(conf->rewriteattrregex);
3216         conf->rewriteattrregex = NULL;
3217         free(conf->rewriteattrreplacement);
3218         conf->rewriteattrreplacement = NULL;
3219         debug(DBG_ERR, "failed to compile regular expression %s", v);
3220         return 0;
3221     }
3222
3223     return 1;
3224 }
3225
3226 /* should accept both names and numeric values, only numeric right now */
3227 uint8_t attrname2val(char *attrname) {
3228     int val = 0;
3229     
3230     val = atoi(attrname);
3231     return val > 0 && val < 256 ? val : 0;
3232 }
3233
3234 /* should accept both names and numeric values, only numeric right now */
3235 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3236     char *s;
3237     
3238     *vendor = atoi(attrname);
3239     s = strchr(attrname, ':');
3240     if (!s) {
3241         *type = -1;
3242         return 1;
3243     }
3244     *type = atoi(s + 1);
3245     return *type >= 0 && *type < 256;
3246 }
3247
3248 struct rewrite *getrewrite(char *alt1, char *alt2) {
3249     struct list_node *entry;
3250     struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3251     
3252     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3253         r = (struct rewriteconf *)entry->data;
3254         if (!strcasecmp(r->name, alt1)) {
3255             r1 = r;
3256             break;
3257         }
3258         if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3259             r2 = r;
3260     }
3261
3262     r = (r1 ? r1 : r2);
3263     if (!r)
3264         return NULL;
3265     return r->rewrite;
3266 }
3267
3268 void addrewrite(char *value, char **attrs, char **vattrs) {
3269     struct rewriteconf *new;
3270     struct rewrite *rewrite = NULL;
3271     int i, n;
3272     uint8_t *a = NULL;
3273     uint32_t *p, *va = NULL;
3274
3275     if (attrs) {
3276         n = 0;
3277         for (; attrs[n]; n++);
3278         a = malloc((n + 1) * sizeof(uint8_t));
3279         if (!a)
3280             debugx(1, DBG_ERR, "malloc failed");
3281     
3282         for (i = 0; i < n; i++) {
3283             if (!(a[i] = attrname2val(attrs[i])))
3284                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3285             free(attrs[i]);
3286         }
3287         free(attrs);
3288         a[i] = 0;
3289     }
3290     
3291     if (vattrs) {
3292         n = 0;
3293         for (; vattrs[n]; n++);
3294         va = malloc((2 * n + 1) * sizeof(uint32_t));
3295         if (!va)
3296             debugx(1, DBG_ERR, "malloc failed");
3297     
3298         for (p = va, i = 0; i < n; i++, p += 2) {
3299             if (!vattrname2val(vattrs[i], p, p + 1))
3300                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3301             free(vattrs[i]);
3302         }
3303         free(vattrs);
3304         *p = 0;
3305     }
3306     
3307     if (a || va) {
3308         rewrite = malloc(sizeof(struct rewrite));
3309         if (!rewrite)
3310             debugx(1, DBG_ERR, "malloc failed");
3311         rewrite->removeattrs = a;
3312         rewrite->removevendorattrs = va;
3313     }
3314     
3315     new = malloc(sizeof(struct rewriteconf));
3316     if (!new || !list_push(rewriteconfs, new))
3317         debugx(1, DBG_ERR, "malloc failed");
3318
3319     memset(new, 0, sizeof(struct rewriteconf));
3320     new->name = stringcopy(value, 0);
3321     if (!new->name)
3322         debugx(1, DBG_ERR, "malloc failed");
3323         
3324     new->rewrite = rewrite;
3325     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3326 }
3327
3328 void freeclsrvconf(struct clsrvconf *conf) {
3329     free(conf->name);
3330     free(conf->conftype);
3331     free(conf->host);
3332     free(conf->port);
3333     free(conf->secret);
3334     free(conf->tls);
3335     free(conf->matchcertattr);
3336     if (conf->certcnregex)
3337         regfree(conf->certcnregex);
3338     if (conf->certuriregex)
3339         regfree(conf->certuriregex);
3340     free(conf->confrewrite);
3341     free(conf->rewriteattr);
3342     if (conf->rewriteattrregex)
3343         regfree(conf->rewriteattrregex);
3344     free(conf->rewriteattrreplacement);
3345     free(conf->dynamiclookupcommand);
3346     free(conf->rewrite);
3347     if (conf->addrinfo)
3348         freeaddrinfo(conf->addrinfo);
3349     /* not touching ssl_ctx, clients and servers */
3350     free(conf);
3351 }
3352
3353 int mergeconfstring(char **dst, char **src) {
3354     char *t;
3355     
3356     if (*src) {
3357         *dst = *src;
3358         *src = NULL;
3359         return 1;
3360     }
3361     if (*dst) {
3362         t = stringcopy(*dst, 0);
3363         if (!t) {
3364             debug(DBG_ERR, "malloc failed");
3365             return 0;
3366         }
3367         *dst = t;
3368     }
3369     return 1;
3370 }
3371
3372 /* assumes dst is a shallow copy */
3373 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3374     if (!mergeconfstring(&dst->name, &src->name) ||
3375         !mergeconfstring(&dst->conftype, &src->conftype) ||
3376         !mergeconfstring(&dst->host, &src->host) ||
3377         !mergeconfstring(&dst->port, &src->port) ||
3378         !mergeconfstring(&dst->secret, &src->secret) ||
3379         !mergeconfstring(&dst->tls, &src->tls) ||
3380         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3381         !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3382         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3383         return 0;
3384     dst->statusserver = src->statusserver;
3385     dst->certnamecheck = src->certnamecheck;
3386     if (src->retrydelay != 255)
3387         dst->retrydelay = src->retrydelay;
3388     if (src->retrycount != 255)
3389         dst->retrycount = src->retrycount;
3390     return 1;
3391 }
3392                    
3393 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3394     struct clsrvconf *conf;
3395     
3396     debug(DBG_DBG, "confclient_cb called for %s", block);
3397
3398     conf = malloc(sizeof(struct clsrvconf));
3399     if (!conf || !list_push(clconfs, conf))
3400         debugx(1, DBG_ERR, "malloc failed");
3401     memset(conf, 0, sizeof(struct clsrvconf));
3402     conf->certnamecheck = 1;
3403     
3404     if (!getgenericconfig(cf, block,
3405                      "type", CONF_STR, &conf->conftype,
3406                      "host", CONF_STR, &conf->host,
3407                      "secret", CONF_STR, &conf->secret,
3408                      "tls", CONF_STR, &conf->tls,
3409                      "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3410                      "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3411                      "rewrite", CONF_STR, &conf->confrewrite,
3412                      "rewriteattribute", CONF_STR, &conf->rewriteattr,
3413                      NULL
3414                           ))
3415         debugx(1, DBG_ERR, "configuration error");
3416     
3417     conf->name = stringcopy(val, 0);
3418     if (!conf->host)
3419         conf->host = stringcopy(val, 0);
3420     
3421     if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3422         conf->type = 'U';
3423         client_udp_count++;
3424     } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3425         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3426         if (!conf->ssl_ctx)
3427             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3428         if (conf->matchcertattr && !addmatchcertattr(conf))
3429             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3430         conf->type = 'T';
3431         client_tls_count++;
3432     } else
3433         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3434     
3435     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3436     
3437     if (conf->rewriteattr) {
3438         if (!addrewriteattr(conf))
3439             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3440     }
3441     
3442     if (!resolvepeer(conf, 0))
3443         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3444     
3445     if (!conf->secret) {
3446         if (conf->type == 'U')
3447             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3448         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3449     }
3450     return 1;
3451 }
3452
3453 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3454     switch (conf->type) {
3455     case 'U':
3456         if (!conf->port)
3457             conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3458         break;
3459     case 'T':
3460         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3461         if (!conf->ssl_ctx) {
3462             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3463             return 0;
3464         }
3465         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3466             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3467             return 0;
3468         }
3469         if (!conf->port)
3470             conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3471         break;
3472     }
3473
3474     if (conf->retrydelay == 255)
3475         conf->retrydelay = REQUEST_RETRY_DELAY;
3476     if (conf->retrycount == 255)
3477         conf->retrycount = REQUEST_RETRY_COUNT;
3478     
3479     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3480     
3481     if (!conf->secret) {
3482         if (conf->type == 'U')
3483             debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3484         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3485         if (!conf->secret) {
3486             debug(DBG_ERR, "malloc failed");
3487             return 0;
3488         }
3489     }
3490     
3491     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3492         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3493         return 0;
3494     }
3495     return 1;
3496 }
3497                         
3498 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3499     struct clsrvconf *conf, *resconf;
3500     long int retrydelay = LONG_MIN, retrycount = LONG_MIN;
3501     
3502     debug(DBG_DBG, "confserver_cb called for %s", block);
3503
3504     conf = malloc(sizeof(struct clsrvconf));
3505     if (!conf) {
3506         debug(DBG_ERR, "malloc failed");
3507         return 0;
3508     }
3509     memset(conf, 0, sizeof(struct clsrvconf));
3510     resconf = (struct clsrvconf *)arg;
3511     if (resconf) {
3512         conf->statusserver = resconf->statusserver;
3513         conf->certnamecheck = resconf->certnamecheck;
3514     } else
3515         conf->certnamecheck = 1;
3516
3517     if (!getgenericconfig(cf, block,
3518                           "type", CONF_STR, &conf->conftype,
3519                           "host", CONF_STR, &conf->host,
3520                           "port", CONF_STR, &conf->port,
3521                           "secret", CONF_STR, &conf->secret,
3522                           "tls", CONF_STR, &conf->tls,
3523                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3524                           "rewrite", CONF_STR, &conf->confrewrite,
3525                           "StatusServer", CONF_BLN, &conf->statusserver,
3526                           "RetryDelay", CONF_LINT, &retrydelay,
3527                           "RetryCount", CONF_LINT, &retrycount,
3528                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3529                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3530                           NULL
3531                           )) {
3532         debug(DBG_ERR, "configuration error");
3533         goto errexit;
3534     }
3535     
3536     conf->name = stringcopy(val, 0);
3537     if (!conf->name) {
3538         debug(DBG_ERR, "malloc failed");
3539         goto errexit;
3540     }
3541     if (!conf->host) {
3542         conf->host = stringcopy(val, 0);
3543         if (!conf->host) {
3544             debug(DBG_ERR, "malloc failed");
3545             goto errexit;
3546         }
3547     }
3548     
3549     if (retrydelay != LONG_MIN) {
3550         if (retrydelay < 1 || retrydelay > 60) {
3551             debug(DBG_ERR, "error in block %s, value of option RetryDelay is %d, must be 1-60", block, retrydelay);
3552             goto errexit;
3553         }
3554         conf->retrydelay = (uint8_t)retrydelay;
3555     } else
3556         conf->retrydelay = 255;
3557     
3558     if (retrycount != LONG_MIN) {
3559         if (retrycount < 0 || retrycount > 10) {
3560             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
3561             goto errexit;
3562         }
3563         conf->retrycount = (uint8_t)retrycount;
3564     } else
3565         conf->retrycount = 255;
3566     
3567     if (resconf) {
3568         if (!mergesrvconf(resconf, conf))
3569             goto errexit;
3570         free(conf);
3571         conf = resconf;
3572         if (conf->dynamiclookupcommand) {
3573             free(conf->dynamiclookupcommand);
3574             conf->dynamiclookupcommand = NULL;
3575         }
3576     }
3577
3578     if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3579         conf->type = 'U';
3580     else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3581         conf->type = 'T';
3582     else {
3583         debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3584         goto errexit;
3585     }
3586     
3587     if (resconf || !conf->dynamiclookupcommand) {
3588         if (!compileserverconfig(conf, block))
3589             goto errexit;
3590     }
3591     
3592     if (resconf)
3593         return 1;
3594         
3595     switch (conf->type) {
3596     case 'U':
3597         server_udp_count++;
3598         break;
3599     case 'T':
3600         server_tls_count++;
3601         break;
3602     default:
3603         goto errexit;
3604     }
3605     
3606     if (!list_push(srvconfs, conf)) {
3607         debug(DBG_ERR, "malloc failed");
3608         goto errexit;
3609     }
3610     return 1;
3611
3612  errexit:    
3613     freeclsrvconf(conf);
3614     return 0;
3615 }
3616
3617 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3618     char **servers = NULL, **accservers = NULL, *msg = NULL;
3619     uint8_t accresp = 0;
3620     
3621     debug(DBG_DBG, "confrealm_cb called for %s", block);
3622     
3623     if (!getgenericconfig(cf, block,
3624                      "server", CONF_MSTR, &servers,
3625                      "accountingServer", CONF_MSTR, &accservers,
3626                      "ReplyMessage", CONF_STR, &msg,
3627                      "AccountingResponse", CONF_BLN, &accresp,
3628                      NULL
3629                           ))
3630         debugx(1, DBG_ERR, "configuration error");
3631
3632     addrealm(realms, val, servers, accservers, msg, accresp);
3633     return 1;
3634 }
3635
3636 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3637     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3638     
3639     debug(DBG_DBG, "conftls_cb called for %s", block);
3640     
3641     if (!getgenericconfig(cf, block,
3642                      "CACertificateFile", CONF_STR, &cacertfile,
3643                      "CACertificatePath", CONF_STR, &cacertpath,
3644                      "CertificateFile", CONF_STR, &certfile,
3645                      "CertificateKeyFile", CONF_STR, &certkeyfile,
3646                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
3647                      NULL
3648                           ))
3649         debugx(1, DBG_ERR, "configuration error");
3650     
3651     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
3652     free(cacertfile);
3653     free(cacertpath);
3654     free(certfile);
3655     free(certkeyfile);
3656     free(certkeypwd);
3657     return 1;
3658 }
3659
3660 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3661     char **attrs = NULL, **vattrs = NULL;
3662     
3663     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3664     
3665     if (!getgenericconfig(cf, block,
3666                      "removeAttribute", CONF_MSTR, &attrs,
3667                      "removeVendorAttribute", CONF_MSTR, &vattrs,
3668                      NULL
3669                           ))
3670         debugx(1, DBG_ERR, "configuration error");
3671     addrewrite(val, attrs, vattrs);
3672     return 1;
3673 }
3674
3675 void getmainconfig(const char *configfile) {
3676     long int loglevel = LONG_MIN;
3677     struct gconffile *cfs;
3678
3679     cfs = openconfigfile(configfile);
3680     memset(&options, 0, sizeof(options));
3681     
3682     clconfs = list_create();
3683     if (!clconfs)
3684         debugx(1, DBG_ERR, "malloc failed");
3685     
3686     srvconfs = list_create();
3687     if (!srvconfs)
3688         debugx(1, DBG_ERR, "malloc failed");
3689     
3690     realms = list_create();
3691     if (!realms)
3692         debugx(1, DBG_ERR, "malloc failed");    
3693  
3694     tlsconfs = list_create();
3695     if (!tlsconfs)
3696         debugx(1, DBG_ERR, "malloc failed");
3697     
3698     rewriteconfs = list_create();
3699     if (!rewriteconfs)
3700         debugx(1, DBG_ERR, "malloc failed");    
3701  
3702     if (!getgenericconfig(&cfs, NULL,
3703                           "ListenUDP", CONF_STR, &options.listenudp,
3704                           "ListenTCP", CONF_STR, &options.listentcp,
3705                           "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3706                           "SourceUDP", CONF_STR, &options.sourceudp,
3707                           "SourceTCP", CONF_STR, &options.sourcetcp,
3708                           "LogLevel", CONF_LINT, &loglevel,
3709                           "LogDestination", CONF_STR, &options.logdestination,
3710                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3711                           "Client", CONF_CBK, confclient_cb, NULL,
3712                           "Server", CONF_CBK, confserver_cb, NULL,
3713                           "Realm", CONF_CBK, confrealm_cb, NULL,
3714                           "TLS", CONF_CBK, conftls_cb, NULL,
3715                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3716                           NULL
3717                           ))
3718         debugx(1, DBG_ERR, "configuration error");
3719     
3720     if (loglevel != LONG_MIN) {
3721         if (loglevel < 1 || loglevel > 4)
3722             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3723         options.loglevel = (uint8_t)loglevel;
3724     }
3725 }
3726
3727 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3728     int c;
3729
3730     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3731         switch (c) {
3732         case 'c':
3733             *configfile = optarg;
3734             break;
3735         case 'd':
3736             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3737                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3738             *loglevel = *optarg - '0';
3739             break;
3740         case 'f':
3741             *foreground = 1;
3742             break;
3743         case 'p':
3744             *pretend = 1;
3745             break;
3746         case 'v':
3747                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3748         default:
3749             goto usage;
3750         }
3751     }
3752     if (!(argc - optind))
3753         return;
3754
3755  usage:
3756     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3757 }
3758
3759 #ifdef SYS_SOLARIS9
3760 int daemon(int a, int b) {
3761     int i;
3762
3763     if (fork())
3764         exit(0);
3765
3766     setsid();
3767
3768     for (i = 0; i < 3; i++) {
3769         close(i);
3770         open("/dev/null", O_RDWR);
3771     }
3772     return 1;
3773 }
3774 #endif
3775
3776 void *sighandler(void *arg) {
3777     sigset_t sigset;
3778     int sig;
3779
3780     for(;;) {
3781         sigemptyset(&sigset);
3782         sigaddset(&sigset, SIGPIPE);
3783         sigwait(&sigset, &sig);
3784         /* only get SIGPIPE right now, so could simplify below code */
3785         switch (sig) {
3786         case 0:
3787             /* completely ignoring this */
3788             break;
3789         case SIGPIPE:
3790             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3791             break;
3792         default:
3793             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3794         }
3795     }
3796 }
3797
3798 int main(int argc, char **argv) {
3799     pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3800     sigset_t sigset;
3801     struct list_node *entry;
3802     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3803     char *configfile = NULL;
3804     struct clsrvconf *srvconf;
3805     
3806     debug_init("radsecproxy");
3807     debug_set_level(DEBUG_LEVEL);
3808     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3809     if (loglevel)
3810         debug_set_level(loglevel);
3811     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3812     if (loglevel)
3813         options.loglevel = loglevel;
3814     else if (options.loglevel)
3815         debug_set_level(options.loglevel);
3816     if (!foreground)
3817         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3818     free(options.logdestination);
3819
3820     if (!list_first(clconfs))
3821         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3822     if (!list_first(srvconfs))
3823         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3824     if (!list_first(realms))
3825         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3826
3827     if (pretend)
3828         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3829
3830     if (!foreground && (daemon(0, 0) < 0))
3831         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3832     
3833     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3834
3835     sigemptyset(&sigset);
3836     /* exit on all but SIGPIPE, ignore more? */
3837     sigaddset(&sigset, SIGPIPE);
3838     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3839     pthread_create(&sigth, NULL, sighandler, NULL);
3840     
3841     if (client_udp_count) {
3842         udp_server_replyq = newreplyq();
3843         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3844             debugx(1, DBG_ERR, "pthread_create failed");
3845         if (options.listenaccudp)
3846             if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3847                 debugx(1, DBG_ERR, "pthread_create failed");
3848     }
3849     
3850     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3851         srvconf = (struct clsrvconf *)entry->data;
3852         if (srvconf->dynamiclookupcommand)
3853             continue;
3854         if (!addserver(srvconf))
3855             debugx(1, DBG_ERR, "failed to add server");
3856         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3857                            (void *)(srvconf->servers)))
3858             debugx(1, DBG_ERR, "pthread_create failed");
3859     }
3860     /* srcudpres no longer needed, while srctcpres is needed later */
3861     if (srcudpres) {
3862         freeaddrinfo(srcudpres);
3863         srcudpres = NULL;
3864     }
3865     if (udp_client4_sock >= 0)
3866         if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3867             debugx(1, DBG_ERR, "pthread_create failed");
3868     if (udp_client6_sock >= 0)
3869         if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3870             debugx(1, DBG_ERR, "pthread_create failed");
3871     
3872     if (client_tls_count)
3873         return tlslistener();
3874     
3875     /* just hang around doing nothing, anything to do here? */
3876     for (;;)
3877         sleep(1000);
3878 }