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