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