including limits.h
[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         }
2081         goto exit;
2082     }
2083     
2084     if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2085         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2086               rq->from->conf->name, to->conf->name);
2087         goto exit;
2088     }
2089
2090     if (rqinqueue(to, rq->from, id, code)) {
2091         debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2092               radmsgtype2string(code), rq->from->conf->host, id);
2093         goto exit;
2094     }
2095     
2096     if (code != RAD_Accounting_Request) {
2097         if (!RAND_bytes(newauth, 16)) {
2098             debug(DBG_WARN, "radsrv: failed to generate random auth");
2099             goto exit;
2100         }
2101     }
2102
2103 #ifdef DEBUG
2104     printfchars(NULL, "auth", "%02x ", auth, 16);
2105 #endif
2106
2107     attr = attrget(attrs, len, RAD_Attr_User_Password);
2108     if (attr) {
2109         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2110         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2111             goto exit;
2112     }
2113     
2114     attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2115     if (attr) {
2116         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2117         if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2118             goto exit;
2119     }
2120
2121     rq->origid = id;
2122     memcpy(rq->origauth, auth, 16);
2123     if (code == RAD_Accounting_Request) {
2124         if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
2125             debug(DBG_WARN, "radsrv: failed to sign Accounting-Request message");
2126             goto exit;
2127         }
2128     } else
2129         memcpy(auth, newauth, 16);
2130     sendrq(to, rq);
2131     return;
2132     
2133  exit:
2134     freerqdata(rq);
2135 }
2136
2137 int replyh(struct server *server, unsigned char *buf) {
2138     struct client *from;
2139     struct request *rq;
2140     int i, len, sublen;
2141     unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2142     struct sockaddr_storage fromsa;
2143     char tmp[760], stationid[760];
2144     
2145     server->connectionok = 1;
2146     server->lostrqs = 0;
2147         
2148     i = buf[1]; /* i is the id */
2149
2150     if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2151         && *buf != RAD_Accounting_Response) {
2152         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2153         return 0;
2154     }
2155     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2156
2157     rq = server->requests + i;
2158
2159     pthread_mutex_lock(&server->newrq_mutex);
2160     if (!rq->buf || !rq->tries) {
2161         pthread_mutex_unlock(&server->newrq_mutex);
2162         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2163         return 0;
2164     }
2165
2166     if (rq->received) {
2167         pthread_mutex_unlock(&server->newrq_mutex);
2168         debug(DBG_INFO, "replyh: already received, ignoring reply");
2169         return 0;
2170     }
2171         
2172     if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2173         pthread_mutex_unlock(&server->newrq_mutex);
2174         debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2175         return 0;
2176     }
2177         
2178     len = RADLEN(buf) - 20;
2179     attrs = buf + 20;
2180
2181     if (!attrvalidate(attrs, len)) {
2182         pthread_mutex_unlock(&server->newrq_mutex);
2183         debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2184         return 0;
2185     }
2186         
2187     /* Message Authenticator */
2188     messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2189     if (messageauth) {
2190         if (ATTRVALLEN(messageauth) != 16) {
2191             pthread_mutex_unlock(&server->newrq_mutex);
2192             debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2193             return 0;
2194         }
2195         memcpy(tmp, buf + 4, 16);
2196         memcpy(buf + 4, rq->buf + 4, 16);
2197         if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2198             pthread_mutex_unlock(&server->newrq_mutex);
2199             debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2200             return 0;
2201         }
2202         memcpy(buf + 4, tmp, 16);
2203         debug(DBG_DBG, "replyh: message auth ok");
2204     }
2205         
2206     if (*rq->buf == RAD_Status_Server) {
2207         rq->received = 1;
2208         pthread_mutex_unlock(&server->newrq_mutex);
2209         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2210         return 0;
2211     }
2212
2213     gettimeofday(&server->lastreply, NULL);
2214     
2215     from = rq->from;
2216     if (!from) {
2217         pthread_mutex_unlock(&server->newrq_mutex);
2218         debug(DBG_INFO, "replyh: client gone, ignoring reply");
2219         return 0;
2220     }
2221         
2222     if (server->conf->rewrite) {
2223         dorewrite(buf, server->conf->rewrite);
2224         len = RADLEN(buf) - 20;
2225     }
2226     
2227     /* MS MPPE */
2228     for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2229         if (ATTRVALLEN(attr) <= 4)
2230             break;
2231             
2232         if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55)  /* 311 == MS */
2233             continue;
2234             
2235         sublen = ATTRVALLEN(attr) - 4;
2236         subattrs = ATTRVAL(attr) + 4;  
2237         if (!attrvalidate(subattrs, sublen) ||
2238             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2239                     rq, server->conf->secret, from->conf->secret) ||
2240             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2241                     rq, server->conf->secret, from->conf->secret))
2242             break;
2243     }
2244     if (attr) {
2245         pthread_mutex_unlock(&server->newrq_mutex);
2246         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2247         return 0;
2248     }
2249         
2250     if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2251         attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2252         if (attr) {
2253             radattr2ascii(tmp, sizeof(tmp), attr);
2254             attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2255             if (attr) {
2256                 radattr2ascii(stationid, sizeof(stationid), attr);
2257                 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2258                       radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2259             } else
2260                 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2261         }
2262     }
2263         
2264     buf[1] = (char)rq->origid;
2265     memcpy(buf + 4, rq->origauth, 16);
2266 #ifdef DEBUG    
2267     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2268 #endif
2269
2270     if (rq->origusername) {
2271         username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2272         if (!username) {
2273             pthread_mutex_unlock(&server->newrq_mutex);
2274             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2275             return 0;
2276         }
2277         memcpy(username, rq->origusername, strlen(rq->origusername));
2278         len = RADLEN(buf) - 20;
2279         attrs = buf + 20;
2280         if (messageauth)
2281             messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2282     }
2283         
2284     if (messageauth) {
2285         if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2286             pthread_mutex_unlock(&server->newrq_mutex);
2287             debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2288             return 0;
2289         }
2290         debug(DBG_DBG, "replyh: computed messageauthattr");
2291     }
2292
2293     if (from->conf->type == 'U')
2294         fromsa = rq->fromsa;
2295     /* once we set received = 1, rq may be reused */
2296     rq->received = 1;
2297
2298     debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2299     sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2300     pthread_mutex_unlock(&server->newrq_mutex);
2301     return 1;
2302 }
2303
2304 void *udpclientrd(void *arg) {
2305     struct server *server;
2306     unsigned char *buf;
2307     int *s = (int *)arg;
2308     
2309     for (;;) {
2310         server = NULL;
2311         buf = radudpget(*s, NULL, &server, NULL);
2312         if (!replyh(server, buf))
2313             free(buf);
2314     }
2315 }
2316
2317 void *tlsclientrd(void *arg) {
2318     struct server *server = (struct server *)arg;
2319     unsigned char *buf;
2320     struct timeval now, lastconnecttry;
2321     
2322     for (;;) {
2323         /* yes, lastconnecttry is really necessary */
2324         lastconnecttry = server->lastconnecttry;
2325         buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2326         if (!buf) {
2327             if (server->dynamiclookuparg)
2328                 break;
2329             tlsconnect(server, &lastconnecttry, 0, "clientrd");
2330             continue;
2331         }
2332
2333         if (!replyh(server, buf))
2334             free(buf);
2335         if (server->dynamiclookuparg) {
2336             gettimeofday(&now, NULL);
2337             if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2338                 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2339                 break;
2340             }
2341         }
2342     }
2343     server->clientrdgone = 1;
2344     return NULL;
2345 }
2346
2347 /* code for removing state not finished */
2348 void *clientwr(void *arg) {
2349     struct server *server = (struct server *)arg;
2350     struct request *rq;
2351     pthread_t tlsclientrdth;
2352     int i, dynconffail = 0;
2353     uint8_t rnd;
2354     struct timeval now, lastsend;
2355     struct timespec timeout;
2356     struct request statsrvrq;
2357     unsigned char statsrvbuf[38];
2358     struct clsrvconf *conf;
2359     
2360     conf = server->conf;
2361     
2362     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2363         dynconffail = 1;
2364         goto errexit;
2365     }
2366     
2367     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2368         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2369         goto errexit;
2370     }
2371
2372     memset(&timeout, 0, sizeof(struct timespec));
2373     
2374     if (conf->statusserver) {
2375         memset(&statsrvrq, 0, sizeof(struct request));
2376         memset(statsrvbuf, 0, sizeof(statsrvbuf));
2377         statsrvbuf[0] = RAD_Status_Server;
2378         statsrvbuf[3] = 38;
2379         statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2380         statsrvbuf[21] = 18;
2381         gettimeofday(&lastsend, NULL);
2382     }
2383     
2384     if (conf->type == 'U') {
2385         server->connectionok = 1;
2386     } else {
2387         if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2388             goto errexit;
2389         server->connectionok = 1;
2390         if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2391             debug(DBG_ERR, "clientwr: pthread_create failed");
2392             goto errexit;
2393         }
2394     }
2395
2396     for (;;) {
2397         pthread_mutex_lock(&server->newrq_mutex);
2398         if (!server->newrq) {
2399             gettimeofday(&now, NULL);
2400             /* random 0-7 seconds */
2401             RAND_bytes(&rnd, 1);
2402             rnd /= 32;
2403             if (conf->statusserver) {
2404                 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2405                     timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2406             } else {
2407                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2408                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2409             }
2410 #if 0       
2411             if (timeout.tv_sec > now.tv_sec)
2412                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2413 #endif      
2414             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2415             timeout.tv_sec = 0;
2416         }
2417         if (server->newrq) {
2418             debug(DBG_DBG, "clientwr: got new request");
2419             server->newrq = 0;
2420         }
2421 #if 0   
2422         else
2423             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2424 #endif  
2425         pthread_mutex_unlock(&server->newrq_mutex);
2426
2427         for (i = 0; i < MAX_REQUESTS; i++) {
2428             if (server->clientrdgone) {
2429                 pthread_join(tlsclientrdth, NULL);
2430                 goto errexit;
2431             }
2432             pthread_mutex_lock(&server->newrq_mutex);
2433             while (i < MAX_REQUESTS && !server->requests[i].buf)
2434                 i++;
2435             if (i == MAX_REQUESTS) {
2436                 pthread_mutex_unlock(&server->newrq_mutex);
2437                 break;
2438             }
2439             rq = server->requests + i;
2440
2441             if (rq->received) {
2442                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2443                 if (rq->buf) {
2444                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2445                     freerqdata(rq);
2446                     /* setting this to NULL means that it can be reused */
2447                     rq->buf = NULL;
2448                 }
2449                 pthread_mutex_unlock(&server->newrq_mutex);
2450                 continue;
2451             }
2452             
2453             gettimeofday(&now, NULL);
2454             if (now.tv_sec < rq->expiry.tv_sec) {
2455                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2456                     timeout.tv_sec = rq->expiry.tv_sec;
2457                 pthread_mutex_unlock(&server->newrq_mutex);
2458                 continue;
2459             }
2460
2461             if (rq->tries == (*rq->buf == RAD_Status_Server || conf->type == 'T'
2462                               ? 1 : conf->retrycount + 1)) {
2463                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2464                 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2465                 if (server->lostrqs < 255)
2466                     server->lostrqs++;
2467                 freerqdata(rq);
2468                 /* setting this to NULL means that it can be reused */
2469                 rq->buf = NULL;
2470                 pthread_mutex_unlock(&server->newrq_mutex);
2471                 continue;
2472             }
2473             pthread_mutex_unlock(&server->newrq_mutex);
2474
2475             rq->expiry.tv_sec = now.tv_sec +
2476                 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2477                  ? conf->retrydelay * (conf->retrycount + 1) : conf->retrydelay);
2478             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2479                 timeout.tv_sec = rq->expiry.tv_sec;
2480             rq->tries++;
2481             clientradput(server, server->requests[i].buf);
2482             gettimeofday(&lastsend, NULL);
2483         }
2484         if (conf->statusserver) {
2485             gettimeofday(&now, NULL);
2486             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2487                 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2488                     debug(DBG_WARN, "clientwr: failed to generate random auth");
2489                     continue;
2490                 }
2491                 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2492                 if (!statsrvrq.buf) {
2493                     debug(DBG_ERR, "clientwr: malloc failed");
2494                     continue;
2495                 }
2496                 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2497                 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2498                 lastsend.tv_sec = now.tv_sec;
2499                 sendrq(server, &statsrvrq);
2500             }
2501         }
2502     }
2503  errexit:
2504     conf->servers = NULL;
2505     if (server->dynamiclookuparg) {
2506         removeserversubrealms(realms, conf);
2507         if (dynconffail)
2508             free(conf);
2509         else
2510             freeclsrvconf(conf);
2511     }
2512     freeserver(server, 1);
2513     return NULL;
2514 }
2515
2516 void *udpserverwr(void *arg) {
2517     struct replyq *replyq = udp_server_replyq;
2518     struct reply *reply;
2519     
2520     for (;;) {
2521         pthread_mutex_lock(&replyq->mutex);
2522         while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2523             debug(DBG_DBG, "udp server writer, waiting for signal");
2524             pthread_cond_wait(&replyq->cond, &replyq->mutex);
2525             debug(DBG_DBG, "udp server writer, got signal");
2526         }
2527         pthread_mutex_unlock(&replyq->mutex);
2528
2529         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2530                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2531             debug(DBG_WARN, "sendudp: send failed");
2532         free(reply->buf);
2533         free(reply);
2534     }
2535 }
2536
2537 void *udpserverrd(void *arg) {
2538     struct request rq;
2539     pthread_t udpserverwrth;
2540     struct clsrvconf *listenres;
2541
2542     listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2543     if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2544         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2545
2546     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2547           listenres->host ? listenres->host : "*", listenres->port);
2548     freeclsrvres(listenres);
2549     
2550     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2551         debugx(1, DBG_ERR, "pthread_create failed");
2552     
2553     for (;;) {
2554         memset(&rq, 0, sizeof(struct request));
2555         rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2556         radsrv(&rq);
2557     }
2558 }
2559
2560 void *udpaccserverrd(void *arg) {
2561     struct request rq;
2562     struct clsrvconf *listenres;
2563     
2564     listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2565     if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2566         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2567
2568     debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2569           listenres->host ? listenres->host : "*", listenres->port);
2570     freeclsrvres(listenres);
2571     
2572     for (;;) {
2573         memset(&rq, 0, sizeof(struct request));
2574         rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2575         if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2576             radsrv(&rq);
2577             continue;
2578         }
2579         debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2580         freerqdata(&rq);
2581     }
2582 }
2583
2584 void *tlsserverwr(void *arg) {
2585     int cnt;
2586     unsigned long error;
2587     struct client *client = (struct client *)arg;
2588     struct replyq *replyq;
2589     struct reply *reply;
2590     
2591     debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2592     replyq = client->replyq;
2593     for (;;) {
2594         pthread_mutex_lock(&replyq->mutex);
2595         while (!list_first(replyq->replies)) {
2596             if (client->ssl) {      
2597                 debug(DBG_DBG, "tls server writer, waiting for signal");
2598                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2599                 debug(DBG_DBG, "tls server writer, got signal");
2600             }
2601             if (!client->ssl) {
2602                 /* ssl might have changed while waiting */
2603                 pthread_mutex_unlock(&replyq->mutex);
2604                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2605                 pthread_exit(NULL);
2606             }
2607         }
2608         reply = (struct reply *)list_shift(replyq->replies);
2609         pthread_mutex_unlock(&replyq->mutex);
2610         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2611         if (cnt > 0)
2612             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2613                   cnt, RADLEN(reply->buf));
2614         else
2615             while ((error = ERR_get_error()))
2616                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2617         free(reply->buf);
2618         free(reply);
2619     }
2620 }
2621
2622 void tlsserverrd(struct client *client) {
2623     struct request rq;
2624     pthread_t tlsserverwrth;
2625     
2626     debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2627     
2628     if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2629         debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2630         return;
2631     }
2632
2633     for (;;) {
2634         memset(&rq, 0, sizeof(struct request));
2635         rq.buf = radtlsget(client->ssl, 0);
2636         if (!rq.buf)
2637             break;
2638         debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2639         rq.from = client;
2640         radsrv(&rq);
2641     }
2642     
2643     debug(DBG_ERR, "tlsserverrd: connection lost");
2644     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2645     client->ssl = NULL;
2646     pthread_mutex_lock(&client->replyq->mutex);
2647     pthread_cond_signal(&client->replyq->cond);
2648     pthread_mutex_unlock(&client->replyq->mutex);
2649     debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2650     pthread_join(tlsserverwrth, NULL);
2651     removeclientrqs(client);
2652     debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2653 }
2654
2655 void *tlsservernew(void *arg) {
2656     int s;
2657     struct sockaddr_storage from;
2658     size_t fromlen = sizeof(from);
2659     struct clsrvconf *conf;
2660     struct list_node *cur = NULL;
2661     SSL *ssl = NULL;
2662     X509 *cert = NULL;
2663     unsigned long error;
2664     struct client *client;
2665
2666     s = *(int *)arg;
2667     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2668         debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2669         goto exit;
2670     }
2671     debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2672
2673     conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2674     if (conf) {
2675         ssl = SSL_new(conf->ssl_ctx);
2676         SSL_set_fd(ssl, s);
2677
2678         if (SSL_accept(ssl) <= 0) {
2679             while ((error = ERR_get_error()))
2680                 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2681             debug(DBG_ERR, "SSL_accept failed");
2682             goto exit;
2683         }
2684         cert = verifytlscert(ssl);
2685         if (!cert)
2686             goto exit;
2687     }
2688     
2689     while (conf) {
2690         if (verifyconfcert(cert, conf)) {
2691             X509_free(cert);
2692             client = addclient(conf);
2693             if (client) {
2694                 client->ssl = ssl;
2695                 tlsserverrd(client);
2696                 removeclient(client);
2697             } else
2698                 debug(DBG_WARN, "Failed to create new client instance");
2699             goto exit;
2700         }
2701         conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2702     }
2703     debug(DBG_WARN, "ignoring request, no matching TLS client");
2704     if (cert)
2705         X509_free(cert);
2706
2707  exit:
2708     SSL_free(ssl);
2709     shutdown(s, SHUT_RDWR);
2710     close(s);
2711     pthread_exit(NULL);
2712 }
2713
2714 int tlslistener() {
2715     pthread_t tlsserverth;
2716     int s, snew;
2717     struct sockaddr_storage from;
2718     size_t fromlen = sizeof(from);
2719     struct clsrvconf *listenres;
2720
2721     listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2722     if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2723         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2724
2725     debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2726     freeclsrvres(listenres);
2727     listen(s, 0);
2728
2729     for (;;) {
2730         snew = accept(s, (struct sockaddr *)&from, &fromlen);
2731         if (snew < 0) {
2732             debug(DBG_WARN, "accept failed");
2733             continue;
2734         }
2735         if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2736             debug(DBG_ERR, "tlslistener: pthread_create failed");
2737             shutdown(snew, SHUT_RDWR);
2738             close(snew);
2739             continue;
2740         }
2741         pthread_detach(tlsserverth);
2742     }
2743     return 0;
2744 }
2745
2746 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2747     struct tls *new;
2748     SSL_CTX *ctx;
2749     STACK_OF(X509_NAME) *calist;
2750     int i;
2751     unsigned long error;
2752     
2753     if (!certfile || !certkeyfile)
2754         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2755
2756     if (!cacertfile && !cacertpath)
2757         debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2758
2759     if (!ssl_locks) {
2760         ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2761         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2762         for (i = 0; i < CRYPTO_num_locks(); i++) {
2763             ssl_lock_count[i] = 0;
2764             pthread_mutex_init(&ssl_locks[i], NULL);
2765         }
2766         CRYPTO_set_id_callback(ssl_thread_id);
2767         CRYPTO_set_locking_callback(ssl_locking_callback);
2768
2769         SSL_load_error_strings();
2770         SSL_library_init();
2771
2772         while (!RAND_status()) {
2773             time_t t = time(NULL);
2774             pid_t pid = getpid();
2775             RAND_seed((unsigned char *)&t, sizeof(time_t));
2776             RAND_seed((unsigned char *)&pid, sizeof(pid));
2777         }
2778     }
2779     ctx = SSL_CTX_new(TLSv1_method());
2780     if (certkeypwd) {
2781         SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2782         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2783     }
2784     if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2785         !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2786         !SSL_CTX_check_private_key(ctx) ||
2787         !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2788         while ((error = ERR_get_error()))
2789             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2790         debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2791     }
2792
2793     calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2794     if (!cacertfile || calist) {
2795         if (cacertpath) {
2796             if (!calist)
2797                 calist = sk_X509_NAME_new_null();
2798             if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2799                 sk_X509_NAME_free(calist);
2800                 calist = NULL;
2801             }
2802         }
2803     }
2804     if (!calist) {
2805         while ((error = ERR_get_error()))
2806             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2807         debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2808     }
2809     SSL_CTX_set_client_CA_list(ctx, calist);
2810     
2811     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2812     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2813
2814     new = malloc(sizeof(struct tls));
2815     if (!new || !list_push(tlsconfs, new))
2816         debugx(1, DBG_ERR, "malloc failed");
2817
2818     memset(new, 0, sizeof(struct tls));
2819     new->name = stringcopy(value, 0);
2820     if (!new->name)
2821         debugx(1, DBG_ERR, "malloc failed");
2822     new->ctx = ctx;
2823     debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2824 }
2825
2826 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2827     struct list_node *entry;
2828     struct tls *t, *t1 = NULL, *t2 = NULL;
2829     
2830     for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2831         t = (struct tls *)entry->data;
2832         if (!strcasecmp(t->name, alt1)) {
2833             t1 = t;
2834             break;
2835         }
2836         if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2837             t2 = t;
2838     }
2839
2840     t = (t1 ? t1 : t2);
2841     if (!t)
2842         return NULL;
2843     return t->ctx;
2844 }
2845
2846 struct list *addsrvconfs(char *value, char **names) {
2847     struct list *conflist;
2848     int n;
2849     struct list_node *entry;
2850     struct clsrvconf *conf = NULL;
2851     
2852     if (!names || !*names)
2853         return NULL;
2854     
2855     conflist = list_create();
2856     if (!conflist) {
2857         debug(DBG_ERR, "malloc failed");
2858         return NULL;
2859     }
2860
2861     for (n = 0; names[n]; n++) {
2862         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2863             conf = (struct clsrvconf *)entry->data;
2864             if (!strcasecmp(names[n], conf->name))
2865                 break;
2866         }
2867         if (!entry) {
2868             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2869             list_destroy(conflist);
2870             return NULL;
2871         }
2872         if (!list_push(conflist, conf)) {
2873             debug(DBG_ERR, "malloc failed");
2874             list_destroy(conflist);
2875             return NULL;
2876         }
2877         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2878     }
2879     return conflist;
2880 }
2881
2882 void freerealm(struct realm *realm) {
2883     if (!realm)
2884         return;
2885     free(realm->name);
2886     free(realm->message);
2887     regfree(&realm->regex);
2888     pthread_mutex_destroy(&realm->subrealms_mutex);
2889     if (realm->subrealms)
2890         list_destroy(realm->subrealms);
2891     if (realm->srvconfs) {
2892         /* emptying list without freeing data */
2893         while (list_shift(realm->srvconfs));
2894         list_destroy(realm->srvconfs);
2895     }
2896     if (realm->accsrvconfs) {
2897         /* emptying list without freeing data */
2898         while (list_shift(realm->accsrvconfs));
2899         list_destroy(realm->accsrvconfs);
2900     }
2901     free(realm);
2902 }
2903
2904 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message) {
2905     int n;
2906     struct realm *realm;
2907     char *s, *regex = NULL;
2908     
2909     if (*value == '/') {
2910         /* regexp, remove optional trailing / if present */
2911         if (value[strlen(value) - 1] == '/')
2912             value[strlen(value) - 1] = '\0';
2913     } else {
2914         /* not a regexp, let us make it one */
2915         if (*value == '*' && !value[1])
2916             regex = stringcopy(".*", 0);
2917         else {
2918             for (n = 0, s = value; *s;)
2919                 if (*s++ == '.')
2920                     n++;
2921             regex = malloc(strlen(value) + n + 3);
2922             if (regex) {
2923                 regex[0] = '@';
2924                 for (n = 1, s = value; *s; s++) {
2925                     if (*s == '.')
2926                         regex[n++] = '\\';
2927                     regex[n++] = *s;
2928                 }
2929                 regex[n++] = '$';
2930                 regex[n] = '\0';
2931             }
2932         }
2933         if (!regex) {
2934             debug(DBG_ERR, "malloc failed");
2935             realm = NULL;
2936             goto exit;
2937         }
2938         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2939     }
2940
2941     realm = malloc(sizeof(struct realm));
2942     if (!realm) {
2943         debug(DBG_ERR, "malloc failed");
2944         goto exit;
2945     }
2946     memset(realm, 0, sizeof(struct realm));
2947     
2948     if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2949         debug(DBG_ERR, "mutex init failed");
2950         free(realm);
2951         realm = NULL;
2952         goto exit;
2953     }
2954
2955     realm->name = stringcopy(value, 0);
2956     if (!realm->name) {
2957         debug(DBG_ERR, "malloc failed");
2958         goto errexit;
2959     }
2960     if (message && strlen(message) > 253) {
2961         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2962         goto errexit;
2963     }
2964     realm->message = message;
2965     
2966     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2967         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2968         goto errexit;
2969     }
2970     
2971     if (servers && *servers) {
2972         realm->srvconfs = addsrvconfs(value, servers);
2973         if (!realm->srvconfs)
2974             goto errexit;
2975     }
2976     
2977     if (accservers && *accservers) {
2978         realm->accsrvconfs = addsrvconfs(value, accservers);
2979         if (!realm->accsrvconfs)
2980             goto errexit;
2981     }
2982
2983     if (!list_push(realmlist, realm)) {
2984         debug(DBG_ERR, "malloc failed");
2985         pthread_mutex_destroy(&realm->subrealms_mutex);
2986         goto errexit;
2987     }
2988     
2989     debug(DBG_DBG, "addrealm: added realm %s", value);
2990     goto exit;
2991
2992  errexit:
2993     freerealm(realm);
2994     realm = NULL;
2995     
2996  exit:
2997     free(regex);
2998     if (servers) {
2999         for (n = 0; servers[n]; n++)
3000             free(servers[n]);
3001         free(servers);
3002     }
3003     if (accservers) {
3004         for (n = 0; accservers[n]; n++)
3005             free(accservers[n]);
3006         free(accservers);
3007     }
3008     return realm;
3009 }
3010
3011 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3012     struct clsrvconf *srvconf;
3013     struct realm *newrealm = NULL;
3014     char *realmname, *s;
3015     pthread_t clientth;
3016     
3017     if (!conf->dynamiclookupcommand)
3018         return;
3019
3020     /* create dynamic for the realm (string after last @, exit if nothing after @ */
3021     realmname = strrchr(id, '@');
3022     if (!realmname)
3023         return;
3024     realmname++;
3025     if (!*realmname)
3026         return;
3027     for (s = realmname; *s; s++)
3028         if (*s != '.' && *s != '-' && !isalnum((int)*s))
3029             return;
3030     
3031     pthread_mutex_lock(&realm->subrealms_mutex);
3032     /* exit if we now already got a matching subrealm */
3033     if (id2realm(realm->subrealms, id))
3034         goto exit;
3035     srvconf = malloc(sizeof(struct clsrvconf));
3036     if (!srvconf) {
3037         debug(DBG_ERR, "malloc failed");
3038         goto exit;
3039     }
3040     *srvconf = *conf;
3041     if (!addserver(srvconf))
3042         goto errexit;
3043
3044     if (!realm->subrealms)
3045         realm->subrealms = list_create();
3046     if (!realm->subrealms)
3047         goto errexit;
3048     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL);
3049     if (!newrealm)
3050         goto errexit;
3051
3052     /* add server and accserver to newrealm */
3053     newrealm->srvconfs = list_create();
3054     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3055         debug(DBG_ERR, "malloc failed");
3056         goto errexit;
3057     }
3058     newrealm->accsrvconfs = list_create();
3059     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3060         debug(DBG_ERR, "malloc failed");
3061         goto errexit;
3062     }
3063
3064     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3065
3066     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3067         debug(DBG_ERR, "pthread_create failed");
3068         goto errexit;
3069     }
3070     pthread_detach(clientth);
3071     goto exit;
3072     
3073  errexit:
3074     if (newrealm) {
3075         list_removedata(realm->subrealms, newrealm);
3076         freerealm(newrealm);
3077         if (!list_first(realm->subrealms)) {
3078             list_destroy(realm->subrealms);
3079             realm->subrealms = NULL;
3080         }
3081     }
3082     freeserver(srvconf->servers, 1);
3083     free(srvconf);
3084     debug(DBG_ERR, "failed to create dynamic server");
3085
3086  exit:
3087     pthread_mutex_unlock(&realm->subrealms_mutex);
3088 }
3089
3090 int dynamicconfig(struct server *server) {
3091     int ok, fd[2], status;
3092     pid_t pid;
3093     struct clsrvconf *conf = server->conf;
3094     struct gconffile *cf = NULL;
3095     
3096     /* for now we only learn hostname/address */
3097     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3098
3099     if (pipe(fd) > 0) {
3100         debug(DBG_ERR, "dynamicconfig: pipe error");
3101         goto errexit;
3102     }
3103     pid = fork();
3104     if (pid < 0) {
3105         debug(DBG_ERR, "dynamicconfig: fork error");
3106         close(fd[0]);
3107         close(fd[1]);
3108         goto errexit;
3109     } else if (pid == 0) {
3110         /* child */
3111         close(fd[0]);
3112         if (fd[1] != STDOUT_FILENO) {
3113             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3114                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3115             close(fd[1]);
3116         }
3117         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3118             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3119     }
3120
3121     close(fd[1]);
3122     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3123     ok = getgenericconfig(&cf, NULL,
3124                           "Server", CONF_CBK, confserver_cb, (void *)conf,
3125                           NULL
3126                           );
3127     freegconf(&cf);
3128         
3129     if (waitpid(pid, &status, 0) < 0) {
3130         debug(DBG_ERR, "dynamicconfig: wait error");
3131         goto errexit;
3132     }
3133     
3134     if (status) {
3135         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3136         goto errexit;
3137     }
3138
3139     if (ok)
3140         return 1;
3141
3142  errexit:    
3143     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3144     return 0;
3145 }
3146
3147 int addmatchcertattr(struct clsrvconf *conf) {
3148     char *v;
3149     regex_t **r;
3150     
3151     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3152         r = &conf->certcnregex;
3153         v = conf->matchcertattr + 4;
3154     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3155         r = &conf->certuriregex;
3156         v = conf->matchcertattr + 20;
3157     } else
3158         return 0;
3159     if (!*v)
3160         return 0;
3161     /* regexp, remove optional trailing / if present */
3162     if (v[strlen(v) - 1] == '/')
3163         v[strlen(v) - 1] = '\0';
3164     if (!*v)
3165         return 0;
3166
3167     *r = malloc(sizeof(regex_t));
3168     if (!*r) {
3169         debug(DBG_ERR, "malloc failed");
3170         return 0;
3171     }
3172     if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3173         free(*r);
3174         *r = NULL;
3175         debug(DBG_ERR, "failed to compile regular expression %s", v);
3176         return 0;
3177     }
3178     return 1;
3179 }
3180
3181 int addrewriteattr(struct clsrvconf *conf) {
3182     char *v, *w;
3183     
3184     v = conf->rewriteattr + 11;
3185     if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3186         return 0;
3187     /* regexp, remove optional trailing / if present */
3188     if (v[strlen(v) - 1] == '/')
3189         v[strlen(v) - 1] = '\0';
3190
3191     w = strchr(v, '/');
3192     if (!*w)
3193         return 0;
3194     *w = '\0';
3195     w++;
3196     
3197     conf->rewriteattrregex = malloc(sizeof(regex_t));
3198     if (!conf->rewriteattrregex) {
3199         debug(DBG_ERR, "malloc failed");
3200         return 0;
3201     }
3202
3203     conf->rewriteattrreplacement = stringcopy(w, 0);
3204     if (!conf->rewriteattrreplacement) {
3205         free(conf->rewriteattrregex);
3206         conf->rewriteattrregex = NULL;
3207         return 0;
3208     }
3209     
3210     if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3211         free(conf->rewriteattrregex);
3212         conf->rewriteattrregex = NULL;
3213         free(conf->rewriteattrreplacement);
3214         conf->rewriteattrreplacement = NULL;
3215         debug(DBG_ERR, "failed to compile regular expression %s", v);
3216         return 0;
3217     }
3218
3219     return 1;
3220 }
3221
3222 /* should accept both names and numeric values, only numeric right now */
3223 uint8_t attrname2val(char *attrname) {
3224     int val = 0;
3225     
3226     val = atoi(attrname);
3227     return val > 0 && val < 256 ? val : 0;
3228 }
3229
3230 /* should accept both names and numeric values, only numeric right now */
3231 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3232     char *s;
3233     
3234     *vendor = atoi(attrname);
3235     s = strchr(attrname, ':');
3236     if (!s) {
3237         *type = -1;
3238         return 1;
3239     }
3240     *type = atoi(s + 1);
3241     return *type >= 0 && *type < 256;
3242 }
3243
3244 struct rewrite *getrewrite(char *alt1, char *alt2) {
3245     struct list_node *entry;
3246     struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3247     
3248     for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3249         r = (struct rewriteconf *)entry->data;
3250         if (!strcasecmp(r->name, alt1)) {
3251             r1 = r;
3252             break;
3253         }
3254         if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3255             r2 = r;
3256     }
3257
3258     r = (r1 ? r1 : r2);
3259     if (!r)
3260         return NULL;
3261     return r->rewrite;
3262 }
3263
3264 void addrewrite(char *value, char **attrs, char **vattrs) {
3265     struct rewriteconf *new;
3266     struct rewrite *rewrite = NULL;
3267     int i, n;
3268     uint8_t *a = NULL;
3269     uint32_t *p, *va = NULL;
3270
3271     if (attrs) {
3272         n = 0;
3273         for (; attrs[n]; n++);
3274         a = malloc((n + 1) * sizeof(uint8_t));
3275         if (!a)
3276             debugx(1, DBG_ERR, "malloc failed");
3277     
3278         for (i = 0; i < n; i++) {
3279             if (!(a[i] = attrname2val(attrs[i])))
3280                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3281             free(attrs[i]);
3282         }
3283         free(attrs);
3284         a[i] = 0;
3285     }
3286     
3287     if (vattrs) {
3288         n = 0;
3289         for (; vattrs[n]; n++);
3290         va = malloc((2 * n + 1) * sizeof(uint32_t));
3291         if (!va)
3292             debugx(1, DBG_ERR, "malloc failed");
3293     
3294         for (p = va, i = 0; i < n; i++, p += 2) {
3295             if (!vattrname2val(vattrs[i], p, p + 1))
3296                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3297             free(vattrs[i]);
3298         }
3299         free(vattrs);
3300         *p = 0;
3301     }
3302     
3303     if (a || va) {
3304         rewrite = malloc(sizeof(struct rewrite));
3305         if (!rewrite)
3306             debugx(1, DBG_ERR, "malloc failed");
3307         rewrite->removeattrs = a;
3308         rewrite->removevendorattrs = va;
3309     }
3310     
3311     new = malloc(sizeof(struct rewriteconf));
3312     if (!new || !list_push(rewriteconfs, new))
3313         debugx(1, DBG_ERR, "malloc failed");
3314
3315     memset(new, 0, sizeof(struct rewriteconf));
3316     new->name = stringcopy(value, 0);
3317     if (!new->name)
3318         debugx(1, DBG_ERR, "malloc failed");
3319         
3320     new->rewrite = rewrite;
3321     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3322 }
3323
3324 void freeclsrvconf(struct clsrvconf *conf) {
3325     free(conf->name);
3326     free(conf->conftype);
3327     free(conf->host);
3328     free(conf->port);
3329     free(conf->secret);
3330     free(conf->tls);
3331     free(conf->matchcertattr);
3332     if (conf->certcnregex)
3333         regfree(conf->certcnregex);
3334     if (conf->certuriregex)
3335         regfree(conf->certuriregex);
3336     free(conf->confrewrite);
3337     free(conf->rewriteattr);
3338     if (conf->rewriteattrregex)
3339         regfree(conf->rewriteattrregex);
3340     free(conf->rewriteattrreplacement);
3341     free(conf->dynamiclookupcommand);
3342     free(conf->rewrite);
3343     if (conf->addrinfo)
3344         freeaddrinfo(conf->addrinfo);
3345     /* not touching ssl_ctx, clients and servers */
3346     free(conf);
3347 }
3348
3349 int mergeconfstring(char **dst, char **src) {
3350     char *t;
3351     
3352     if (*src) {
3353         *dst = *src;
3354         *src = NULL;
3355         return 1;
3356     }
3357     if (*dst) {
3358         t = stringcopy(*dst, 0);
3359         if (!t) {
3360             debug(DBG_ERR, "malloc failed");
3361             return 0;
3362         }
3363         *dst = t;
3364     }
3365     return 1;
3366 }
3367
3368 /* assumes dst is a shallow copy */
3369 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3370     if (!mergeconfstring(&dst->name, &src->name) ||
3371         !mergeconfstring(&dst->conftype, &src->conftype) ||
3372         !mergeconfstring(&dst->host, &src->host) ||
3373         !mergeconfstring(&dst->port, &src->port) ||
3374         !mergeconfstring(&dst->secret, &src->secret) ||
3375         !mergeconfstring(&dst->tls, &src->tls) ||
3376         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3377         !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3378         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3379         return 0;
3380     dst->statusserver = src->statusserver;
3381     dst->certnamecheck = src->certnamecheck;
3382     if (src->retrydelay != 255)
3383         dst->retrydelay = src->retrydelay;
3384     if (src->retrycount != 255)
3385         dst->retrycount = src->retrycount;
3386     return 1;
3387 }
3388                    
3389 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3390     struct clsrvconf *conf;
3391     
3392     debug(DBG_DBG, "confclient_cb called for %s", block);
3393
3394     conf = malloc(sizeof(struct clsrvconf));
3395     if (!conf || !list_push(clconfs, conf))
3396         debugx(1, DBG_ERR, "malloc failed");
3397     memset(conf, 0, sizeof(struct clsrvconf));
3398     conf->certnamecheck = 1;
3399     
3400     if (!getgenericconfig(cf, block,
3401                      "type", CONF_STR, &conf->conftype,
3402                      "host", CONF_STR, &conf->host,
3403                      "secret", CONF_STR, &conf->secret,
3404                      "tls", CONF_STR, &conf->tls,
3405                      "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3406                      "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3407                      "rewrite", CONF_STR, &conf->confrewrite,
3408                      "rewriteattribute", CONF_STR, &conf->rewriteattr,
3409                      NULL
3410                           ))
3411         debugx(1, DBG_ERR, "configuration error");
3412     
3413     conf->name = stringcopy(val, 0);
3414     if (!conf->host)
3415         conf->host = stringcopy(val, 0);
3416     
3417     if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3418         conf->type = 'U';
3419         client_udp_count++;
3420     } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3421         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3422         if (!conf->ssl_ctx)
3423             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3424         if (conf->matchcertattr && !addmatchcertattr(conf))
3425             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3426         conf->type = 'T';
3427         client_tls_count++;
3428     } else
3429         debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3430     
3431     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3432     
3433     if (conf->rewriteattr) {
3434         if (!addrewriteattr(conf))
3435             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3436     }
3437     
3438     if (!resolvepeer(conf, 0))
3439         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3440     
3441     if (!conf->secret) {
3442         if (conf->type == 'U')
3443             debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3444         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3445     }
3446     return 1;
3447 }
3448
3449 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3450     switch (conf->type) {
3451     case 'U':
3452         if (!conf->port)
3453             conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3454         break;
3455     case 'T':
3456         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3457         if (!conf->ssl_ctx) {
3458             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3459             return 0;
3460         }
3461         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3462             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3463             return 0;
3464         }
3465         if (!conf->port)
3466             conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3467         break;
3468     }
3469
3470     if (conf->retrydelay == 255)
3471         conf->retrydelay = REQUEST_RETRY_DELAY;
3472     if (conf->retrycount == 255)
3473         conf->retrycount = REQUEST_RETRY_COUNT;
3474     
3475     conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3476     
3477     if (!conf->secret) {
3478         if (conf->type == 'U')
3479             debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3480         conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3481         if (!conf->secret) {
3482             debug(DBG_ERR, "malloc failed");
3483             return 0;
3484         }
3485     }
3486     
3487     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3488         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3489         return 0;
3490     }
3491     return 1;
3492 }
3493                         
3494 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3495     struct clsrvconf *conf, *resconf;
3496     long int retrydelay = LONG_MIN, retrycount = LONG_MIN;
3497     
3498     debug(DBG_DBG, "confserver_cb called for %s", block);
3499
3500     conf = malloc(sizeof(struct clsrvconf));
3501     if (!conf) {
3502         debug(DBG_ERR, "malloc failed");
3503         return 0;
3504     }
3505     memset(conf, 0, sizeof(struct clsrvconf));
3506     resconf = (struct clsrvconf *)arg;
3507     if (resconf) {
3508         conf->statusserver = resconf->statusserver;
3509         conf->certnamecheck = resconf->certnamecheck;
3510     } else
3511         conf->certnamecheck = 1;
3512
3513     if (!getgenericconfig(cf, block,
3514                           "type", CONF_STR, &conf->conftype,
3515                           "host", CONF_STR, &conf->host,
3516                           "port", CONF_STR, &conf->port,
3517                           "secret", CONF_STR, &conf->secret,
3518                           "tls", CONF_STR, &conf->tls,
3519                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3520                           "rewrite", CONF_STR, &conf->confrewrite,
3521                           "StatusServer", CONF_BLN, &conf->statusserver,
3522                           "RetryDelay", CONF_LINT, &retrydelay,
3523                           "RetryCount", CONF_LINT, &retrycount,
3524                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3525                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3526                           NULL
3527                           )) {
3528         debug(DBG_ERR, "configuration error");
3529         goto errexit;
3530     }
3531     
3532     conf->name = stringcopy(val, 0);
3533     if (!conf->name) {
3534         debug(DBG_ERR, "malloc failed");
3535         goto errexit;
3536     }
3537     if (!conf->host) {
3538         conf->host = stringcopy(val, 0);
3539         if (!conf->host) {
3540             debug(DBG_ERR, "malloc failed");
3541             goto errexit;
3542         }
3543     }
3544     
3545     if (retrydelay != LONG_MIN) {
3546         if (retrydelay < 1 || retrydelay > 60) {
3547             debug(DBG_ERR, "error in block %s, value of option RetryDelay is %d, must be 1-60", block, retrydelay);
3548             goto errexit;
3549         }
3550         conf->retrydelay = (uint8_t)retrydelay;
3551     } else
3552         conf->retrydelay = 255;
3553     
3554     if (retrycount != LONG_MIN) {
3555         if (retrycount < 0 || retrycount > 10) {
3556             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
3557             goto errexit;
3558         }
3559         conf->retrycount = (uint8_t)retrycount;
3560     } else
3561         conf->retrycount = 255;
3562     
3563     if (resconf) {
3564         if (!mergesrvconf(resconf, conf))
3565             goto errexit;
3566         free(conf);
3567         conf = resconf;
3568         if (conf->dynamiclookupcommand) {
3569             free(conf->dynamiclookupcommand);
3570             conf->dynamiclookupcommand = NULL;
3571         }
3572     }
3573
3574     if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3575         conf->type = 'U';
3576     else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3577         conf->type = 'T';
3578     else {
3579         debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3580         goto errexit;
3581     }
3582     
3583     if (resconf || !conf->dynamiclookupcommand) {
3584         if (!compileserverconfig(conf, block))
3585             goto errexit;
3586     }
3587     
3588     if (resconf)
3589         return 1;
3590         
3591     switch (conf->type) {
3592     case 'U':
3593         server_udp_count++;
3594         break;
3595     case 'T':
3596         server_tls_count++;
3597         break;
3598     default:
3599         goto errexit;
3600     }
3601     
3602     if (!list_push(srvconfs, conf)) {
3603         debug(DBG_ERR, "malloc failed");
3604         goto errexit;
3605     }
3606     return 1;
3607
3608  errexit:    
3609     freeclsrvconf(conf);
3610     return 0;
3611 }
3612
3613 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3614     char **servers = NULL, **accservers = NULL, *msg = NULL;
3615     
3616     debug(DBG_DBG, "confrealm_cb called for %s", block);
3617     
3618     if (!getgenericconfig(cf, block,
3619                      "server", CONF_MSTR, &servers,
3620                      "accountingServer", CONF_MSTR, &accservers,
3621                      "ReplyMessage", CONF_STR, &msg,
3622                      NULL
3623                           ))
3624         debugx(1, DBG_ERR, "configuration error");
3625
3626     addrealm(realms, val, servers, accservers, msg);
3627     return 1;
3628 }
3629
3630 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3631     char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3632     
3633     debug(DBG_DBG, "conftls_cb called for %s", block);
3634     
3635     if (!getgenericconfig(cf, block,
3636                      "CACertificateFile", CONF_STR, &cacertfile,
3637                      "CACertificatePath", CONF_STR, &cacertpath,
3638                      "CertificateFile", CONF_STR, &certfile,
3639                      "CertificateKeyFile", CONF_STR, &certkeyfile,
3640                      "CertificateKeyPassword", CONF_STR, &certkeypwd,
3641                      NULL
3642                           ))
3643         debugx(1, DBG_ERR, "configuration error");
3644     
3645     tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
3646     free(cacertfile);
3647     free(cacertpath);
3648     free(certfile);
3649     free(certkeyfile);
3650     free(certkeypwd);
3651     return 1;
3652 }
3653
3654 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3655     char **attrs = NULL, **vattrs = NULL;
3656     
3657     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3658     
3659     if (!getgenericconfig(cf, block,
3660                      "removeAttribute", CONF_MSTR, &attrs,
3661                      "removeVendorAttribute", CONF_MSTR, &vattrs,
3662                      NULL
3663                           ))
3664         debugx(1, DBG_ERR, "configuration error");
3665     addrewrite(val, attrs, vattrs);
3666     return 1;
3667 }
3668
3669 void getmainconfig(const char *configfile) {
3670     long int loglevel = LONG_MIN;
3671     struct gconffile *cfs;
3672
3673     cfs = openconfigfile(configfile);
3674     memset(&options, 0, sizeof(options));
3675     
3676     clconfs = list_create();
3677     if (!clconfs)
3678         debugx(1, DBG_ERR, "malloc failed");
3679     
3680     srvconfs = list_create();
3681     if (!srvconfs)
3682         debugx(1, DBG_ERR, "malloc failed");
3683     
3684     realms = list_create();
3685     if (!realms)
3686         debugx(1, DBG_ERR, "malloc failed");    
3687  
3688     tlsconfs = list_create();
3689     if (!tlsconfs)
3690         debugx(1, DBG_ERR, "malloc failed");
3691     
3692     rewriteconfs = list_create();
3693     if (!rewriteconfs)
3694         debugx(1, DBG_ERR, "malloc failed");    
3695  
3696     if (!getgenericconfig(&cfs, NULL,
3697                           "ListenUDP", CONF_STR, &options.listenudp,
3698                           "ListenTCP", CONF_STR, &options.listentcp,
3699                           "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3700                           "SourceUDP", CONF_STR, &options.sourceudp,
3701                           "SourceTCP", CONF_STR, &options.sourcetcp,
3702                           "LogLevel", CONF_LINT, &loglevel,
3703                           "LogDestination", CONF_STR, &options.logdestination,
3704                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3705                           "Client", CONF_CBK, confclient_cb, NULL,
3706                           "Server", CONF_CBK, confserver_cb, NULL,
3707                           "Realm", CONF_CBK, confrealm_cb, NULL,
3708                           "TLS", CONF_CBK, conftls_cb, NULL,
3709                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3710                           NULL
3711                           ))
3712         debugx(1, DBG_ERR, "configuration error");
3713     
3714     if (loglevel != LONG_MIN) {
3715         if (loglevel < 1 || loglevel > 4)
3716             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3717         options.loglevel = (uint8_t)loglevel;
3718     }
3719 }
3720
3721 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3722     int c;
3723
3724     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3725         switch (c) {
3726         case 'c':
3727             *configfile = optarg;
3728             break;
3729         case 'd':
3730             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3731                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3732             *loglevel = *optarg - '0';
3733             break;
3734         case 'f':
3735             *foreground = 1;
3736             break;
3737         case 'p':
3738             *pretend = 1;
3739             break;
3740         case 'v':
3741                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3742         default:
3743             goto usage;
3744         }
3745     }
3746     if (!(argc - optind))
3747         return;
3748
3749  usage:
3750     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3751 }
3752
3753 #ifdef SYS_SOLARIS9
3754 int daemon(int a, int b) {
3755     int i;
3756
3757     if (fork())
3758         exit(0);
3759
3760     setsid();
3761
3762     for (i = 0; i < 3; i++) {
3763         close(i);
3764         open("/dev/null", O_RDWR);
3765     }
3766     return 1;
3767 }
3768 #endif
3769
3770 void *sighandler(void *arg) {
3771     sigset_t sigset;
3772     int sig;
3773
3774     for(;;) {
3775         sigemptyset(&sigset);
3776         sigaddset(&sigset, SIGPIPE);
3777         sigwait(&sigset, &sig);
3778         /* only get SIGPIPE right now, so could simplify below code */
3779         switch (sig) {
3780         case 0:
3781             /* completely ignoring this */
3782             break;
3783         case SIGPIPE:
3784             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3785             break;
3786         default:
3787             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3788         }
3789     }
3790 }
3791
3792 int main(int argc, char **argv) {
3793     pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3794     sigset_t sigset;
3795     struct list_node *entry;
3796     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3797     char *configfile = NULL;
3798     struct clsrvconf *srvconf;
3799     
3800     debug_init("radsecproxy");
3801     debug_set_level(DEBUG_LEVEL);
3802     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3803     if (loglevel)
3804         debug_set_level(loglevel);
3805     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3806     if (loglevel)
3807         options.loglevel = loglevel;
3808     else if (options.loglevel)
3809         debug_set_level(options.loglevel);
3810     if (!foreground)
3811         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3812     free(options.logdestination);
3813
3814     if (!list_first(clconfs))
3815         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3816     if (!list_first(srvconfs))
3817         debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3818     if (!list_first(realms))
3819         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3820
3821     if (pretend)
3822         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3823
3824     if (!foreground && (daemon(0, 0) < 0))
3825         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3826     
3827     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3828
3829     sigemptyset(&sigset);
3830     /* exit on all but SIGPIPE, ignore more? */
3831     sigaddset(&sigset, SIGPIPE);
3832     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3833     pthread_create(&sigth, NULL, sighandler, NULL);
3834     
3835     if (client_udp_count) {
3836         udp_server_replyq = newreplyq();
3837         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3838             debugx(1, DBG_ERR, "pthread_create failed");
3839         if (options.listenaccudp)
3840             if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3841                 debugx(1, DBG_ERR, "pthread_create failed");
3842     }
3843     
3844     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3845         srvconf = (struct clsrvconf *)entry->data;
3846         if (srvconf->dynamiclookupcommand)
3847             continue;
3848         if (!addserver(srvconf))
3849             debugx(1, DBG_ERR, "failed to add server");
3850         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3851                            (void *)(srvconf->servers)))
3852             debugx(1, DBG_ERR, "pthread_create failed");
3853     }
3854     /* srcudpres no longer needed, while srctcpres is needed later */
3855     if (srcudpres) {
3856         freeaddrinfo(srcudpres);
3857         srcudpres = NULL;
3858     }
3859     if (udp_client4_sock >= 0)
3860         if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3861             debugx(1, DBG_ERR, "pthread_create failed");
3862     if (udp_client6_sock >= 0)
3863         if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3864             debugx(1, DBG_ERR, "pthread_create failed");
3865     
3866     if (client_tls_count)
3867         return tlslistener();
3868     
3869     /* just hang around doing nothing, anything to do here? */
3870     for (;;)
3871         sleep(1000);
3872 }