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