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