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