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