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