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