6565c75481f8d5224c02474f7a750510236c42b8
[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->buf)
921         free(rq->buf);
922 }
923
924 void freerq(struct request *rq) {
925     if (!rq)
926         return;
927     debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
928     if (--rq->refcount)
929         return;
930     freerqdata(rq);
931     free(rq);
932 }
933
934 void freerqoutdata(struct rqout *rqout) {
935     if (!rqout)
936         return;
937     if (rqout->origusername)
938         free(rqout->origusername);
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->origid == id && rqout->rq && 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 *rq,
1367            char *oldsecret, char *newsecret) {
1368     unsigned char *attr;
1369     
1370     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1371         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1372         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->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->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     if (!msg) {
1786         debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1787         return 0;
1788     }
1789
1790     rqout = &rqdata;
1791     memset(rqout, 0, sizeof(struct rqout));
1792     rqout->msg = msg;
1793     debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1794     
1795     if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1796         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1797         freerqoutdata(rqout);
1798         return 1;
1799     }
1800
1801     if (!addclientrq(rq, msg->id)) {
1802         debug(DBG_INFO, "radsrv: already got request with id %d from %s, ignoring", msg->id, from->conf->host);
1803         freerqoutdata(rqout);
1804         return 1;
1805     }
1806     rqout->rq = rq;
1807     rq->refcount++;
1808     
1809     if (msg->code == RAD_Status_Server) {
1810         respondstatusserver(rqout);
1811         goto exit;
1812     }
1813
1814     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1815
1816     if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1817         goto exit;
1818
1819     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1820     if (!attr) {
1821         if (msg->code == RAD_Accounting_Request) {
1822             acclog(msg, from->conf->host);
1823             respondaccounting(rqout);
1824         } else
1825             debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1826         goto exit;
1827     }
1828     
1829     if (from->conf->rewriteusername && !rewriteusername(rqout, attr)) {
1830         debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1831         goto exit;
1832     }
1833     
1834     userascii = radattr2ascii(attr);
1835     if (!userascii)
1836         goto exit;
1837     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1838
1839     to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1840     if (!realm) {
1841         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1842         goto exit;
1843     }
1844     if (!to) {
1845         if (realm->message && msg->code == RAD_Access_Request) {
1846             debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1847             respondreject(rqout, realm->message);
1848         } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1849             acclog(msg, from->conf->host);
1850             respondaccounting(rqout);
1851         }
1852         goto exit;
1853     }
1854     
1855     free(rq->buf);
1856     rq->buf = NULL;
1857     
1858     if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1859         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1860               from->conf->name, to->conf->name);
1861         goto exit;
1862     }
1863
1864 #if 0
1865     skip this now that we have rqrcv... per client?
1866     if (rqinqueue(to, from, msg->id, msg->code)) {
1867         debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1868               radmsgtype2string(msg->code), from->conf->host, msg->id);
1869         goto exit;
1870     }
1871 #endif
1872     
1873     if (msg->code != RAD_Accounting_Request) {
1874         if (!RAND_bytes(newauth, 16)) {
1875             debug(DBG_WARN, "radsrv: failed to generate random auth");
1876             goto exit;
1877         }
1878     }
1879     
1880 #ifdef DEBUG
1881     printfchars(NULL, "auth", "%02x ", auth, 16);
1882 #endif
1883
1884     attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1885     if (attr) {
1886         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1887         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, msg->auth, newauth))
1888             goto exit;
1889     }
1890
1891     attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1892     if (attr) {
1893         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1894         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, msg->auth, newauth))
1895             goto exit;
1896     }
1897
1898     rqout->origid = msg->id;
1899     memcpy(rqout->origauth, msg->auth, 16);
1900     memcpy(msg->auth, newauth, 16);    
1901
1902     if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1903         goto exit;
1904     
1905     free(userascii);
1906     sendrq(to, rqout);
1907     return 1;
1908     
1909  exit:
1910     rmclientrq(rq, msg->id);
1911     free(userascii);
1912     freerqoutdata(rqout);
1913     return 1;
1914 }
1915
1916 void replyh(struct server *server, unsigned char *buf) {
1917     struct client *from;
1918     struct rqout *rqout;
1919     int sublen;
1920     unsigned char *subattrs;
1921     struct sockaddr_storage fromsa;
1922     uint8_t *username, *stationid;
1923     struct radmsg *msg = NULL;
1924     struct tlv *attr;
1925     struct list_node *node;
1926     
1927     server->connectionok = 1;
1928     server->lostrqs = 0;
1929
1930     rqout = server->requests + buf[1];
1931     msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->msg->auth);
1932     free(buf);
1933     buf = NULL;
1934     if (!msg) {
1935         debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1936         return;
1937     }
1938     if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1939         && msg->code != RAD_Accounting_Response) {
1940         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1941         radmsg_free(msg);
1942         return;
1943     }
1944     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1945
1946     pthread_mutex_lock(&server->newrq_mutex);
1947     if (!rqout->buf || !rqout->tries) {
1948         debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1949         goto errunlock;
1950     }
1951
1952     if (rqout->received) {
1953         debug(DBG_INFO, "replyh: already received, ignoring reply");
1954         goto errunlock;
1955     }
1956         
1957     gettimeofday(&server->lastrcv, NULL);
1958     
1959     if (rqout->msg->code == RAD_Status_Server) {
1960         rqout->received = 1;
1961         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1962         goto errunlock;
1963     }
1964
1965     gettimeofday(&server->lastreply, NULL);
1966     
1967     if (!rqout->rq) {
1968         debug(DBG_INFO, "replyh: client gone, ignoring reply");
1969         goto errunlock;
1970     }
1971     from = rqout->rq->from;
1972         
1973     if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1974         debug(DBG_WARN, "replyh: rewritein failed");
1975         goto errunlock;
1976     }
1977     
1978     /* MS MPPE */
1979     for (node = list_first(msg->attrs); node; node = list_next(node)) {
1980         attr = (struct tlv *)node->data;
1981         if (attr->t != RAD_Attr_Vendor_Specific)
1982             continue;
1983         if (attr->l <= 4)
1984             break;
1985         if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55)  /* 311 == MS */
1986             continue;
1987             
1988         sublen = attr->l - 4;
1989         subattrs = attr->v + 4;  
1990         if (!attrvalidate(subattrs, sublen) ||
1991             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1992                     rqout, server->conf->secret, from->conf->secret) ||
1993             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1994                     rqout, server->conf->secret, from->conf->secret))
1995             break;
1996     }
1997     if (node) {
1998         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1999         goto errunlock;
2000     }
2001
2002     if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2003         username = radattr2ascii(radmsg_gettype(rqout->msg, RAD_Attr_User_Name));
2004         if (username) {
2005             stationid = radattr2ascii(radmsg_gettype(rqout->msg, RAD_Attr_Calling_Station_Id));
2006             if (stationid) {
2007                 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2008                       radmsgtype2string(msg->code), username, stationid, server->conf->host);
2009                 free(stationid);
2010             } else
2011                 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(msg->code), username, server->conf->host);
2012             free(username);
2013         }
2014     }
2015
2016     msg->id = (char)rqout->origid;
2017     memcpy(msg->auth, rqout->origauth, 16);
2018
2019 #ifdef DEBUG    
2020     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2021 #endif
2022
2023     if (rqout->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2024         if (!resizeattr(attr, strlen(rqout->origusername))) {
2025             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2026             goto errunlock;
2027         }
2028         memcpy(attr->v, rqout->origusername, strlen(rqout->origusername));
2029     }
2030
2031     if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2032         debug(DBG_WARN, "replyh: rewriteout failed");
2033         goto errunlock;
2034     }
2035
2036     fromsa = rqout->rq->fromsa; /* only needed for UDP */
2037     /* once we set received = 1, rq may be reused */
2038     rqout->received = 1;
2039
2040     debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2041     sendreply(from, msg, &fromsa, rqout->rq->fromudpsock);
2042     pthread_mutex_unlock(&server->newrq_mutex);
2043     return;
2044
2045  errunlock:
2046     radmsg_free(msg);
2047     pthread_mutex_unlock(&server->newrq_mutex);
2048     return;
2049 }
2050
2051 struct radmsg *createstatsrvmsg() {
2052     struct radmsg *msg;
2053     struct tlv *attr;
2054
2055     msg = radmsg_init(RAD_Status_Server, 0, NULL);
2056     if (!msg)
2057         return NULL;
2058     
2059     attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2060     if (!attr) {
2061         radmsg_free(msg);
2062         return NULL;
2063     }
2064     if (!radmsg_add(msg, attr)) {
2065         freetlv(attr);
2066         radmsg_free(msg);
2067         return NULL;
2068     }
2069     return msg;
2070 }
2071
2072 /* code for removing state not finished */
2073 void *clientwr(void *arg) {
2074     struct server *server = (struct server *)arg;
2075     struct rqout *rqout;
2076     pthread_t clientrdth;
2077     int i, secs, dynconffail = 0;
2078     uint8_t rnd;
2079     struct timeval now, laststatsrv;
2080     struct timespec timeout;
2081     struct rqout statsrvrq;
2082     struct clsrvconf *conf;
2083     
2084     conf = server->conf;
2085     
2086     if (server->dynamiclookuparg && !dynamicconfig(server)) {
2087         dynconffail = 1;
2088         goto errexit;
2089     }
2090     
2091     if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2092         debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2093         goto errexit;
2094     }
2095
2096     memset(&timeout, 0, sizeof(struct timespec));
2097     
2098     if (conf->statusserver) {
2099         gettimeofday(&server->lastrcv, NULL);
2100         gettimeofday(&laststatsrv, NULL);
2101     }
2102
2103     if (conf->pdef->connecter) {
2104         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2105             goto errexit;
2106         server->connectionok = 1;
2107         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2108             debug(DBG_ERR, "clientwr: pthread_create failed");
2109             goto errexit;
2110         }
2111     } else
2112         server->connectionok = 1;
2113     
2114     for (;;) {
2115         pthread_mutex_lock(&server->newrq_mutex);
2116         if (!server->newrq) {
2117             gettimeofday(&now, NULL);
2118             /* random 0-7 seconds */
2119             RAND_bytes(&rnd, 1);
2120             rnd /= 32;
2121             if (conf->statusserver) {
2122                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2123                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2124                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2125             } else {
2126                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2127                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2128             }
2129 #if 0
2130             if (timeout.tv_sec > now.tv_sec)
2131                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2132 #endif      
2133             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2134             timeout.tv_sec = 0;
2135         }
2136         if (server->newrq) {
2137             debug(DBG_DBG, "clientwr: got new request");
2138             server->newrq = 0;
2139         }
2140 #if 0   
2141         else
2142             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2143 #endif  
2144         pthread_mutex_unlock(&server->newrq_mutex);
2145
2146         for (i = 0; i < MAX_REQUESTS; i++) {
2147             if (server->clientrdgone) {
2148                 pthread_join(clientrdth, NULL);
2149                 goto errexit;
2150             }
2151             pthread_mutex_lock(&server->newrq_mutex);
2152             while (i < MAX_REQUESTS && !server->requests[i].buf)
2153                 i++;
2154             if (i == MAX_REQUESTS) {
2155                 pthread_mutex_unlock(&server->newrq_mutex);
2156                 break;
2157             }
2158             rqout = server->requests + i;
2159
2160             if (rqout->received) {
2161                 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2162                 if (rqout->buf) {
2163                     debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2164                     freerqoutdata(rqout);
2165                     /* setting this to NULL means that it can be reused */
2166                     rqout->buf = NULL;
2167                 }
2168                 pthread_mutex_unlock(&server->newrq_mutex);
2169                 continue;
2170             }
2171             
2172             gettimeofday(&now, NULL);
2173             if (now.tv_sec < rqout->expiry.tv_sec) {
2174                 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2175                     timeout.tv_sec = rqout->expiry.tv_sec;
2176                 pthread_mutex_unlock(&server->newrq_mutex);
2177                 continue;
2178             }
2179
2180             if (rqout->tries == (*rqout->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2181                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2182                 if (conf->statusserver) {
2183                     if (*rqout->buf == RAD_Status_Server) {
2184                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2185                         if (server->lostrqs < 255)
2186                             server->lostrqs++;
2187                     }
2188                 } else {
2189                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2190                     if (server->lostrqs < 255)
2191                         server->lostrqs++;
2192                 }
2193                 freerqoutdata(rqout);
2194                 /* setting this to NULL means that it can be reused */
2195                 rqout->buf = NULL;
2196                 pthread_mutex_unlock(&server->newrq_mutex);
2197                 continue;
2198             }
2199             pthread_mutex_unlock(&server->newrq_mutex);
2200
2201             rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2202             if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2203                 timeout.tv_sec = rqout->expiry.tv_sec;
2204             rqout->tries++;
2205             conf->pdef->clientradput(server, server->requests[i].buf);
2206         }
2207         if (conf->statusserver) {
2208             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2209             gettimeofday(&now, NULL);
2210             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2211                 laststatsrv = now;
2212                 memset(&statsrvrq, 0, sizeof(struct rqout));
2213                 statsrvrq.msg = createstatsrvmsg();
2214                 if (statsrvrq.msg) {
2215                     debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2216                     sendrq(server, &statsrvrq);
2217                 }
2218             }
2219         }
2220     }
2221  errexit:
2222     conf->servers = NULL;
2223     if (server->dynamiclookuparg) {
2224         removeserversubrealms(realms, conf);
2225         if (dynconffail)
2226             free(conf);
2227         else
2228             freeclsrvconf(conf);
2229     }
2230     freeserver(server, 1);
2231     ERR_remove_state(0);
2232     return NULL;
2233 }
2234
2235 void createlistener(uint8_t type, char *arg) {
2236     pthread_t th;
2237     struct clsrvconf *listenres;
2238     struct addrinfo *res;
2239     int s = -1, on = 1, *sp = NULL;
2240     
2241     listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2242     if (!listenres)
2243         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2244     
2245     for (res = listenres->addrinfo; res; res = res->ai_next) {
2246         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2247         if (s < 0) {
2248             debug(DBG_WARN, "createlistener: socket failed");
2249             continue;
2250         }
2251         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2252 #ifdef IPV6_V6ONLY
2253         if (res->ai_family == AF_INET6)
2254             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2255 #endif          
2256         if (bind(s, res->ai_addr, res->ai_addrlen)) {
2257             debug(DBG_WARN, "createlistener: bind failed");
2258             close(s);
2259             s = -1;
2260             continue;
2261         }
2262
2263         sp = malloc(sizeof(int));
2264         if (!sp)
2265             debugx(1, DBG_ERR, "malloc failed");
2266         *sp = s;
2267         if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2268             debugx(1, DBG_ERR, "pthread_create failed");
2269         pthread_detach(th);
2270     }
2271     if (!sp)
2272         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2273     
2274     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2275           listenres->host ? listenres->host : "*", listenres->port);
2276     freeclsrvres(listenres);
2277 }
2278
2279 void createlisteners(uint8_t type, char **args) {
2280     int i;
2281
2282     if (args)
2283         for (i = 0; args[i]; i++)
2284             createlistener(type, args[i]);
2285     else
2286         createlistener(type, NULL);
2287 }
2288
2289 #ifdef DEBUG
2290 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2291     const char *s;
2292     int w;
2293
2294     w = where & ~SSL_ST_MASK;
2295
2296     if (w & SSL_ST_CONNECT)
2297         s = "SSL_connect";
2298     else if (w & SSL_ST_ACCEPT)
2299         s = "SSL_accept";
2300     else
2301         s = "undefined";
2302
2303     if (where & SSL_CB_LOOP)
2304         debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2305     else if (where & SSL_CB_ALERT) {
2306         s = (where & SSL_CB_READ) ? "read" : "write";
2307         debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2308     }
2309     else if (where & SSL_CB_EXIT) {
2310         if (ret == 0)
2311             debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2312         else if (ret < 0)
2313             debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2314     }
2315 }
2316 #endif
2317
2318 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2319     SSL_CTX *ctx = NULL;
2320     STACK_OF(X509_NAME) *calist;
2321     X509_STORE *x509_s;
2322     int i;
2323     unsigned long error;
2324
2325     if (!ssl_locks) {
2326         ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2327         ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2328         for (i = 0; i < CRYPTO_num_locks(); i++) {
2329             ssl_lock_count[i] = 0;
2330             pthread_mutex_init(&ssl_locks[i], NULL);
2331         }
2332         CRYPTO_set_id_callback(ssl_thread_id);
2333         CRYPTO_set_locking_callback(ssl_locking_callback);
2334
2335         SSL_load_error_strings();
2336         SSL_library_init();
2337
2338         while (!RAND_status()) {
2339             time_t t = time(NULL);
2340             pid_t pid = getpid();
2341             RAND_seed((unsigned char *)&t, sizeof(time_t));
2342             RAND_seed((unsigned char *)&pid, sizeof(pid));
2343         }
2344     }
2345
2346     switch (type) {
2347     case RAD_TLS:
2348         ctx = SSL_CTX_new(TLSv1_method());
2349 #ifdef DEBUG    
2350         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2351 #endif  
2352         break;
2353     case RAD_DTLS:
2354         ctx = SSL_CTX_new(DTLSv1_method());
2355 #ifdef DEBUG    
2356         SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2357 #endif  
2358         SSL_CTX_set_read_ahead(ctx, 1);
2359         break;
2360     }
2361     if (!ctx) {
2362         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2363         return NULL;
2364     }
2365     
2366     if (conf->certkeypwd) {
2367         SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2368         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2369     }
2370     if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2371         !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2372         !SSL_CTX_check_private_key(ctx) ||
2373         !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2374         while ((error = ERR_get_error()))
2375             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2376         debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2377         SSL_CTX_free(ctx);
2378         return NULL;
2379     }
2380
2381     calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2382     if (!conf->cacertfile || calist) {
2383         if (conf->cacertpath) {
2384             if (!calist)
2385                 calist = sk_X509_NAME_new_null();
2386             if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2387                 sk_X509_NAME_free(calist);
2388                 calist = NULL;
2389             }
2390         }
2391     }
2392     if (!calist) {
2393         while ((error = ERR_get_error()))
2394             debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2395         debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2396         SSL_CTX_free(ctx);
2397         return NULL;
2398     }
2399     ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2400     SSL_CTX_set_client_CA_list(ctx, calist);
2401     
2402     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2403     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2404
2405     if (conf->crlcheck) {
2406         x509_s = SSL_CTX_get_cert_store(ctx);
2407         X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2408     }
2409
2410     debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2411     return ctx;
2412 }
2413
2414 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2415     struct tls *t;
2416
2417     t = hash_read(tlsconfs, alt1, strlen(alt1));
2418     if (!t) {
2419         t = hash_read(tlsconfs, alt2, strlen(alt2));
2420         if (!t)
2421             return NULL;
2422     }
2423
2424     switch (type) {
2425     case RAD_TLS:
2426         if (!t->tlsctx)
2427             t->tlsctx = tlscreatectx(RAD_TLS, t);
2428         return t->tlsctx;
2429     case RAD_DTLS:
2430         if (!t->dtlsctx)
2431             t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2432         return t->dtlsctx;
2433     }
2434     return NULL;
2435 }
2436
2437 struct list *addsrvconfs(char *value, char **names) {
2438     struct list *conflist;
2439     int n;
2440     struct list_node *entry;
2441     struct clsrvconf *conf = NULL;
2442     
2443     if (!names || !*names)
2444         return NULL;
2445     
2446     conflist = list_create();
2447     if (!conflist) {
2448         debug(DBG_ERR, "malloc failed");
2449         return NULL;
2450     }
2451
2452     for (n = 0; names[n]; n++) {
2453         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2454             conf = (struct clsrvconf *)entry->data;
2455             if (!strcasecmp(names[n], conf->name))
2456                 break;
2457         }
2458         if (!entry) {
2459             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2460             list_destroy(conflist);
2461             return NULL;
2462         }
2463         if (!list_push(conflist, conf)) {
2464             debug(DBG_ERR, "malloc failed");
2465             list_destroy(conflist);
2466             return NULL;
2467         }
2468         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2469     }
2470     return conflist;
2471 }
2472
2473 void freerealm(struct realm *realm) {
2474     if (!realm)
2475         return;
2476     free(realm->name);
2477     free(realm->message);
2478     regfree(&realm->regex);
2479     pthread_mutex_destroy(&realm->subrealms_mutex);
2480     if (realm->subrealms)
2481         list_destroy(realm->subrealms);
2482     if (realm->srvconfs) {
2483         /* emptying list without freeing data */
2484         while (list_shift(realm->srvconfs));
2485         list_destroy(realm->srvconfs);
2486     }
2487     if (realm->accsrvconfs) {
2488         /* emptying list without freeing data */
2489         while (list_shift(realm->accsrvconfs));
2490         list_destroy(realm->accsrvconfs);
2491     }
2492     free(realm);
2493 }
2494
2495 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2496     int n;
2497     struct realm *realm;
2498     char *s, *regex = NULL;
2499     
2500     if (*value == '/') {
2501         /* regexp, remove optional trailing / if present */
2502         if (value[strlen(value) - 1] == '/')
2503             value[strlen(value) - 1] = '\0';
2504     } else {
2505         /* not a regexp, let us make it one */
2506         if (*value == '*' && !value[1])
2507             regex = stringcopy(".*", 0);
2508         else {
2509             for (n = 0, s = value; *s;)
2510                 if (*s++ == '.')
2511                     n++;
2512             regex = malloc(strlen(value) + n + 3);
2513             if (regex) {
2514                 regex[0] = '@';
2515                 for (n = 1, s = value; *s; s++) {
2516                     if (*s == '.')
2517                         regex[n++] = '\\';
2518                     regex[n++] = *s;
2519                 }
2520                 regex[n++] = '$';
2521                 regex[n] = '\0';
2522             }
2523         }
2524         if (!regex) {
2525             debug(DBG_ERR, "malloc failed");
2526             realm = NULL;
2527             goto exit;
2528         }
2529         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2530     }
2531
2532     realm = malloc(sizeof(struct realm));
2533     if (!realm) {
2534         debug(DBG_ERR, "malloc failed");
2535         goto exit;
2536     }
2537     memset(realm, 0, sizeof(struct realm));
2538     
2539     if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2540         debug(DBG_ERR, "mutex init failed");
2541         free(realm);
2542         realm = NULL;
2543         goto exit;
2544     }
2545
2546     realm->name = stringcopy(value, 0);
2547     if (!realm->name) {
2548         debug(DBG_ERR, "malloc failed");
2549         goto errexit;
2550     }
2551     if (message && strlen(message) > 253) {
2552         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2553         goto errexit;
2554     }
2555     realm->message = message;
2556     realm->accresp = accresp;
2557     
2558     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2559         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2560         goto errexit;
2561     }
2562     
2563     if (servers && *servers) {
2564         realm->srvconfs = addsrvconfs(value, servers);
2565         if (!realm->srvconfs)
2566             goto errexit;
2567     }
2568     
2569     if (accservers && *accservers) {
2570         realm->accsrvconfs = addsrvconfs(value, accservers);
2571         if (!realm->accsrvconfs)
2572             goto errexit;
2573     }
2574
2575     if (!list_push(realmlist, realm)) {
2576         debug(DBG_ERR, "malloc failed");
2577         pthread_mutex_destroy(&realm->subrealms_mutex);
2578         goto errexit;
2579     }
2580     
2581     debug(DBG_DBG, "addrealm: added realm %s", value);
2582     goto exit;
2583
2584  errexit:
2585     freerealm(realm);
2586     realm = NULL;
2587     
2588  exit:
2589     free(regex);
2590     if (servers) {
2591         for (n = 0; servers[n]; n++)
2592             free(servers[n]);
2593         free(servers);
2594     }
2595     if (accservers) {
2596         for (n = 0; accservers[n]; n++)
2597             free(accservers[n]);
2598         free(accservers);
2599     }
2600     return realm;
2601 }
2602
2603 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2604     struct clsrvconf *srvconf;
2605     struct realm *newrealm = NULL;
2606     char *realmname, *s;
2607     pthread_t clientth;
2608     
2609     if (!conf->dynamiclookupcommand)
2610         return;
2611
2612     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2613     realmname = strrchr(id, '@');
2614     if (!realmname)
2615         return;
2616     realmname++;
2617     if (!*realmname)
2618         return;
2619     for (s = realmname; *s; s++)
2620         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2621             return;
2622     
2623     pthread_mutex_lock(&realm->subrealms_mutex);
2624     /* exit if we now already got a matching subrealm */
2625     if (id2realm(realm->subrealms, id))
2626         goto exit;
2627     srvconf = malloc(sizeof(struct clsrvconf));
2628     if (!srvconf) {
2629         debug(DBG_ERR, "malloc failed");
2630         goto exit;
2631     }
2632     *srvconf = *conf;
2633     if (!addserver(srvconf))
2634         goto errexit;
2635
2636     if (!realm->subrealms)
2637         realm->subrealms = list_create();
2638     if (!realm->subrealms)
2639         goto errexit;
2640     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2641     if (!newrealm)
2642         goto errexit;
2643
2644     /* add server and accserver to newrealm */
2645     newrealm->srvconfs = list_create();
2646     if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2647         debug(DBG_ERR, "malloc failed");
2648         goto errexit;
2649     }
2650     newrealm->accsrvconfs = list_create();
2651     if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2652         debug(DBG_ERR, "malloc failed");
2653         goto errexit;
2654     }
2655
2656     srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2657
2658     if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2659         debug(DBG_ERR, "pthread_create failed");
2660         goto errexit;
2661     }
2662     pthread_detach(clientth);
2663     goto exit;
2664     
2665  errexit:
2666     if (newrealm) {
2667         list_removedata(realm->subrealms, newrealm);
2668         freerealm(newrealm);
2669         if (!list_first(realm->subrealms)) {
2670             list_destroy(realm->subrealms);
2671             realm->subrealms = NULL;
2672         }
2673     }
2674     freeserver(srvconf->servers, 1);
2675     free(srvconf);
2676     debug(DBG_ERR, "failed to create dynamic server");
2677
2678  exit:
2679     pthread_mutex_unlock(&realm->subrealms_mutex);
2680 }
2681
2682 int dynamicconfig(struct server *server) {
2683     int ok, fd[2], status;
2684     pid_t pid;
2685     struct clsrvconf *conf = server->conf;
2686     struct gconffile *cf = NULL;
2687     
2688     /* for now we only learn hostname/address */
2689     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2690
2691     if (pipe(fd) > 0) {
2692         debug(DBG_ERR, "dynamicconfig: pipe error");
2693         goto errexit;
2694     }
2695     pid = fork();
2696     if (pid < 0) {
2697         debug(DBG_ERR, "dynamicconfig: fork error");
2698         close(fd[0]);
2699         close(fd[1]);
2700         goto errexit;
2701     } else if (pid == 0) {
2702         /* child */
2703         close(fd[0]);
2704         if (fd[1] != STDOUT_FILENO) {
2705             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2706                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2707             close(fd[1]);
2708         }
2709         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2710             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2711     }
2712
2713     close(fd[1]);
2714     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2715     ok = getgenericconfig(&cf, NULL,
2716                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2717                           NULL
2718                           );
2719     freegconf(&cf);
2720         
2721     if (waitpid(pid, &status, 0) < 0) {
2722         debug(DBG_ERR, "dynamicconfig: wait error");
2723         goto errexit;
2724     }
2725     
2726     if (status) {
2727         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2728         goto errexit;
2729     }
2730
2731     if (ok)
2732         return 1;
2733
2734  errexit:    
2735     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2736     return 0;
2737 }
2738
2739 int addmatchcertattr(struct clsrvconf *conf) {
2740     char *v;
2741     regex_t **r;
2742     
2743     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2744         r = &conf->certcnregex;
2745         v = conf->matchcertattr + 4;
2746     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2747         r = &conf->certuriregex;
2748         v = conf->matchcertattr + 20;
2749     } else
2750         return 0;
2751     if (!*v)
2752         return 0;
2753     /* regexp, remove optional trailing / if present */
2754     if (v[strlen(v) - 1] == '/')
2755         v[strlen(v) - 1] = '\0';
2756     if (!*v)
2757         return 0;
2758
2759     *r = malloc(sizeof(regex_t));
2760     if (!*r) {
2761         debug(DBG_ERR, "malloc failed");
2762         return 0;
2763     }
2764     if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2765         free(*r);
2766         *r = NULL;
2767         debug(DBG_ERR, "failed to compile regular expression %s", v);
2768         return 0;
2769     }
2770     return 1;
2771 }
2772
2773 /* should accept both names and numeric values, only numeric right now */
2774 uint8_t attrname2val(char *attrname) {
2775     int val = 0;
2776     
2777     val = atoi(attrname);
2778     return val > 0 && val < 256 ? val : 0;
2779 }
2780
2781 /* should accept both names and numeric values, only numeric right now */
2782 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2783     char *s;
2784     
2785     *vendor = atoi(attrname);
2786     s = strchr(attrname, ':');
2787     if (!s) {
2788         *type = -1;
2789         return 1;
2790     }
2791     *type = atoi(s + 1);
2792     return *type >= 0 && *type < 256;
2793 }
2794
2795 /* should accept both names and numeric values, only numeric right now */
2796 struct tlv *extractattr(char *nameval) {
2797     int len, name = 0;
2798     char *s;
2799     struct tlv *a;
2800     
2801     s = strchr(nameval, ':');
2802     name = atoi(nameval);
2803     if (!s || name < 1 || name > 255)
2804         return NULL;
2805     len = strlen(s + 1);
2806     if (len > 253)
2807         return NULL;
2808     a = malloc(sizeof(struct tlv));
2809     if (!a)
2810         return NULL;
2811     a->v = (uint8_t *)stringcopy(s + 1, 0);
2812     if (!a->v) {
2813         free(a);
2814         return NULL;
2815     }
2816     a->t = name;
2817     a->l = len;
2818     return a;
2819 }
2820
2821 /* should accept both names and numeric values, only numeric right now */
2822 struct modattr *extractmodattr(char *nameval) {
2823     int name = 0;
2824     char *s, *t;
2825     struct modattr *m;
2826
2827     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2828         s = nameval + 11;
2829         name = 1;
2830     } else {
2831         s = strchr(nameval, ':');
2832         name = atoi(nameval);
2833         if (!s || name < 1 || name > 255 || s[1] != '/')
2834             return NULL;
2835         s += 2;
2836     }
2837     /* regexp, remove optional trailing / if present */
2838     if (s[strlen(s) - 1] == '/')
2839         s[strlen(s) - 1] = '\0';
2840
2841     t = strchr(s, '/');
2842     if (!t)
2843         return NULL;
2844     *t = '\0';
2845     t++;
2846
2847     m = malloc(sizeof(struct modattr));
2848     if (!m) {
2849         debug(DBG_ERR, "malloc failed");
2850         return NULL;
2851     }
2852     m->t = name;
2853
2854     m->replacement = stringcopy(t, 0);
2855     if (!m->replacement) {
2856         free(m);
2857         debug(DBG_ERR, "malloc failed");
2858         return NULL;
2859     }
2860         
2861     m->regex = malloc(sizeof(regex_t));
2862     if (!m->regex) {
2863         free(m->replacement);
2864         free(m);
2865         debug(DBG_ERR, "malloc failed");
2866         return NULL;
2867     }
2868     
2869     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2870         free(m->regex);
2871         free(m->replacement);
2872         free(m);
2873         debug(DBG_ERR, "failed to compile regular expression %s", s);
2874         return NULL;
2875     }
2876
2877     return m;
2878 }
2879
2880 struct rewrite *getrewrite(char *alt1, char *alt2) {
2881     struct rewrite *r;
2882
2883     if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
2884         return r;
2885     if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
2886         return r;
2887     return NULL;
2888 }
2889
2890 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2891     struct rewrite *rewrite = NULL;
2892     int i, n;
2893     uint8_t *rma = NULL;
2894     uint32_t *p, *rmva = NULL;
2895     struct list *adda = NULL, *moda = NULL;
2896     struct tlv *a;
2897     struct modattr *m;
2898     
2899     if (rmattrs) {
2900         for (n = 0; rmattrs[n]; n++);
2901         rma = calloc(n + 1, sizeof(uint8_t));
2902         if (!rma)
2903             debugx(1, DBG_ERR, "malloc failed");
2904     
2905         for (i = 0; i < n; i++) {
2906             if (!(rma[i] = attrname2val(rmattrs[i])))
2907                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2908             free(rmattrs[i]);
2909         }
2910         free(rmattrs);
2911         rma[i] = 0;
2912     }
2913     
2914     if (rmvattrs) {
2915         for (n = 0; rmvattrs[n]; n++);
2916         rmva = calloc(2 * n + 1, sizeof(uint32_t));
2917         if (!rmva)
2918             debugx(1, DBG_ERR, "malloc failed");
2919     
2920         for (p = rmva, i = 0; i < n; i++, p += 2) {
2921             if (!vattrname2val(rmvattrs[i], p, p + 1))
2922                 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2923             free(rmvattrs[i]);
2924         }
2925         free(rmvattrs);
2926         *p = 0;
2927     }
2928     
2929     if (addattrs) {
2930         adda = list_create();
2931         if (!adda)
2932             debugx(1, DBG_ERR, "malloc failed");
2933         for (i = 0; addattrs[i]; i++) {
2934             a = extractattr(addattrs[i]);
2935             if (!a)
2936                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2937             free(addattrs[i]);
2938             if (!list_push(adda, a))
2939                 debugx(1, DBG_ERR, "malloc failed");
2940         }
2941         free(addattrs);
2942     }
2943
2944     if (modattrs) {
2945         moda = list_create();
2946         if (!moda)
2947             debugx(1, DBG_ERR, "malloc failed");
2948         for (i = 0; modattrs[i]; i++) {
2949             m = extractmodattr(modattrs[i]);
2950             if (!m)
2951                 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2952             free(modattrs[i]);
2953             if (!list_push(moda, m))
2954                 debugx(1, DBG_ERR, "malloc failed");
2955         }
2956         free(modattrs);
2957     }
2958         
2959     if (rma || rmva || adda || moda) {
2960         rewrite = malloc(sizeof(struct rewrite));
2961         if (!rewrite)
2962             debugx(1, DBG_ERR, "malloc failed");
2963         rewrite->removeattrs = rma;
2964         rewrite->removevendorattrs = rmva;
2965         rewrite->addattrs = adda;
2966         rewrite->modattrs = moda;
2967     }
2968     
2969     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2970         debugx(1, DBG_ERR, "malloc failed");
2971     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2972 }
2973
2974 void freeclsrvconf(struct clsrvconf *conf) {
2975     free(conf->name);
2976     free(conf->host);
2977     free(conf->port);
2978     free(conf->secret);
2979     free(conf->tls);
2980     free(conf->matchcertattr);
2981     if (conf->certcnregex)
2982         regfree(conf->certcnregex);
2983     if (conf->certuriregex)
2984         regfree(conf->certuriregex);
2985     free(conf->confrewritein);
2986     free(conf->confrewriteout);
2987     if (conf->rewriteusername) {
2988         if (conf->rewriteusername->regex)
2989             regfree(conf->rewriteusername->regex);
2990         free(conf->rewriteusername->replacement);
2991         free(conf->rewriteusername);
2992     }
2993     free(conf->dynamiclookupcommand);
2994     free(conf->rewritein);
2995     free(conf->rewriteout);
2996     if (conf->addrinfo)
2997         freeaddrinfo(conf->addrinfo);
2998     if (conf->lock) {
2999         pthread_mutex_destroy(conf->lock);
3000         free(conf->lock);
3001     }
3002     /* not touching ssl_ctx, clients and servers */
3003     free(conf);
3004 }
3005
3006 int mergeconfstring(char **dst, char **src) {
3007     char *t;
3008     
3009     if (*src) {
3010         *dst = *src;
3011         *src = NULL;
3012         return 1;
3013     }
3014     if (*dst) {
3015         t = stringcopy(*dst, 0);
3016         if (!t) {
3017             debug(DBG_ERR, "malloc failed");
3018             return 0;
3019         }
3020         *dst = t;
3021     }
3022     return 1;
3023 }
3024
3025 /* assumes dst is a shallow copy */
3026 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3027     if (!mergeconfstring(&dst->name, &src->name) ||
3028         !mergeconfstring(&dst->host, &src->host) ||
3029         !mergeconfstring(&dst->port, &src->port) ||
3030         !mergeconfstring(&dst->secret, &src->secret) ||
3031         !mergeconfstring(&dst->tls, &src->tls) ||
3032         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3033         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3034         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3035         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3036         return 0;
3037     if (src->pdef)
3038         dst->pdef = src->pdef;
3039     dst->statusserver = src->statusserver;
3040     dst->certnamecheck = src->certnamecheck;
3041     if (src->retryinterval != 255)
3042         dst->retryinterval = src->retryinterval;
3043     if (src->retrycount != 255)
3044         dst->retrycount = src->retrycount;
3045     return 1;
3046 }
3047
3048 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3049     struct clsrvconf *conf;
3050     char *conftype = NULL, *rewriteinalias = NULL;
3051     long int dupinterval = LONG_MIN;
3052     
3053     debug(DBG_DBG, "confclient_cb called for %s", block);
3054
3055     conf = malloc(sizeof(struct clsrvconf));
3056     if (!conf)
3057         debugx(1, DBG_ERR, "malloc failed");
3058     memset(conf, 0, sizeof(struct clsrvconf));
3059     conf->certnamecheck = 1;
3060     
3061     if (!getgenericconfig(cf, block,
3062                      "type", CONF_STR, &conftype,
3063                      "host", CONF_STR, &conf->host,
3064                      "secret", CONF_STR, &conf->secret,
3065                      "tls", CONF_STR, &conf->tls,
3066                      "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3067                      "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3068                      "DuplicateInterval", CONF_LINT, &dupinterval,
3069                      "rewrite", CONF_STR, &rewriteinalias,
3070                      "rewriteIn", CONF_STR, &conf->confrewritein,
3071                      "rewriteOut", CONF_STR, &conf->confrewriteout,
3072                      "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3073                      NULL
3074                           ))
3075         debugx(1, DBG_ERR, "configuration error");
3076     
3077     conf->name = stringcopy(val, 0);
3078     if (!conf->host)
3079         conf->host = stringcopy(val, 0);
3080     if (!conf->name || !conf->host)
3081         debugx(1, DBG_ERR, "malloc failed");
3082         
3083     if (!conftype)
3084         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3085     conf->type = protoname2int(conftype);
3086     conf->pdef = &protodefs[conf->type];
3087     if (!conf->pdef->name)
3088         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3089     free(conftype);
3090     
3091     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3092         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3093         if (!conf->ssl_ctx)
3094             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3095         if (conf->matchcertattr && !addmatchcertattr(conf))
3096             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3097     }
3098     
3099     if (dupinterval != LONG_MIN) {
3100         if (dupinterval < 0 || dupinterval > 255)
3101             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3102         conf->dupinterval = (uint8_t)dupinterval;
3103     } else
3104         conf->dupinterval = conf->pdef->duplicateintervaldefault;
3105     
3106     if (!conf->confrewritein)
3107         conf->confrewritein = rewriteinalias;
3108     else
3109         free(rewriteinalias);
3110     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3111     if (conf->confrewriteout)
3112         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3113     
3114     if (conf->confrewriteusername) {
3115         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3116         if (!conf->rewriteusername)
3117             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3118     }
3119     
3120     if (!resolvepeer(conf, 0))
3121         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3122     
3123     if (!conf->secret) {
3124         if (!conf->pdef->secretdefault)
3125             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3126         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3127         if (!conf->secret)
3128             debugx(1, DBG_ERR, "malloc failed");
3129     }
3130
3131     conf->lock = malloc(sizeof(pthread_mutex_t));
3132     if (!conf->lock)
3133         debugx(1, DBG_ERR, "malloc failed");
3134
3135     pthread_mutex_init(conf->lock, NULL);
3136     if (!list_push(clconfs, conf))
3137         debugx(1, DBG_ERR, "malloc failed");
3138     return 1;
3139 }
3140
3141 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3142     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3143         conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3144         if (!conf->ssl_ctx) {
3145             debug(DBG_ERR, "error in block %s, no tls context defined", block);
3146             return 0;
3147         }
3148         if (conf->matchcertattr && !addmatchcertattr(conf)) {
3149             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3150             return 0;
3151         }
3152     }
3153
3154     if (!conf->port) {
3155         conf->port = stringcopy(conf->pdef->portdefault, 0);
3156         if (!conf->port) {
3157             debug(DBG_ERR, "malloc failed");
3158             return 0;
3159         }
3160     }
3161     
3162     if (conf->retryinterval == 255)
3163         conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3164     if (conf->retrycount == 255)
3165         conf->retrycount = protodefs[conf->type].retrycountdefault;
3166     
3167     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3168     if (conf->confrewriteout)
3169         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3170
3171     if (!conf->secret) {
3172         if (!conf->pdef->secretdefault) {
3173             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3174             return 0;
3175         }
3176         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3177         if (!conf->secret) {
3178             debug(DBG_ERR, "malloc failed");
3179             return 0;
3180         }
3181     }
3182     
3183     if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3184         debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3185         return 0;
3186     }
3187     return 1;
3188 }
3189                         
3190 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3191     struct clsrvconf *conf, *resconf;
3192     char *conftype = NULL, *rewriteinalias = NULL;
3193     long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3194     
3195     debug(DBG_DBG, "confserver_cb called for %s", block);
3196
3197     conf = malloc(sizeof(struct clsrvconf));
3198     if (!conf) {
3199         debug(DBG_ERR, "malloc failed");
3200         return 0;
3201     }
3202     memset(conf, 0, sizeof(struct clsrvconf));
3203     resconf = (struct clsrvconf *)arg;
3204     if (resconf) {
3205         conf->statusserver = resconf->statusserver;
3206         conf->certnamecheck = resconf->certnamecheck;
3207     } else
3208         conf->certnamecheck = 1;
3209
3210     if (!getgenericconfig(cf, block,
3211                           "type", CONF_STR, &conftype,
3212                           "host", CONF_STR, &conf->host,
3213                           "port", CONF_STR, &conf->port,
3214                           "secret", CONF_STR, &conf->secret,
3215                           "tls", CONF_STR, &conf->tls,
3216                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3217                           "rewrite", CONF_STR, &rewriteinalias,
3218                           "rewriteIn", CONF_STR, &conf->confrewritein,
3219                           "rewriteOut", CONF_STR, &conf->confrewriteout,
3220                           "StatusServer", CONF_BLN, &conf->statusserver,
3221                           "RetryInterval", CONF_LINT, &retryinterval,
3222                           "RetryCount", CONF_LINT, &retrycount,
3223                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3224                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3225                           NULL
3226                           )) {
3227         debug(DBG_ERR, "configuration error");
3228         goto errexit;
3229     }
3230     
3231     conf->name = stringcopy(val, 0);
3232     if (!conf->name) {
3233         debug(DBG_ERR, "malloc failed");
3234         goto errexit;
3235     }
3236     if (!conf->host) {
3237         conf->host = stringcopy(val, 0);
3238         if (!conf->host) {
3239             debug(DBG_ERR, "malloc failed");
3240             goto errexit;
3241         }
3242     }
3243
3244     if (!conftype)
3245         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3246     conf->type = protoname2int(conftype);
3247     conf->pdef = &protodefs[conf->type];
3248     if (!conf->pdef->name) {
3249         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3250         goto errexit;
3251     }
3252     free(conftype);
3253     conftype = NULL;
3254
3255     if (!conf->confrewritein)
3256         conf->confrewritein = rewriteinalias;
3257     else
3258         free(rewriteinalias);
3259     rewriteinalias = NULL;
3260
3261     if (retryinterval != LONG_MIN) {
3262         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3263             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3264             goto errexit;
3265         }
3266         conf->retryinterval = (uint8_t)retryinterval;
3267     } else
3268         conf->retryinterval = 255;
3269     
3270     if (retrycount != LONG_MIN) {
3271         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3272             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3273             goto errexit;
3274         }
3275         conf->retrycount = (uint8_t)retrycount;
3276     } else
3277         conf->retrycount = 255;
3278     
3279     if (resconf) {
3280         if (!mergesrvconf(resconf, conf))
3281             goto errexit;
3282         free(conf);
3283         conf = resconf;
3284         if (conf->dynamiclookupcommand) {
3285             free(conf->dynamiclookupcommand);
3286             conf->dynamiclookupcommand = NULL;
3287         }
3288     }
3289
3290     if (resconf || !conf->dynamiclookupcommand) {
3291         if (!compileserverconfig(conf, block))
3292             goto errexit;
3293     }
3294     
3295     if (resconf)
3296         return 1;
3297         
3298     if (!list_push(srvconfs, conf)) {
3299         debug(DBG_ERR, "malloc failed");
3300         goto errexit;
3301     }
3302     return 1;
3303
3304  errexit:
3305     free(conftype);
3306     free(rewriteinalias);
3307     freeclsrvconf(conf);
3308     return 0;
3309 }
3310
3311 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3312     char **servers = NULL, **accservers = NULL, *msg = NULL;
3313     uint8_t accresp = 0;
3314     
3315     debug(DBG_DBG, "confrealm_cb called for %s", block);
3316     
3317     if (!getgenericconfig(cf, block,
3318                      "server", CONF_MSTR, &servers,
3319                      "accountingServer", CONF_MSTR, &accservers,
3320                      "ReplyMessage", CONF_STR, &msg,
3321                      "AccountingResponse", CONF_BLN, &accresp,
3322                      NULL
3323                           ))
3324         debugx(1, DBG_ERR, "configuration error");
3325
3326     addrealm(realms, val, servers, accservers, msg, accresp);
3327     return 1;
3328 }
3329
3330 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3331     struct tls *conf;
3332     
3333     debug(DBG_DBG, "conftls_cb called for %s", block);
3334     
3335     conf = malloc(sizeof(struct tls));
3336     if (!conf) {
3337         debug(DBG_ERR, "conftls_cb: malloc failed");
3338         return 0;
3339     }
3340     memset(conf, 0, sizeof(struct tls));
3341     
3342     if (!getgenericconfig(cf, block,
3343                      "CACertificateFile", CONF_STR, &conf->cacertfile,
3344                      "CACertificatePath", CONF_STR, &conf->cacertpath,
3345                      "CertificateFile", CONF_STR, &conf->certfile,
3346                      "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3347                      "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3348                      "CRLCheck", CONF_BLN, &conf->crlcheck,
3349                      NULL
3350                           )) {
3351         debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3352         goto errexit;
3353     }
3354     if (!conf->certfile || !conf->certkeyfile) {
3355         debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3356         goto errexit;
3357     }
3358     if (!conf->cacertfile && !conf->cacertpath) {
3359         debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3360         goto errexit;
3361     }
3362
3363     conf->name = stringcopy(val, 0);
3364     if (!conf->name) {
3365         debug(DBG_ERR, "conftls_cb: malloc failed");
3366         goto errexit;
3367     }
3368
3369     if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3370         debug(DBG_ERR, "conftls_cb: malloc failed");
3371         goto errexit;
3372     }
3373             
3374     debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3375     return 1;
3376
3377  errexit:
3378     free(conf->cacertfile);
3379     free(conf->cacertpath);
3380     free(conf->certfile);
3381     free(conf->certkeyfile);
3382     free(conf->certkeypwd);
3383     free(conf);
3384     return 0;
3385 }
3386
3387 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3388     char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3389     
3390     debug(DBG_DBG, "confrewrite_cb called for %s", block);
3391     
3392     if (!getgenericconfig(cf, block,
3393                      "removeAttribute", CONF_MSTR, &rmattrs,
3394                      "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3395                      "addAttribute", CONF_MSTR, &addattrs,
3396                      "modifyAttribute", CONF_MSTR, &modattrs,
3397                      NULL
3398                           ))
3399         debugx(1, DBG_ERR, "configuration error");
3400     addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3401     return 1;
3402 }
3403
3404 void getmainconfig(const char *configfile) {
3405     long int loglevel = LONG_MIN;
3406     struct gconffile *cfs;
3407
3408     cfs = openconfigfile(configfile);
3409     memset(&options, 0, sizeof(options));
3410     
3411     clconfs = list_create();
3412     if (!clconfs)
3413         debugx(1, DBG_ERR, "malloc failed");
3414     
3415     srvconfs = list_create();
3416     if (!srvconfs)
3417         debugx(1, DBG_ERR, "malloc failed");
3418     
3419     realms = list_create();
3420     if (!realms)
3421         debugx(1, DBG_ERR, "malloc failed");    
3422  
3423     tlsconfs = hash_create();
3424     if (!tlsconfs)
3425         debugx(1, DBG_ERR, "malloc failed");
3426     
3427     rewriteconfs = hash_create();
3428     if (!rewriteconfs)
3429         debugx(1, DBG_ERR, "malloc failed");    
3430  
3431     if (!getgenericconfig(&cfs, NULL,
3432                           "ListenUDP", CONF_MSTR, &options.listenudp,
3433                           "ListenTCP", CONF_MSTR, &options.listentcp,
3434                           "ListenTLS", CONF_MSTR, &options.listentls,
3435                           "ListenDTLS", CONF_MSTR, &options.listendtls,
3436                           "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3437                           "SourceUDP", CONF_STR, &options.sourceudp,
3438                           "SourceTCP", CONF_STR, &options.sourcetcp,
3439                           "SourceTLS", CONF_STR, &options.sourcetls,
3440                           "SourceDTLS", CONF_STR, &options.sourcedtls,
3441                           "LogLevel", CONF_LINT, &loglevel,
3442                           "LogDestination", CONF_STR, &options.logdestination,
3443                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3444                           "Client", CONF_CBK, confclient_cb, NULL,
3445                           "Server", CONF_CBK, confserver_cb, NULL,
3446                           "Realm", CONF_CBK, confrealm_cb, NULL,
3447                           "TLS", CONF_CBK, conftls_cb, NULL,
3448                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3449                           NULL
3450                           ))
3451         debugx(1, DBG_ERR, "configuration error");
3452     
3453     if (loglevel != LONG_MIN) {
3454         if (loglevel < 1 || loglevel > 4)
3455             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3456         options.loglevel = (uint8_t)loglevel;
3457     }
3458 }
3459
3460 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3461     int c;
3462
3463     while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3464         switch (c) {
3465         case 'c':
3466             *configfile = optarg;
3467             break;
3468         case 'd':
3469             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3470                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3471             *loglevel = *optarg - '0';
3472             break;
3473         case 'f':
3474             *foreground = 1;
3475             break;
3476         case 'p':
3477             *pretend = 1;
3478             break;
3479         case 'v':
3480                 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3481         default:
3482             goto usage;
3483         }
3484     }
3485     if (!(argc - optind))
3486         return;
3487
3488  usage:
3489     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3490 }
3491
3492 #ifdef SYS_SOLARIS9
3493 int daemon(int a, int b) {
3494     int i;
3495
3496     if (fork())
3497         exit(0);
3498
3499     setsid();
3500
3501     for (i = 0; i < 3; i++) {
3502         close(i);
3503         open("/dev/null", O_RDWR);
3504     }
3505     return 1;
3506 }
3507 #endif
3508
3509 void *sighandler(void *arg) {
3510     sigset_t sigset;
3511     int sig;
3512
3513     for(;;) {
3514         sigemptyset(&sigset);
3515         sigaddset(&sigset, SIGPIPE);
3516         sigwait(&sigset, &sig);
3517         /* only get SIGPIPE right now, so could simplify below code */
3518         switch (sig) {
3519         case 0:
3520             /* completely ignoring this */
3521             break;
3522         case SIGPIPE:
3523             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3524             break;
3525         default:
3526             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3527         }
3528     }
3529 }
3530
3531 int main(int argc, char **argv) {
3532     pthread_t sigth;
3533     sigset_t sigset;
3534     struct list_node *entry;
3535     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3536     char *configfile = NULL;
3537     struct clsrvconf *srvconf;
3538     int i;
3539     
3540     debug_init("radsecproxy");
3541     debug_set_level(DEBUG_LEVEL);
3542     
3543     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3544     if (loglevel)
3545         debug_set_level(loglevel);
3546     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3547     if (loglevel)
3548         options.loglevel = loglevel;
3549     else if (options.loglevel)
3550         debug_set_level(options.loglevel);
3551     if (!foreground)
3552         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3553     free(options.logdestination);
3554
3555     if (!list_first(clconfs))
3556         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3557     if (!list_first(realms))
3558         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3559
3560     if (pretend)
3561         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3562
3563     if (!foreground && (daemon(0, 0) < 0))
3564         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3565     
3566     debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3567
3568     sigemptyset(&sigset);
3569     /* exit on all but SIGPIPE, ignore more? */
3570     sigaddset(&sigset, SIGPIPE);
3571     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3572     pthread_create(&sigth, NULL, sighandler, NULL);
3573
3574     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3575         srvconf = (struct clsrvconf *)entry->data;
3576         if (srvconf->dynamiclookupcommand)
3577             continue;
3578         if (!addserver(srvconf))
3579             debugx(1, DBG_ERR, "failed to add server");
3580         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3581                            (void *)(srvconf->servers)))
3582             debugx(1, DBG_ERR, "pthread_create failed");
3583     }
3584     /* srcprotores for UDP no longer needed */
3585     if (srcprotores[RAD_UDP]) {
3586         freeaddrinfo(srcprotores[RAD_UDP]);
3587         srcprotores[RAD_UDP] = NULL;
3588     }
3589
3590     for (i = 0; protodefs[i].name; i++)
3591         if (protodefs[i].initextra)
3592             protodefs[i].initextra();
3593     
3594     if (find_clconf_type(RAD_TCP, NULL))
3595         createlisteners(RAD_TCP, options.listentcp);
3596     
3597     if (find_clconf_type(RAD_TLS, NULL))
3598         createlisteners(RAD_TLS, options.listentls);
3599     
3600     if (find_clconf_type(RAD_DTLS, NULL))
3601         createlisteners(RAD_DTLS, options.listendtls);
3602     
3603     if (find_clconf_type(RAD_UDP, NULL)) {
3604         createlisteners(RAD_UDP, options.listenudp);
3605         if (options.listenaccudp)
3606             createlisteners(RAD_UDP, options.listenaccudp);
3607     }
3608     
3609     /* just hang around doing nothing, anything to do here? */
3610     for (;;)
3611         sleep(1000);
3612 }