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