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