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