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