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