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