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