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