4 debug levels, 3 default
[radsecproxy.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006, 2007 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 /* TODO:
10  * accounting
11  * radius keep alives (server status)
12  * setsockopt(keepalive...), check if openssl has some keepalive feature
13 */
14
15 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
16  *              rd is responsible for init and launching wr
17  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
18  *          each tlsserverrd launches tlsserverwr
19  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
20  *          for init and launching rd
21  *
22  * serverrd will receive a request, processes it and puts it in the requestq of
23  *          the appropriate clientwr
24  * clientwr monitors its requestq and sends requests
25  * clientrd looks for responses, processes them and puts them in the replyq of
26  *          the peer the request came from
27  * serverwr monitors its reply and sends replies
28  *
29  * In addition to the main thread, we have:
30  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
31  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
32  * For each TLS peer connecting to us there will be 2 more TLS threads
33  *       This is only for connected peers
34  * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
35  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
36 */
37
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <netdb.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <sys/time.h>
44 #include <libgen.h>
45 #include <pthread.h>
46 #include <openssl/ssl.h>
47 #include <openssl/rand.h>
48 #include <openssl/err.h>
49 #include <openssl/md5.h>
50 #include <openssl/hmac.h>
51 #include "debug.h"
52 #include "radsecproxy.h"
53
54 static struct options options;
55 static struct client *clients;
56 static struct server *servers;
57
58 static int client_udp_count = 0;
59 static int client_tls_count = 0;
60 static int client_count = 0;
61 static int server_udp_count = 0;
62 static int server_tls_count = 0;
63 static int server_count = 0;
64
65 static struct peer *tcp_server_listen;
66 static struct peer *udp_server_listen;
67 static struct replyq udp_server_replyq;
68 static int udp_server_sock = -1;
69 static pthread_mutex_t *ssl_locks;
70 static long *ssl_lock_count;
71 static SSL_CTX *ssl_ctx = NULL;
72 extern int optind;
73 extern char *optarg;
74
75 /* callbacks for making OpenSSL thread safe */
76 unsigned long ssl_thread_id() {
77         return (unsigned long)pthread_self();
78 }
79
80 void ssl_locking_callback(int mode, int type, const char *file, int line) {
81     if (mode & CRYPTO_LOCK) {
82         pthread_mutex_lock(&ssl_locks[type]);
83         ssl_lock_count[type]++;
84     } else
85         pthread_mutex_unlock(&ssl_locks[type]);
86 }
87
88 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
89     int pwdlen = strlen(userdata);
90     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
91         return 0;
92     memcpy(buf, userdata, pwdlen);
93     return pwdlen;
94 }
95
96 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
97   char buf[256];
98   X509 *err_cert;
99   int err, depth;
100
101   err_cert = X509_STORE_CTX_get_current_cert(ctx);
102   err = X509_STORE_CTX_get_error(ctx);
103   depth = X509_STORE_CTX_get_error_depth(ctx);
104
105   if (depth > MAX_CERT_DEPTH) {
106       ok = 0;
107       err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
108       X509_STORE_CTX_set_error(ctx, err);
109   }
110
111   if (!ok) {
112       X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
113       debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
114
115       switch (err) {
116       case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
117           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
118           debug(DBG_WARN, "\tIssuer=%s", buf);
119           break;
120       case X509_V_ERR_CERT_NOT_YET_VALID:
121       case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
122           debug(DBG_WARN, "\tCertificate not yet valid");
123           break;
124       case X509_V_ERR_CERT_HAS_EXPIRED:
125           debug(DBG_WARN, "Certificate has expired");
126           break;
127       case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
128           debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
129           break;
130       }
131   }
132 #ifdef DEBUG  
133   printf("certificate verify returns %d\n", ok);
134 #endif  
135   return ok;
136 }
137
138 SSL_CTX *ssl_init() {
139     SSL_CTX *ctx;
140     int i;
141     unsigned long error;
142     
143     if (!options.tlscertificatefile || !options.tlscertificatekeyfile)
144         debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS");
145
146     if (!options.tlscacertificatefile && !options.tlscacertificatepath)
147         debugx(1, DBG_ERR, "CA Certificate file/path need to be configured");
148
149     ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
150     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
151     for (i = 0; i < CRYPTO_num_locks(); i++) {
152         ssl_lock_count[i] = 0;
153         pthread_mutex_init(&ssl_locks[i], NULL);
154     }
155     CRYPTO_set_id_callback(ssl_thread_id);
156     CRYPTO_set_locking_callback(ssl_locking_callback);
157
158     SSL_load_error_strings();
159     SSL_library_init();
160
161     while (!RAND_status()) {
162         time_t t = time(NULL);
163         pid_t pid = getpid();
164         RAND_seed((unsigned char *)&t, sizeof(time_t));
165         RAND_seed((unsigned char *)&pid, sizeof(pid));
166     }
167
168     ctx = SSL_CTX_new(TLSv1_method());
169     if (options.tlscertificatekeypassword) {
170         SSL_CTX_set_default_passwd_cb_userdata(ctx, options.tlscertificatekeypassword);
171         SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
172     }
173     if (SSL_CTX_use_certificate_chain_file(ctx, options.tlscertificatefile) &&
174         SSL_CTX_use_PrivateKey_file(ctx, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) &&
175         SSL_CTX_check_private_key(ctx) &&
176         SSL_CTX_load_verify_locations(ctx, options.tlscacertificatefile, options.tlscacertificatepath)) {
177         SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
178         SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
179         return ctx;
180     }
181
182     while ((error = ERR_get_error()))
183         debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
184     debug(DBG_ERR, "Error initialising SSL/TLS");
185     exit(1);
186 }    
187
188 #ifdef DEBUG
189 void printauth(char *s, unsigned char *t) {
190     int i;
191     printf("%s:", s);
192     for (i = 0; i < 16; i++)
193             printf("%02x ", t[i]);
194     printf("\n");
195 }
196 #endif
197
198 int resolvepeer(struct peer *peer, int ai_flags) {
199     struct addrinfo hints, *addrinfo;
200     
201     memset(&hints, 0, sizeof(hints));
202     hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
203     hints.ai_family = AF_UNSPEC;
204     hints.ai_flags = ai_flags;
205     if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
206         debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
207         return 0;
208     }
209
210     if (peer->addrinfo)
211         freeaddrinfo(peer->addrinfo);
212     peer->addrinfo = addrinfo;
213     return 1;
214 }         
215
216 int connecttoserver(struct addrinfo *addrinfo) {
217     int s;
218     struct addrinfo *res;
219     
220     for (res = addrinfo; res; res = res->ai_next) {
221         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
222         if (s < 0) {
223             debug(DBG_WARN, "connecttoserver: socket failed");
224             continue;
225         }
226         if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
227             break;
228         debug(DBG_WARN, "connecttoserver: connect failed");
229         close(s);
230         s = -1;
231     }
232     return s;
233 }         
234
235 int bindtoaddr(struct addrinfo *addrinfo) {
236     int s, on = 1;
237     struct addrinfo *res;
238     
239     for (res = addrinfo; res; res = res->ai_next) {
240         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
241         if (s < 0) {
242             debug(DBG_WARN, "bindtoaddr: socket failed");
243             continue;
244         }
245         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
246         if (!bind(s, res->ai_addr, res->ai_addrlen))
247             return s;
248         debug(DBG_WARN, "bindtoaddr: bind failed");
249         close(s);
250     }
251     return -1;
252 }         
253
254 /* returns the client with matching address, or NULL */
255 /* if client argument is not NULL, we only check that one client */
256 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
257     struct sockaddr_in6 *sa6;
258     struct in_addr *a4 = NULL;
259     struct client *c;
260     int i;
261     struct addrinfo *res;
262
263     if (addr->sa_family == AF_INET6) {
264         sa6 = (struct sockaddr_in6 *)addr;
265         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
266             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
267     } else
268         a4 = &((struct sockaddr_in *)addr)->sin_addr;
269
270     c = (client ? client : clients);
271     for (i = 0; i < client_count; i++) {
272         if (c->peer.type == type)
273             for (res = c->peer.addrinfo; res; res = res->ai_next)
274                 if ((a4 && res->ai_family == AF_INET &&
275                      !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
276                     (res->ai_family == AF_INET6 &&
277                      !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
278                     return c;
279         if (client)
280             break;
281         c++;
282     }
283     return NULL;
284 }
285
286 /* returns the server with matching address, or NULL */
287 /* if server argument is not NULL, we only check that one server */
288 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
289     struct sockaddr_in6 *sa6;
290     struct in_addr *a4 = NULL;
291     struct server *s;
292     int i;
293     struct addrinfo *res;
294
295     if (addr->sa_family == AF_INET6) {
296         sa6 = (struct sockaddr_in6 *)addr;
297         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
298             a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
299     } else
300         a4 = &((struct sockaddr_in *)addr)->sin_addr;
301
302     s = (server ? server : servers);
303     for (i = 0; i < server_count; i++) {
304         if (s->peer.type == type)
305             for (res = s->peer.addrinfo; res; res = res->ai_next)
306                 if ((a4 && res->ai_family == AF_INET &&
307                      !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
308                     (res->ai_family == AF_INET6 &&
309                      !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
310                     return s;
311         if (server)
312             break;
313         s++;
314     }
315     return NULL;
316 }
317
318 /* exactly one of client and server must be non-NULL */
319 /* if *peer == NULL we return who we received from, else require it to be from peer */
320 /* return from in sa if not NULL */
321 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
322     int cnt, len;
323     void *f;
324     unsigned char buf[65536], *rad;
325     struct sockaddr_storage from;
326     socklen_t fromlen = sizeof(from);
327
328     for (;;) {
329         cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
330         if (cnt == -1) {
331             debug(DBG_WARN, "radudpget: recv failed");
332             continue;
333         }
334         debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
335
336         if (cnt < 20) {
337             debug(DBG_WARN, "radudpget: packet too small");
338             continue;
339         }
340     
341         len = RADLEN(buf);
342
343         if (cnt < len) {
344             debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
345             continue;
346         }
347         if (cnt > len)
348             debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
349
350         f = (client
351              ? (void *)find_client('U', (struct sockaddr *)&from, *client)
352              : (void *)find_server('U', (struct sockaddr *)&from, *server));
353         if (!f) {
354             debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
355             continue;
356         }
357
358         rad = malloc(len);
359         if (rad)
360             break;
361         debug(DBG_ERR, "radudpget: malloc failed");
362     }
363     memcpy(rad, buf, len);
364     if (client)
365         *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
366     else
367         *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
368     if (sa)
369         *sa = from;
370     return rad;
371 }
372
373 int tlsverifycert(struct peer *peer) {
374     int l, loc;
375     X509 *cert;
376     X509_NAME *nm;
377     X509_NAME_ENTRY *e;
378     unsigned char *v;
379     unsigned long error;
380
381     if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
382         debug(DBG_ERR, "tlsverifycert: basic validation failed");
383         while ((error = ERR_get_error()))
384             debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
385         return 0;
386     }
387
388     cert = SSL_get_peer_certificate(peer->ssl);
389     if (!cert) {
390         debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
391         return 0;
392     }
393     nm = X509_get_subject_name(cert);
394     loc = -1;
395     for (;;) {
396         loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
397         if (loc == -1)
398             break;
399         e = X509_NAME_get_entry(nm, loc);
400         l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
401         if (l < 0)
402             continue;
403 #ifdef DEBUG
404         {
405             int i;
406             printf("cn: ");
407             for (i = 0; i < l; i++)
408                 printf("%c", v[i]);
409             printf("\n");
410         }
411 #endif  
412         if (l == strlen(peer->host) && !strncasecmp(peer->host, (char *)v, l)) {
413             debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
414             return 1;
415         }
416         debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
417     }
418     X509_free(cert);
419     return 0;
420 }
421
422 void tlsconnect(struct server *server, struct timeval *when, char *text) {
423     struct timeval now;
424     time_t elapsed;
425
426     debug(DBG_DBG, "tlsconnect called from %s", text);
427     pthread_mutex_lock(&server->lock);
428     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
429         /* already reconnected, nothing to do */
430         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
431         pthread_mutex_unlock(&server->lock);
432         return;
433     }
434
435     debug(DBG_DBG, "tlsconnect %s", text);
436
437     for (;;) {
438         gettimeofday(&now, NULL);
439         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
440         if (server->connectionok) {
441             server->connectionok = 0;
442             sleep(10);
443         } else if (elapsed < 5)
444             sleep(10);
445         else if (elapsed < 600) {
446             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
447             sleep(elapsed);
448         } else if (elapsed < 1000) {
449             debug(DBG_INFO, "tlsconnect: sleeping %ds", 900);
450             sleep(900);
451         } else
452             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
453         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
454         if (server->sock >= 0)
455             close(server->sock);
456         if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
457             debug(DBG_ERR, "tlsconnect: connecttoserver failed");
458             continue;
459         }
460         
461         SSL_free(server->peer.ssl);
462         server->peer.ssl = SSL_new(ssl_ctx);
463         SSL_set_fd(server->peer.ssl, server->sock);
464         if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
465             break;
466     }
467     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
468     gettimeofday(&server->lastconnecttry, NULL);
469     pthread_mutex_unlock(&server->lock);
470 }
471
472 unsigned char *radtlsget(SSL *ssl) {
473     int cnt, total, len;
474     unsigned char buf[4], *rad;
475
476     for (;;) {
477         for (total = 0; total < 4; total += cnt) {
478             cnt = SSL_read(ssl, buf + total, 4 - total);
479             if (cnt <= 0) {
480                 debug(DBG_ERR, "radtlsget: connection lost");
481                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
482                     /* remote end sent close_notify, send one back */
483                     SSL_shutdown(ssl);
484                 }
485                 return NULL;
486             }
487         }
488
489         len = RADLEN(buf);
490         rad = malloc(len);
491         if (!rad) {
492             debug(DBG_ERR, "radtlsget: malloc failed");
493             continue;
494         }
495         memcpy(rad, buf, 4);
496
497         for (; total < len; total += cnt) {
498             cnt = SSL_read(ssl, rad + total, len - total);
499             if (cnt <= 0) {
500                 debug(DBG_ERR, "radtlsget: connection lost");
501                 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
502                     /* remote end sent close_notify, send one back */
503                     SSL_shutdown(ssl);
504                 }
505                 free(rad);
506                 return NULL;
507             }
508         }
509     
510         if (total >= 20)
511             break;
512         
513         free(rad);
514         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
515     }
516     
517     debug(DBG_DBG, "radtlsget: got %d bytes", total);
518     return rad;
519 }
520
521 int clientradput(struct server *server, unsigned char *rad) {
522     int cnt;
523     size_t len;
524     unsigned long error;
525     struct timeval lastconnecttry;
526     
527     len = RADLEN(rad);
528     if (server->peer.type == 'U') {
529         if (send(server->sock, rad, len, 0) >= 0) {
530             debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
531             return 1;
532         }
533         debug(DBG_WARN, "clientradput: send failed");
534         return 0;
535     }
536
537     lastconnecttry = server->lastconnecttry;
538     while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
539         while ((error = ERR_get_error()))
540             debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
541         tlsconnect(server, &lastconnecttry, "clientradput");
542         lastconnecttry = server->lastconnecttry;
543     }
544
545     server->connectionok = 1;
546     debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
547            cnt, len, server->peer.host);
548     return 1;
549 }
550
551 int radsign(unsigned char *rad, unsigned char *sec) {
552     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
553     static unsigned char first = 1;
554     static EVP_MD_CTX mdctx;
555     unsigned int md_len;
556     int result;
557     
558     pthread_mutex_lock(&lock);
559     if (first) {
560         EVP_MD_CTX_init(&mdctx);
561         first = 0;
562     }
563
564     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
565         EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
566         EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
567         EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
568         md_len == 16);
569     pthread_mutex_unlock(&lock);
570     return result;
571 }
572
573 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
574     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
575     static unsigned char first = 1;
576     static EVP_MD_CTX mdctx;
577     unsigned char hash[EVP_MAX_MD_SIZE];
578     unsigned int len;
579     int result;
580     
581     pthread_mutex_lock(&lock);
582     if (first) {
583         EVP_MD_CTX_init(&mdctx);
584         first = 0;
585     }
586
587     len = RADLEN(rad);
588     
589     result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
590               EVP_DigestUpdate(&mdctx, rad, 4) &&
591               EVP_DigestUpdate(&mdctx, reqauth, 16) &&
592               (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
593               EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
594               EVP_DigestFinal_ex(&mdctx, hash, &len) &&
595               len == 16 &&
596               !memcmp(hash, rad + 4, 16));
597     pthread_mutex_unlock(&lock);
598     return result;
599 }
600               
601 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
602     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
603     static unsigned char first = 1;
604     static HMAC_CTX hmacctx;
605     unsigned int md_len;
606     uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
607     
608     pthread_mutex_lock(&lock);
609     if (first) {
610         HMAC_CTX_init(&hmacctx);
611         first = 0;
612     }
613
614     memcpy(auth, authattr, 16);
615     memset(authattr, 0, 16);
616     md_len = 0;
617     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
618     HMAC_Update(&hmacctx, rad, RADLEN(rad));
619     HMAC_Final(&hmacctx, hash, &md_len);
620     memcpy(authattr, auth, 16);
621     if (md_len != 16) {
622         debug(DBG_WARN, "message auth computation failed");
623         pthread_mutex_unlock(&lock);
624         return 0;
625     }
626
627     if (memcmp(auth, hash, 16)) {
628         debug(DBG_WARN, "message authenticator, wrong value");
629         pthread_mutex_unlock(&lock);
630         return 0;
631     }   
632         
633     pthread_mutex_unlock(&lock);
634     return 1;
635 }
636
637 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
638     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
639     static unsigned char first = 1;
640     static HMAC_CTX hmacctx;
641     unsigned int md_len;
642
643     if (!authattrval)
644         return 1;
645     
646     pthread_mutex_lock(&lock);
647     if (first) {
648         HMAC_CTX_init(&hmacctx);
649         first = 0;
650     }
651
652     memset(authattrval, 0, 16);
653     md_len = 0;
654     HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
655     HMAC_Update(&hmacctx, rad, RADLEN(rad));
656     HMAC_Final(&hmacctx, authattrval, &md_len);
657     if (md_len != 16) {
658         debug(DBG_WARN, "message auth computation failed");
659         pthread_mutex_unlock(&lock);
660         return 0;
661     }
662
663     pthread_mutex_unlock(&lock);
664     return 1;
665 }
666
667 void sendrq(struct server *to, struct client *from, struct request *rq) {
668     int i;
669     
670     pthread_mutex_lock(&to->newrq_mutex);
671     /* might simplify if only try nextid, might be ok */
672     for (i = to->nextid; i < MAX_REQUESTS; i++)
673         if (!to->requests[i].buf)
674             break;
675     if (i == MAX_REQUESTS) {
676         for (i = 0; i < to->nextid; i++)
677             if (!to->requests[i].buf)
678                 break;
679         if (i == to->nextid) {
680             debug(DBG_WARN, "No room in queue, dropping request");
681             pthread_mutex_unlock(&to->newrq_mutex);
682             return;
683         }
684     }
685     
686     to->nextid = i + 1;
687     rq->buf[1] = (char)i;
688     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
689     
690     if (!createmessageauth(rq->buf, rq->messageauthattrval, to->peer.secret))
691         return;
692
693     to->requests[i] = *rq;
694
695     if (!to->newrq) {
696         to->newrq = 1;
697         debug(DBG_DBG, "signalling client writer");
698         pthread_cond_signal(&to->newrq_cond);
699     }
700     pthread_mutex_unlock(&to->newrq_mutex);
701 }
702
703 void sendreply(struct client *to, struct server *from, unsigned char *buf, struct sockaddr_storage *tosa) {
704     struct replyq *replyq = to->replyq;
705     
706     pthread_mutex_lock(&replyq->count_mutex);
707     if (replyq->count == replyq->size) {
708         debug(DBG_WARN, "No room in queue, dropping request");
709         pthread_mutex_unlock(&replyq->count_mutex);
710         return;
711     }
712
713     replyq->replies[replyq->count].buf = buf;
714     if (tosa)
715         replyq->replies[replyq->count].tosa = *tosa;
716     replyq->count++;
717
718     if (replyq->count == 1) {
719         debug(DBG_DBG, "signalling client writer");
720         pthread_cond_signal(&replyq->count_cond);
721     }
722     pthread_mutex_unlock(&replyq->count_mutex);
723 }
724
725 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
726     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
727     static unsigned char first = 1;
728     static EVP_MD_CTX mdctx;
729     unsigned char hash[EVP_MAX_MD_SIZE], *input;
730     unsigned int md_len;
731     uint8_t i, offset = 0, out[128];
732     
733     pthread_mutex_lock(&lock);
734     if (first) {
735         EVP_MD_CTX_init(&mdctx);
736         first = 0;
737     }
738
739     input = auth;
740     for (;;) {
741         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
742             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
743             !EVP_DigestUpdate(&mdctx, input, 16) ||
744             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
745             md_len != 16) {
746             pthread_mutex_unlock(&lock);
747             return 0;
748         }
749         for (i = 0; i < 16; i++)
750             out[offset + i] = hash[i] ^ in[offset + i];
751         input = out + offset - 16;
752         offset += 16;
753         if (offset == len)
754             break;
755     }
756     memcpy(in, out, len);
757     pthread_mutex_unlock(&lock);
758     return 1;
759 }
760
761 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
762     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
763     static unsigned char first = 1;
764     static EVP_MD_CTX mdctx;
765     unsigned char hash[EVP_MAX_MD_SIZE], *input;
766     unsigned int md_len;
767     uint8_t i, offset = 0, out[128];
768     
769     pthread_mutex_lock(&lock);
770     if (first) {
771         EVP_MD_CTX_init(&mdctx);
772         first = 0;
773     }
774
775     input = auth;
776     for (;;) {
777         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
778             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
779             !EVP_DigestUpdate(&mdctx, input, 16) ||
780             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
781             md_len != 16) {
782             pthread_mutex_unlock(&lock);
783             return 0;
784         }
785         for (i = 0; i < 16; i++)
786             out[offset + i] = hash[i] ^ in[offset + i];
787         input = in + offset;
788         offset += 16;
789         if (offset == len)
790             break;
791     }
792     memcpy(in, out, len);
793     pthread_mutex_unlock(&lock);
794     return 1;
795 }
796
797 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
798     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
799     static unsigned char first = 1;
800     static EVP_MD_CTX mdctx;
801     unsigned char hash[EVP_MAX_MD_SIZE];
802     unsigned int md_len;
803     uint8_t i, offset;
804     
805     pthread_mutex_lock(&lock);
806     if (first) {
807         EVP_MD_CTX_init(&mdctx);
808         first = 0;
809     }
810
811 #if 0    
812     printf("msppencrypt auth in: ");
813     for (i = 0; i < 16; i++)
814         printf("%02x ", auth[i]);
815     printf("\n");
816     
817     printf("msppencrypt salt in: ");
818     for (i = 0; i < 2; i++)
819         printf("%02x ", salt[i]);
820     printf("\n");
821     
822     printf("msppencrypt in: ");
823     for (i = 0; i < len; i++)
824         printf("%02x ", text[i]);
825     printf("\n");
826 #endif
827     
828     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
829         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
830         !EVP_DigestUpdate(&mdctx, auth, 16) ||
831         !EVP_DigestUpdate(&mdctx, salt, 2) ||
832         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
833         pthread_mutex_unlock(&lock);
834         return 0;
835     }
836
837 #if 0    
838     printf("msppencrypt hash: ");
839     for (i = 0; i < 16; i++)
840         printf("%02x ", hash[i]);
841     printf("\n");
842 #endif
843     
844     for (i = 0; i < 16; i++)
845         text[i] ^= hash[i];
846     
847     for (offset = 16; offset < len; offset += 16) {
848 #if 0   
849         printf("text + offset - 16 c(%d): ", offset / 16);
850         for (i = 0; i < 16; i++)
851             printf("%02x ", (text + offset - 16)[i]);
852         printf("\n");
853 #endif
854         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
855             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
856             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
857             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
858             md_len != 16) {
859             pthread_mutex_unlock(&lock);
860             return 0;
861         }
862 #if 0   
863         printf("msppencrypt hash: ");
864         for (i = 0; i < 16; i++)
865             printf("%02x ", hash[i]);
866         printf("\n");
867 #endif    
868         
869         for (i = 0; i < 16; i++)
870             text[offset + i] ^= hash[i];
871     }
872     
873 #if 0
874     printf("msppencrypt out: ");
875     for (i = 0; i < len; i++)
876         printf("%02x ", text[i]);
877     printf("\n");
878 #endif
879
880     pthread_mutex_unlock(&lock);
881     return 1;
882 }
883
884 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
885     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
886     static unsigned char first = 1;
887     static EVP_MD_CTX mdctx;
888     unsigned char hash[EVP_MAX_MD_SIZE];
889     unsigned int md_len;
890     uint8_t i, offset;
891     char plain[255];
892     
893     pthread_mutex_lock(&lock);
894     if (first) {
895         EVP_MD_CTX_init(&mdctx);
896         first = 0;
897     }
898
899 #if 0    
900     printf("msppdecrypt auth in: ");
901     for (i = 0; i < 16; i++)
902         printf("%02x ", auth[i]);
903     printf("\n");
904     
905     printf("msppedecrypt salt in: ");
906     for (i = 0; i < 2; i++)
907         printf("%02x ", salt[i]);
908     printf("\n");
909     
910     printf("msppedecrypt in: ");
911     for (i = 0; i < len; i++)
912         printf("%02x ", text[i]);
913     printf("\n");
914 #endif
915     
916     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
917         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
918         !EVP_DigestUpdate(&mdctx, auth, 16) ||
919         !EVP_DigestUpdate(&mdctx, salt, 2) ||
920         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
921         pthread_mutex_unlock(&lock);
922         return 0;
923     }
924
925 #if 0    
926     printf("msppedecrypt hash: ");
927     for (i = 0; i < 16; i++)
928         printf("%02x ", hash[i]);
929     printf("\n");
930 #endif
931     
932     for (i = 0; i < 16; i++)
933         plain[i] = text[i] ^ hash[i];
934     
935     for (offset = 16; offset < len; offset += 16) {
936 #if 0   
937         printf("text + offset - 16 c(%d): ", offset / 16);
938         for (i = 0; i < 16; i++)
939             printf("%02x ", (text + offset - 16)[i]);
940         printf("\n");
941 #endif
942         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
943             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
944             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
945             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
946             md_len != 16) {
947             pthread_mutex_unlock(&lock);
948             return 0;
949         }
950 #if 0   
951     printf("msppedecrypt hash: ");
952     for (i = 0; i < 16; i++)
953         printf("%02x ", hash[i]);
954     printf("\n");
955 #endif    
956
957     for (i = 0; i < 16; i++)
958         plain[offset + i] = text[offset + i] ^ hash[i];
959     }
960
961     memcpy(text, plain, len);
962 #if 0
963     printf("msppedecrypt out: ");
964     for (i = 0; i < len; i++)
965         printf("%02x ", text[i]);
966     printf("\n");
967 #endif
968
969     pthread_mutex_unlock(&lock);
970     return 1;
971 }
972
973 struct server *id2server(char *id, uint8_t len) {
974     int i;
975     char **realm, *idrealm;
976
977     idrealm = strchr(id, '@');
978     if (idrealm) {
979         idrealm++;
980         len -= idrealm - id;
981     } else {
982         idrealm = "-";
983         len = 1;
984     }
985     for (i = 0; i < server_count; i++) {
986         for (realm = servers[i].realms; *realm; realm++) {
987             if ((strlen(*realm) == 1 && **realm == '*') ||
988                 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
989                 debug(DBG_DBG, "found matching realm: %s, host %s", *realm, servers[i].peer.host);
990                 return servers + i;
991             }
992         }
993     }
994     return NULL;
995 }
996
997 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
998     int i;
999     
1000     pthread_mutex_lock(&to->newrq_mutex);
1001     for (i = 0; i < MAX_REQUESTS; i++)
1002         if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1003             break;
1004     pthread_mutex_unlock(&to->newrq_mutex);
1005     
1006     return i < MAX_REQUESTS;
1007 }
1008
1009 struct server *radsrv(struct request *rq, unsigned char *buf, struct client *from) {
1010     uint8_t code, id, *auth, *attr, attrvallen;
1011     uint8_t *usernameattr = NULL, *userpwdattr = NULL, *tunnelpwdattr = NULL, *messageauthattr = NULL;
1012     uint16_t len;
1013     int left;
1014     struct server *to;
1015     unsigned char newauth[16];
1016     char attrstring[256];
1017 #ifdef DEBUG
1018     int i;
1019 #endif    
1020     
1021     code = *(uint8_t *)buf;
1022     id = *(uint8_t *)(buf + 1);
1023     len = RADLEN(buf);
1024     auth = (uint8_t *)(buf + 4);
1025
1026     debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1027     
1028     if (code != RAD_Access_Request) {
1029         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, ignoring");
1030         return NULL;
1031     }
1032
1033     left = len - 20;
1034     attr = buf + 20;
1035     
1036     while (left > 1) {
1037         if (attr[RAD_Attr_Length] < 2) {
1038             debug(DBG_WARN, "radsrv: invalid attribute length, ignoring packet");
1039             return NULL;
1040         }
1041         left -= attr[RAD_Attr_Length];
1042         if (left < 0) {
1043             debug(DBG_WARN, "radsrv: attribute length exceeds packet length, ignoring packet");
1044             return NULL;
1045         }
1046         switch (attr[RAD_Attr_Type]) {
1047         case RAD_Attr_User_Name:
1048             usernameattr = attr;
1049             break;
1050         case RAD_Attr_User_Password:
1051             userpwdattr = attr;
1052             break;
1053         case RAD_Attr_Tunnel_Password:
1054             tunnelpwdattr = attr;
1055             break;
1056         case RAD_Attr_Message_Authenticator:
1057             messageauthattr = attr;
1058             break;
1059         }
1060         attr += attr[RAD_Attr_Length];
1061     }
1062     if (left)
1063         debug(DBG_WARN, "radsrv: malformed packet? remaining byte after last attribute");
1064
1065     if (!usernameattr) {
1066         debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1067         return NULL;
1068     }
1069         
1070     memcpy(attrstring, &usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1071     attrstring[usernameattr[RAD_Attr_Length] - 2] = '\0';
1072     debug(DBG_DBG, "Access Request with username: %s", attrstring);
1073     
1074     to = id2server((char *)&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1075     if (!to) {
1076         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1077         return NULL;
1078     }
1079
1080     if (rqinqueue(to, from, id)) {
1081         debug(DBG_INFO, "radsrv: ignoring request from host %s with id %d, already got one", from->peer.host, id);
1082         return NULL;
1083     }
1084     
1085     if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
1086                             !checkmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))) {
1087         debug(DBG_WARN, "radsrv: message authentication failed");
1088         return NULL;
1089     }
1090
1091     if (!RAND_bytes(newauth, 16)) {
1092         debug(DBG_WARN, "radsrv: failed to generate random auth");
1093         return NULL;
1094     }
1095
1096 #ifdef DEBUG    
1097     printauth("auth", auth);
1098     printauth("newauth", newauth);
1099 #endif
1100     
1101     if (userpwdattr) {
1102         debug(DBG_DBG, "radsrv: found userpwdattr of length %d", userpwdattr[RAD_Attr_Length]);
1103         attrvallen = userpwdattr[RAD_Attr_Length] - 2;
1104         if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1105             debug(DBG_WARN, "radsrv: invalid user password length");
1106             return NULL;
1107         }
1108         
1109         if (!pwddecrypt(&userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1110             debug(DBG_WARN, "radsrv: cannot decrypt password");
1111             return NULL;
1112         }
1113 #ifdef DEBUG
1114         printf("radsrv: password: ");
1115         for (i = 0; i < attrvallen; i++)
1116             printf("%02x ", userpwdattr[RAD_Attr_Value + i]);
1117         printf("\n");
1118 #endif  
1119         if (!pwdencrypt(&userpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1120             debug(DBG_WARN, "radsrv: cannot encrypt password");
1121             return NULL;
1122         }
1123     }
1124
1125     if (tunnelpwdattr) {
1126         debug(DBG_DBG, "radsrv: found tunnelpwdattr of length %d", tunnelpwdattr[RAD_Attr_Length]);
1127         attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
1128         if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1129             debug(DBG_WARN, "radsrv: invalid user password length");
1130             return NULL;
1131         }
1132         
1133         if (!pwddecrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1134             debug(DBG_WARN, "radsrv: cannot decrypt password");
1135             return NULL;
1136         }
1137 #ifdef DEBUG    
1138         printf("radsrv: password: ");
1139         for (i = 0; i < attrvallen; i++)
1140             printf("%02x ", tunnelpwdattr[RAD_Attr_Value + i]);
1141         printf("\n");
1142 #endif  
1143         if (!pwdencrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1144             debug(DBG_WARN, "radsrv: cannot encrypt password");
1145             return NULL;
1146         }
1147     }
1148
1149     rq->buf = buf;
1150     rq->from = from;
1151     rq->origid = id;
1152     rq->messageauthattrval = (messageauthattr ? &messageauthattr[RAD_Attr_Value] : NULL);
1153     memcpy(rq->origauth, auth, 16);
1154     memcpy(auth, newauth, 16);
1155 #ifdef DEBUG    
1156     printauth("rq->origauth", (unsigned char *)rq->origauth);
1157     printauth("auth", auth);
1158 #endif    
1159     return to;
1160 }
1161
1162 void *clientrd(void *arg) {
1163     struct server *server = (struct server *)arg;
1164     struct client *from;
1165     int i, left, subleft;
1166     unsigned char *buf, *messageauthattr, *subattr, *attr;
1167     struct sockaddr_storage fromsa;
1168     struct timeval lastconnecttry;
1169     char tmp[255];
1170     
1171     for (;;) {
1172     getnext:
1173         lastconnecttry = server->lastconnecttry;
1174         buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1175         if (!buf && server->peer.type == 'T') {
1176             tlsconnect(server, &lastconnecttry, "clientrd");
1177             continue;
1178         }
1179     
1180         server->connectionok = 1;
1181
1182         i = buf[1]; /* i is the id */
1183
1184         switch (*buf) {
1185         case RAD_Access_Accept:
1186             debug(DBG_DBG, "got Access Accept with id %d", i);
1187             break;
1188         case RAD_Access_Reject:
1189             debug(DBG_DBG, "got Access Reject with id %d", i);
1190             break;
1191         case RAD_Access_Challenge:
1192             debug(DBG_DBG, "got Access Challenge with id %d", i);
1193             break;
1194         default:
1195             debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1196             continue;
1197         }
1198         
1199         pthread_mutex_lock(&server->newrq_mutex);
1200         if (!server->requests[i].buf || !server->requests[i].tries) {
1201             pthread_mutex_unlock(&server->newrq_mutex);
1202             debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1203             continue;
1204         }
1205
1206         if (server->requests[i].received) {
1207             pthread_mutex_unlock(&server->newrq_mutex);
1208             debug(DBG_INFO, "clientrd: already received, ignoring");
1209             continue;
1210         }
1211         
1212         if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1213             pthread_mutex_unlock(&server->newrq_mutex);
1214             debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1215             continue;
1216         }
1217         
1218         from = server->requests[i].from;
1219
1220         /* messageauthattr present? */
1221         messageauthattr = NULL;
1222         left = RADLEN(buf) - 20;
1223         attr = buf + 20;
1224         while (left > 1) {
1225             left -= attr[RAD_Attr_Length];
1226             if (left < 0) {
1227                 debug(DBG_WARN, "clientrd: attribute length exceeds packet length, ignoring packet");
1228                 goto getnext;
1229             }
1230             if (attr[RAD_Attr_Type] == RAD_Attr_Message_Authenticator) {
1231                 if (attr[RAD_Attr_Length] != 18) {
1232                     debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1233                     goto getnext;
1234                 }
1235                 memcpy(tmp, buf + 4, 16);
1236                 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1237                 if (!checkmessageauth(buf, &attr[RAD_Attr_Value], server->peer.secret)) {
1238                     debug(DBG_WARN, "clientrd: message authentication failed");
1239                     goto getnext;
1240                 }
1241                 memcpy(buf + 4, tmp, 16);
1242                 debug(DBG_DBG, "clientrd: message auth ok");
1243                 messageauthattr = attr;
1244                 break;
1245             }
1246             attr += attr[RAD_Attr_Length];
1247         }
1248
1249         /* handle MS MPPE */
1250         left = RADLEN(buf) - 20;
1251         attr = buf + 20;
1252         while (left > 1) {
1253             left -= attr[RAD_Attr_Length];
1254             if (left < 0) {
1255                 debug(DBG_WARN, "clientrd: attribute length exceeds packet length, ignoring packet");
1256                 goto getnext;
1257             }
1258             if (attr[RAD_Attr_Type] == RAD_Attr_Vendor_Specific &&
1259                 ((uint16_t *)attr)[1] == 0 && ntohs(((uint16_t *)attr)[2]) == 311) { /* 311 == MS */
1260                 subleft = attr[RAD_Attr_Length] - 6;
1261                 subattr = attr + 6;
1262                 while (subleft > 1) {
1263                     subleft -= subattr[RAD_Attr_Length];
1264                     if (subleft < 0)
1265                         break;
1266                     if (subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Send_Key &&
1267                         subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Recv_Key)
1268                         continue;
1269                     debug(DBG_DBG, "clientrd: Got MS MPPE");
1270                     if (subattr[RAD_Attr_Length] < 20)
1271                         continue;
1272
1273                     if (!msmppdecrypt(subattr + 4, subattr[RAD_Attr_Length] - 4, (unsigned char *)server->peer.secret,
1274                                       strlen(server->peer.secret), server->requests[i].buf + 4, subattr + 2)) {
1275                         debug(DBG_WARN, "clientrd: failed to decrypt msppe key");
1276                         continue;
1277                     }
1278
1279                     if (!msmppencrypt(subattr + 4, subattr[RAD_Attr_Length] - 4, (unsigned char *)from->peer.secret,
1280                                       strlen(from->peer.secret), (unsigned char *)server->requests[i].origauth, subattr + 2)) {
1281                         debug(DBG_WARN, "clientrd: failed to encrypt msppe key");
1282                         continue;
1283                     }
1284                 }
1285                 if (subleft < 0) {
1286                     debug(DBG_WARN, "clientrd: bad vendor specific attr or subattr length, ignoring packet");
1287                     goto getnext;
1288                 }
1289             }
1290             attr += attr[RAD_Attr_Length];
1291         }
1292
1293         /* log DBG_INFO that received access accept/reject and username attr from original request */
1294         /* TODO STIG */
1295         /* once we set received = 1, requests[i] may be reused */
1296         buf[1] = (char)server->requests[i].origid;
1297         memcpy(buf + 4, server->requests[i].origauth, 16);
1298 #ifdef DEBUG    
1299         printauth("origauth/buf+4", buf + 4);
1300 #endif  
1301         if (messageauthattr) {
1302             if (!createmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))
1303                 continue;
1304             debug(DBG_DBG, "clientrd: computed messageauthattr");
1305         }
1306
1307         if (from->peer.type == 'U')
1308             fromsa = server->requests[i].fromsa;
1309         server->requests[i].received = 1;
1310         pthread_mutex_unlock(&server->newrq_mutex);
1311
1312         if (!radsign(buf, (unsigned char *)from->peer.secret)) {
1313             debug(DBG_WARN, "clientrd: failed to sign message");
1314             continue;
1315         }
1316 #ifdef DEBUG    
1317         printauth("signedorigauth/buf+4", buf + 4);
1318 #endif  
1319         debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1320         sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1321     }
1322 }
1323
1324 void *clientwr(void *arg) {
1325     struct server *server = (struct server *)arg;
1326     struct request *rq;
1327     pthread_t clientrdth;
1328     int i;
1329     uint8_t rnd;
1330     struct timeval now, lastsend;
1331     struct timespec timeout;
1332
1333     memset(&lastsend, 0, sizeof(struct timeval));
1334     memset(&timeout, 0, sizeof(struct timespec));
1335
1336     if (server->peer.type == 'U') {
1337         if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1338             debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1339     } else
1340         tlsconnect(server, NULL, "new client");
1341     
1342     if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1343         debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1344
1345     for (;;) {
1346         pthread_mutex_lock(&server->newrq_mutex);
1347         if (!server->newrq) {
1348             gettimeofday(&now, NULL);
1349             if (timeout.tv_sec) {
1350                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1351                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1352                 timeout.tv_sec = 0;
1353             } else if (options.statusserver) {
1354                 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD;
1355                 /* add random 0-7 seconds to timeout */
1356                 RAND_bytes(&rnd, 1);
1357                 timeout.tv_sec += rnd / 32;
1358                 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1359                 timeout.tv_sec = 0;
1360             } else {
1361                 debug(DBG_DBG, "clientwr: waiting for new request");
1362                 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1363             }
1364         }
1365         if (server->newrq) {
1366             debug(DBG_DBG, "clientwr: got new request");
1367             server->newrq = 0;
1368         } else
1369             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1370         pthread_mutex_unlock(&server->newrq_mutex);
1371
1372         for (i = 0; i < MAX_REQUESTS; i++) {
1373             pthread_mutex_lock(&server->newrq_mutex);
1374             while (!server->requests[i].buf && i < MAX_REQUESTS)
1375                 i++;
1376             if (i == MAX_REQUESTS) {
1377                 pthread_mutex_unlock(&server->newrq_mutex);
1378                 break;
1379             }
1380             rq = server->requests + i;
1381
1382             if (rq->received) {
1383                 debug(DBG_DBG, "clientwr: removing received packet from queue");
1384                 free(rq->buf);
1385                 /* setting this to NULL means that it can be reused */
1386                 rq->buf = NULL;
1387                 pthread_mutex_unlock(&server->newrq_mutex);
1388                 continue;
1389             }
1390             
1391             gettimeofday(&now, NULL);
1392             if (now.tv_sec <= rq->expiry.tv_sec) {
1393                 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1394                     timeout.tv_sec = rq->expiry.tv_sec;
1395                 pthread_mutex_unlock(&server->newrq_mutex);
1396                 continue;
1397             }
1398
1399             if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1400                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1401                 free(rq->buf);
1402                 /* setting this to NULL means that it can be reused */
1403                 rq->buf = NULL;
1404                 pthread_mutex_unlock(&server->newrq_mutex);
1405                 continue;
1406             }
1407             pthread_mutex_unlock(&server->newrq_mutex);
1408
1409             rq->expiry.tv_sec = now.tv_sec +
1410                 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1411             if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1412                 timeout.tv_sec = rq->expiry.tv_sec;
1413             rq->tries++;
1414             clientradput(server, server->requests[i].buf);
1415             gettimeofday(&lastsend, NULL);
1416             usleep(200000);
1417         }
1418         if (options.statusserver) {
1419             gettimeofday(&now, NULL);
1420             if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1421                 lastsend.tv_sec = now.tv_sec;
1422                 debug(DBG_DBG, "clientwr: should send status to %s here", server->peer.host);
1423             }
1424         }
1425     }
1426 }
1427
1428 void *udpserverwr(void *arg) {
1429     struct replyq *replyq = &udp_server_replyq;
1430     struct reply *reply = replyq->replies;
1431     
1432     pthread_mutex_lock(&replyq->count_mutex);
1433     for (;;) {
1434         while (!replyq->count) {
1435             debug(DBG_DBG, "udp server writer, waiting for signal");
1436             pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1437             debug(DBG_DBG, "udp server writer, got signal");
1438         }
1439         pthread_mutex_unlock(&replyq->count_mutex);
1440         
1441         if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1442                    (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1443             debug(DBG_WARN, "sendudp: send failed");
1444         free(reply->buf);
1445         
1446         pthread_mutex_lock(&replyq->count_mutex);
1447         replyq->count--;
1448         memmove(replyq->replies, replyq->replies + 1,
1449                 replyq->count * sizeof(struct reply));
1450     }
1451 }
1452
1453 void *udpserverrd(void *arg) {
1454     struct request rq;
1455     unsigned char *buf;
1456     struct server *to;
1457     struct client *fr;
1458     pthread_t udpserverwrth;
1459
1460     if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1461         debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1462
1463     debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1464           udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1465
1466     if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1467         debugx(1, DBG_ERR, "pthread_create failed");
1468     
1469     for (;;) {
1470         fr = NULL;
1471         memset(&rq, 0, sizeof(struct request));
1472         buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1473         to = radsrv(&rq, buf, fr);
1474         if (!to) {
1475             debug(DBG_INFO, "udpserverrd: ignoring request, no place to send it");
1476             continue;
1477         }
1478         sendrq(to, fr, &rq);
1479     }
1480 }
1481
1482 void *tlsserverwr(void *arg) {
1483     int cnt;
1484     unsigned long error;
1485     struct client *client = (struct client *)arg;
1486     struct replyq *replyq;
1487     
1488     debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1489     replyq = client->replyq;
1490     pthread_mutex_lock(&replyq->count_mutex);
1491     for (;;) {
1492         while (!replyq->count) {
1493             if (client->peer.ssl) {         
1494                 debug(DBG_DBG, "tls server writer, waiting for signal");
1495                 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1496                 debug(DBG_DBG, "tls server writer, got signal");
1497             }
1498             if (!client->peer.ssl) {
1499                 /* ssl might have changed while waiting */
1500                 pthread_mutex_unlock(&replyq->count_mutex);
1501                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1502                 pthread_exit(NULL);
1503             }
1504         }
1505         pthread_mutex_unlock(&replyq->count_mutex);
1506         cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1507         if (cnt > 0)
1508             debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1509                   cnt, RADLEN(replyq->replies->buf));
1510         else
1511             while ((error = ERR_get_error()))
1512                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1513         free(replyq->replies->buf);
1514
1515         pthread_mutex_lock(&replyq->count_mutex);
1516         replyq->count--;
1517         memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1518     }
1519 }
1520
1521 void *tlsserverrd(void *arg) {
1522     struct request rq;
1523     char unsigned *buf;
1524     unsigned long error;
1525     struct server *to;
1526     int s;
1527     struct client *client = (struct client *)arg;
1528     pthread_t tlsserverwrth;
1529     SSL *ssl;
1530     
1531     debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1532     ssl = client->peer.ssl;
1533
1534     if (SSL_accept(ssl) <= 0) {
1535         while ((error = ERR_get_error()))
1536             debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1537         debug(DBG_ERR, "SSL_accept failed");
1538         goto errexit;
1539     }
1540     if (tlsverifycert(&client->peer)) {
1541         if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1542             debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1543             goto errexit;
1544         }
1545         for (;;) {
1546             buf = radtlsget(client->peer.ssl);
1547             if (!buf)
1548                 break;
1549             debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1550             memset(&rq, 0, sizeof(struct request));
1551             to = radsrv(&rq, buf, client);
1552             if (!to) {
1553                 debug(DBG_INFO, "tlsserverrd: ignoring request, no place to send it");
1554                 continue;
1555             }
1556             sendrq(to, client, &rq);
1557         }
1558         debug(DBG_ERR, "tlsserverrd: connection lost");
1559         /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1560         client->peer.ssl = NULL;
1561         pthread_mutex_lock(&client->replyq->count_mutex);
1562         pthread_cond_signal(&client->replyq->count_cond);
1563         pthread_mutex_unlock(&client->replyq->count_mutex);
1564         debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1565         pthread_join(tlsserverwrth, NULL);
1566     }
1567     
1568  errexit:
1569     s = SSL_get_fd(ssl);
1570     SSL_free(ssl);
1571     shutdown(s, SHUT_RDWR);
1572     close(s);
1573     debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1574     client->peer.ssl = NULL;
1575     pthread_exit(NULL);
1576 }
1577
1578 int tlslistener() {
1579     pthread_t tlsserverth;
1580     int s, snew;
1581     struct sockaddr_storage from;
1582     size_t fromlen = sizeof(from);
1583     struct client *client;
1584
1585     if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1586         debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1587     
1588     listen(s, 0);
1589     debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1590           tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1591
1592     for (;;) {
1593         snew = accept(s, (struct sockaddr *)&from, &fromlen);
1594         if (snew < 0) {
1595             debug(DBG_WARN, "accept failed");
1596             continue;
1597         }
1598         debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1599
1600         client = find_client('T', (struct sockaddr *)&from, NULL);
1601         if (!client) {
1602             debug(DBG_WARN, "ignoring request, not a known TLS client");
1603             shutdown(snew, SHUT_RDWR);
1604             close(snew);
1605             continue;
1606         }
1607
1608         if (client->peer.ssl) {
1609             debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1610             shutdown(snew, SHUT_RDWR);
1611             close(snew);
1612             continue;
1613         }
1614         client->peer.ssl = SSL_new(ssl_ctx);
1615         SSL_set_fd(client->peer.ssl, snew);
1616         if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1617             debug(DBG_ERR, "tlslistener: pthread_create failed");
1618             SSL_free(client->peer.ssl);
1619             shutdown(snew, SHUT_RDWR);
1620             close(snew);
1621             client->peer.ssl = NULL;
1622             continue;
1623         }
1624         pthread_detach(tlsserverth);
1625     }
1626     return 0;
1627 }
1628
1629 char *parsehostport(char *s, struct peer *peer) {
1630     char *p, *field;
1631     int ipv6 = 0;
1632
1633     p = s;
1634     /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1635     if (*p == '[') {
1636         p++;
1637         field = p;
1638         for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1639         if (*p != ']')
1640             debugx(1, DBG_ERR, "no ] matching initial [");
1641         ipv6 = 1;
1642     } else {
1643         field = p;
1644         for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1645     }
1646     if (field == p)
1647         debugx(1, DBG_ERR, "missing host/address");
1648
1649     peer->host = stringcopy(field, p - field);
1650     if (ipv6) {
1651         p++;
1652         if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1653             debugx(1, DBG_ERR, "unexpected character after ]");
1654     }
1655     if (*p == ':') {
1656             /* port number or service name is specified */;
1657             field = ++p;
1658             for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1659             if (field == p)
1660                 debugx(1, DBG_ERR, "syntax error, : but no following port");
1661             peer->port = stringcopy(field, p - field);
1662     } else
1663         peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1664     return p;
1665 }
1666
1667 /* * is default, else longest match ... ";" used for separator */
1668 char *parserealmlist(char *s, struct server *server) {
1669     char *p;
1670     int i, n, l;
1671
1672     for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1673         if (*p == ';')
1674             n++;
1675     l = p - s;
1676     if (!l)
1677         debugx(1, DBG_ERR, "realm list must be specified");
1678
1679     server->realmdata = stringcopy(s, l);
1680     server->realms = malloc((1+n) * sizeof(char *));
1681     if (!server->realms)
1682         debugx(1, DBG_ERR, "malloc failed");
1683     server->realms[0] = server->realmdata;
1684     for (n = 1, i = 0; i < l; i++)
1685         if (server->realmdata[i] == ';') {
1686             server->realmdata[i] = '\0';
1687             server->realms[n++] = server->realmdata + i + 1;
1688         }       
1689     server->realms[n] = NULL;
1690     return p;
1691 }
1692
1693 FILE *openconfigfile(const char *filename) {
1694     FILE *f;
1695     char pathname[100], *base;
1696     
1697     f = fopen(filename, "r");
1698     if (f) {
1699         debug(DBG_DBG, "reading config file %s", filename);
1700         return f;
1701     }
1702
1703     if (strlen(filename) + 1 <= sizeof(pathname)) {
1704         /* basename() might modify the string */
1705         strcpy(pathname, filename);
1706         base = basename(pathname);
1707         f = fopen(base, "r");
1708     }
1709
1710     if (!f)
1711         debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1712     
1713     debug(DBG_DBG, "reading config file %s", base);
1714     return f;
1715 }
1716
1717 /* exactly one argument must be non-NULL */
1718 void getconfig(const char *serverfile, const char *clientfile) {
1719     FILE *f;
1720     char line[1024];
1721     char *p, *field, **r;
1722     struct client *client;
1723     struct server *server;
1724     struct peer *peer;
1725     int i, count, *ucount, *tcount;
1726  
1727     f = openconfigfile(serverfile ? serverfile : clientfile);
1728     if (serverfile) {
1729         ucount = &server_udp_count;
1730         tcount = &server_tls_count;
1731     } else {
1732         ucount = &client_udp_count;
1733         tcount = &client_tls_count;
1734     }
1735     while (fgets(line, 1024, f)) {
1736         for (p = line; *p == ' ' || *p == '\t'; p++);
1737         switch (*p) {
1738         case '#':
1739         case '\n':
1740             break;
1741         case 'T':
1742             (*tcount)++;
1743             break;
1744         case 'U':
1745             (*ucount)++;
1746             break;
1747         default:
1748             debugx(1, DBG_ERR, "type must be U or T, got %c", *p);
1749         }
1750     }
1751
1752     if (serverfile) {
1753         count = server_count = server_udp_count + server_tls_count;
1754         servers = calloc(count, sizeof(struct server));
1755         if (!servers)
1756             debugx(1, DBG_ERR, "malloc failed");
1757     } else {
1758         count = client_count = client_udp_count + client_tls_count;
1759         clients = calloc(count, sizeof(struct client));
1760         if (!clients)
1761             debugx(1, DBG_ERR, "malloc failed");
1762     }
1763     
1764     if (client_udp_count) {
1765         udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1766         if (!udp_server_replyq.replies)
1767             debugx(1, DBG_ERR, "malloc failed");
1768         udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1769         udp_server_replyq.count = 0;
1770         pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1771         pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1772     }    
1773     
1774     rewind(f);
1775     for (i = 0; i < count && fgets(line, 1024, f);) {
1776         if (serverfile) {
1777             server = &servers[i];
1778             peer = &server->peer;
1779         } else {
1780             client = &clients[i];
1781             peer = &client->peer;
1782         }
1783         for (p = line; *p == ' ' || *p == '\t'; p++);
1784         if (*p == '#' || *p == '\n')
1785             continue;
1786         peer->type = *p;        /* we already know it must be U or T */
1787         for (p++; *p == ' ' || *p == '\t'; p++);
1788         p = parsehostport(p, peer);
1789         for (; *p == ' ' || *p == '\t'; p++);
1790         if (serverfile) {
1791             p = parserealmlist(p, server);
1792             for (; *p == ' ' || *p == '\t'; p++);
1793         }
1794         field = p;
1795         for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1796         if (field == p) {
1797             /* no secret set and end of line, line is complete if TLS */
1798             if (peer->type == 'U')
1799                 debugx(1, DBG_ERR, "secret must be specified for UDP");
1800             peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1801         } else {
1802             peer->secret = stringcopy(field, p - field);
1803             /* check that rest of line only white space */
1804             for (; *p == ' ' || *p == '\t'; p++);
1805             if (*p && *p != '\n')
1806                 debugx(1, DBG_ERR, "max 4 fields per line, found a 5th");
1807         }
1808
1809         if ((serverfile && !resolvepeer(&server->peer, 0)) ||
1810             (clientfile && !resolvepeer(&client->peer, 0)))
1811             debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
1812
1813         if (serverfile) {
1814             pthread_mutex_init(&server->lock, NULL);
1815             server->sock = -1;
1816             server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1817             if (!server->requests)
1818                 debugx(1, DBG_ERR, "malloc failed");
1819             server->newrq = 0;
1820             pthread_mutex_init(&server->newrq_mutex, NULL);
1821             pthread_cond_init(&server->newrq_cond, NULL);
1822         } else {
1823             if (peer->type == 'U')
1824                 client->replyq = &udp_server_replyq;
1825             else {
1826                 client->replyq = malloc(sizeof(struct replyq));
1827                 if (!client->replyq)
1828                     debugx(1, DBG_ERR, "malloc failed");
1829                 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1830                 if (!client->replyq->replies)
1831                     debugx(1, DBG_ERR, "malloc failed");
1832                 client->replyq->size = MAX_REQUESTS;
1833                 client->replyq->count = 0;
1834                 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1835                 pthread_cond_init(&client->replyq->count_cond, NULL);
1836             }
1837         }
1838         debug(DBG_DBG, "got type %c, host %s, port %s, secret %s", peer->type, peer->host, peer->port, peer->secret);
1839         if (serverfile) {
1840             debug(DBG_DBG, "    with realms:");
1841             for (r = server->realms; *r; r++)
1842                 debug(DBG_DBG, "\t%s", *r);
1843         }
1844         i++;
1845     }
1846     fclose(f);
1847 }
1848
1849 struct peer *server_create(char type) {
1850     struct peer *server;
1851     char *conf;
1852
1853     server = malloc(sizeof(struct peer));
1854     if (!server)
1855         debugx(1, DBG_ERR, "malloc failed");
1856     memset(server, 0, sizeof(struct peer));
1857     server->type = type;
1858     conf = (type == 'T' ? options.listentcp : options.listenudp);
1859     if (conf) {
1860         parsehostport(conf, server);
1861         if (!strcmp(server->host, "*")) {
1862             free(server->host);
1863             server->host = NULL;
1864         }
1865     } else
1866         server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1867     if (!resolvepeer(server, AI_PASSIVE))
1868         debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1869     return server;
1870 }
1871                 
1872 void getmainconfig(const char *configfile) {
1873     FILE *f;
1874     char line[1024];
1875     char *p, *opt, *endopt, *val, *endval;
1876     
1877     f = openconfigfile(configfile);
1878     memset(&options, 0, sizeof(options));
1879
1880     while (fgets(line, 1024, f)) {
1881         for (p = line; *p == ' ' || *p == '\t'; p++);
1882         if (!*p || *p == '#' || *p == '\n')
1883             continue;
1884         opt = p++;
1885         for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1886         endopt = p - 1;
1887         for (; *p == ' ' || *p == '\t'; p++);
1888         if (!*p || *p == '\n') {
1889             endopt[1] = '\0';
1890             debugx(1, DBG_ERR, "error in %s, option %s has no value", configfile, opt);
1891         }
1892         val = p;
1893         for (; *p && *p != '\n'; p++)
1894             if (*p != ' ' && *p != '\t')
1895                 endval = p;
1896         endopt[1] = '\0';
1897         endval[1] = '\0';
1898         debug(DBG_DBG, "getmainconfig: %s = %s", opt, val);
1899         
1900         if (!strcasecmp(opt, "TLSCACertificateFile")) {
1901             options.tlscacertificatefile = stringcopy(val, 0);
1902             continue;
1903         }
1904         if (!strcasecmp(opt, "TLSCACertificatePath")) {
1905             options.tlscacertificatepath = stringcopy(val, 0);
1906             continue;
1907         }
1908         if (!strcasecmp(opt, "TLSCertificateFile")) {
1909             options.tlscertificatefile = stringcopy(val, 0);
1910             continue;
1911         }
1912         if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1913             options.tlscertificatekeyfile = stringcopy(val, 0);
1914             continue;
1915         }
1916         if (!strcasecmp(opt, "TLSCertificateKeyPassword")) {
1917             options.tlscertificatekeypassword = stringcopy(val, 0);
1918             continue;
1919         }
1920         if (!strcasecmp(opt, "ListenUDP")) {
1921             options.listenudp = stringcopy(val, 0);
1922             continue;
1923         }
1924         if (!strcasecmp(opt, "ListenTCP")) {
1925             options.listentcp = stringcopy(val, 0);
1926             continue;
1927         }
1928         if (!strcasecmp(opt, "StatusServer")) {
1929             if (!strcasecmp(val, "on"))
1930                 options.statusserver = 1;
1931             else if (strcasecmp(val, "off")) {
1932                 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be on or off", configfile, opt, val);
1933             }
1934             continue;
1935         }
1936         if (!strcasecmp(opt, "LogLevel")) {
1937             if (strlen(val) != 1 || *val < '1' || *val > '4')
1938                 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be 1, 2, 3 or 4", configfile, opt, val);
1939             options.loglevel = *val - '0';
1940             continue;
1941         }
1942         if (!strcasecmp(opt, "LogDestination")) {
1943             options.logdestination = stringcopy(val, 0);
1944             continue;
1945         }
1946         debugx(1, DBG_ERR, "error in %s, unknown option %s", configfile, opt);
1947     }
1948     fclose(f);
1949 }
1950
1951 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel) {
1952     int c;
1953
1954     while ((c = getopt(argc, argv, "d:f")) != -1) {
1955         switch (c) {
1956         case 'd':
1957             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
1958                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
1959             *loglevel = *optarg - '0';
1960             break;
1961         case 'f':
1962             *foreground = 1;
1963             break;
1964         default:
1965             goto usage;
1966         }
1967     }
1968     if (!(argc - optind))
1969         return;
1970
1971  usage:
1972     debug(DBG_ERR, "Usage:\n%s [ -f ] [ -d debuglevel ]", argv[0]);
1973     exit(1);
1974 }
1975
1976 int main(int argc, char **argv) {
1977     pthread_t udpserverth;
1978     int i;
1979     uint8_t foreground = 0, loglevel = 0;
1980     
1981     debug_init("radsecproxy");
1982     debug_set_level(DEBUG_LEVEL);
1983     getargs(argc, argv, &foreground, &loglevel);
1984     if (loglevel)
1985         debug_set_level(loglevel);
1986     getmainconfig(CONFIG_MAIN);
1987     if (loglevel)
1988         options.loglevel = loglevel;
1989     else if (options.loglevel)
1990         debug_set_level(options.loglevel);
1991     if (foreground)
1992         options.logdestination = NULL;
1993     else {
1994         if (!options.logdestination)
1995             options.logdestination = "x-syslog://";
1996         debug_set_destination(options.logdestination);
1997     }
1998     getconfig(CONFIG_SERVERS, NULL);
1999     getconfig(NULL, CONFIG_CLIENTS);
2000
2001     if (!foreground && (daemon(0, 0) < 0))
2002         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2003         
2004     if (client_udp_count) {
2005         udp_server_listen = server_create('U');
2006         if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2007             debugx(1, DBG_ERR, "pthread_create failed");
2008     }
2009     
2010     if (client_tls_count || server_tls_count)
2011         ssl_ctx = ssl_init();
2012     
2013     for (i = 0; i < server_count; i++)
2014         if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2015             debugx(1, DBG_ERR, "pthread_create failed");
2016
2017     if (client_tls_count) {
2018         tcp_server_listen = server_create('T');
2019         return tlslistener();
2020     }
2021     
2022     /* just hang around doing nothing, anything to do here? */
2023     for (;;)
2024         sleep(1000);
2025 }