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