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