* radsecproxy.c (createpidfile): Treat pid_t as long, avoiding compiler warnings...
[radsecproxy.git] / radsecproxy.c
1 /*
2  * Copyright (C) 2006-2009 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 /* Code contributions from:
10  *
11  * Arne Schwabe <schwabe at uni-paderborn.de>
12  * Maja Wolniewicz <mgw@umk.pl>
13  * Simon Leinen <simon.leinen@switch.ch>
14  * Stefan Winter <stefan.winter@restena.lu>
15  */
16
17 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
18  *              rd is responsible for init and launching wr
19  * For TLS there is a server instance that launches tlsserverrd for each TLS peer
20  *          each tlsserverrd launches tlsserverwr
21  * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
22  *          for init and launching rd
23  *
24  * serverrd will receive a request, processes it and puts it in the requestq of
25  *          the appropriate clientwr
26  * clientwr monitors its requestq and sends requests
27  * clientrd looks for responses, processes them and puts them in the replyq of
28  *          the peer the request came from
29  * serverwr monitors its reply and sends replies
30  *
31  * In addition to the main thread, we have:
32  * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
33  * If TLS peers are configured, there will initially be 2 * #peers TLS threads
34  * For each TLS peer connecting to us there will be 2 more TLS threads
35  *       This is only for connected peers
36  * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
37  *          1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38  */
39
40 /* Bugs:
41  * May segfault when dtls connections go down? More testing needed
42  * Remove expired stuff from clients request list?
43  * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
44  * Useful for TCP accounting? Now we require separate server config for alt port
45  */
46
47 #include <signal.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <netdb.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <limits.h>
54 #ifdef SYS_SOLARIS9
55 #include <fcntl.h>
56 #endif
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <ctype.h>
60 #include <sys/wait.h>
61 #include <arpa/inet.h>
62 #include <regex.h>
63 #include <libgen.h>
64 #include <pthread.h>
65 #include <errno.h>
66 #include <openssl/ssl.h>
67 #include <openssl/rand.h>
68 #include <openssl/err.h>
69 #include <openssl/md5.h>
70 #include "debug.h"
71 #include "list.h"
72 #include "hash.h"
73 #include "util.h"
74 #include "hostport.h"
75 #include "radsecproxy.h"
76 #include "udp.h"
77 #include "tcp.h"
78 #include "tls.h"
79 #include "dtls.h"
80
81 static struct options options;
82 static struct list *clconfs, *srvconfs;
83 static struct list *realms;
84 static struct hash *rewriteconfs;
85
86 static pthread_mutex_t *ssl_locks = NULL;
87 static long *ssl_lock_count;
88 extern int optind;
89 extern char *optarg;
90 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
91
92 /* minimum required declarations to avoid reordering code */
93 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
94 int dynamicconfig(struct server *server);
95 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
96 void freerealm(struct realm *realm);
97 void freeclsrvconf(struct clsrvconf *conf);
98 void freerq(struct request *rq);
99 void freerqoutdata(struct rqout *rqout);
100 void rmclientrq(struct request *rq, uint8_t id);
101
102 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
103
104 uint8_t protoname2int(const char *name) {
105     uint8_t i;
106
107     for (i = 0; i < RAD_PROTOCOUNT; i++)
108         if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
109             return i;
110     return 255;
111 }
112
113 /* callbacks for making OpenSSL thread safe */
114 unsigned long ssl_thread_id() {
115     return (unsigned long)pthread_self();
116 }
117
118 void ssl_locking_callback(int mode, int type, const char *file, int line) {
119     if (mode & CRYPTO_LOCK) {
120         pthread_mutex_lock(&ssl_locks[type]);
121         ssl_lock_count[type]++;
122     } else
123         pthread_mutex_unlock(&ssl_locks[type]);
124 }
125
126 /* returns 1 if the len first bits are equal, else 0 */
127 int prefixmatch(void *a1, void *a2, uint8_t len) {
128     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
129     uint8_t r, l = len / 8;
130     if (l && memcmp(a1, a2, l))
131         return 0;
132     r = len % 8;
133     if (!r)
134         return 1;
135     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
136 }
137
138 /* returns next config with matching address, or NULL */
139 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
140     struct list_node *entry;
141     struct clsrvconf *conf;
142
143     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
144         conf = (struct clsrvconf *)entry->data;
145         if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
146             if (cur)
147                 *cur = entry;
148             return conf;
149         }
150     }
151     return NULL;
152 }
153
154 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
155     return find_conf(type, addr, clconfs, cur, 0);
156 }
157
158 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
159     return find_conf(type, addr, srvconfs, cur, 1);
160 }
161
162 /* returns next config of given type, or NULL */
163 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
164     struct list_node *entry;
165     struct clsrvconf *conf;
166
167     for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
168         conf = (struct clsrvconf *)entry->data;
169         if (conf->type == type) {
170             if (cur)
171                 *cur = entry;
172             return conf;
173         }
174     }
175     return NULL;
176 }
177
178 struct gqueue *newqueue() {
179     struct gqueue *q;
180
181     q = malloc(sizeof(struct gqueue));
182     if (!q)
183         debugx(1, DBG_ERR, "malloc failed");
184     q->entries = list_create();
185     if (!q->entries)
186         debugx(1, DBG_ERR, "malloc failed");
187     pthread_mutex_init(&q->mutex, NULL);
188     pthread_cond_init(&q->cond, NULL);
189     return q;
190 }
191
192 void removequeue(struct gqueue *q) {
193     struct list_node *entry;
194
195     if (!q)
196         return;
197     pthread_mutex_lock(&q->mutex);
198     for (entry = list_first(q->entries); entry; entry = list_next(entry))
199         freerq((struct request *)entry);
200     list_destroy(q->entries);
201     pthread_cond_destroy(&q->cond);
202     pthread_mutex_unlock(&q->mutex);
203     pthread_mutex_destroy(&q->mutex);
204     free(q);
205 }
206
207 void freebios(struct gqueue *q) {
208     BIO *bio;
209
210     pthread_mutex_lock(&q->mutex);
211     while ((bio = (BIO *)list_shift(q->entries)))
212         BIO_free(bio);
213     pthread_mutex_unlock(&q->mutex);
214     removequeue(q);
215 }
216
217 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
218     struct client *new = malloc(sizeof(struct client));
219
220     if (!new) {
221         debug(DBG_ERR, "malloc failed");
222         return NULL;
223     }
224
225     if (lock)
226         pthread_mutex_lock(conf->lock);
227     if (!conf->clients) {
228         conf->clients = list_create();
229         if (!conf->clients) {
230             if (lock)
231                 pthread_mutex_unlock(conf->lock);
232             debug(DBG_ERR, "malloc failed");
233             return NULL;
234         }
235     }
236
237     memset(new, 0, sizeof(struct client));
238     new->conf = conf;
239     if (conf->pdef->addclient)
240         conf->pdef->addclient(new);
241     else
242         new->replyq = newqueue();
243     list_push(conf->clients, new);
244     if (lock)
245         pthread_mutex_unlock(conf->lock);
246     return new;
247 }
248
249 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
250     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
251
252     if (wantlock)
253         pthread_mutex_lock(&lock);
254     else
255         pthread_mutex_unlock(&lock);
256 }
257
258 void removeclientrqs(struct client *client) {
259     struct request *rq;
260     struct rqout *rqout;
261     int i;
262
263     removeclientrqs_sendrq_freeserver_lock(1);
264     for (i = 0; i < MAX_REQUESTS; i++) {
265         rq = client->rqs[i];
266         if (!rq)
267             continue;
268         if (rq->to) {
269             rqout = rq->to->requests + rq->newid;
270             pthread_mutex_lock(rqout->lock);
271             if (rqout->rq == rq) /* still pointing to our request */
272                 freerqoutdata(rqout);
273             pthread_mutex_unlock(rqout->lock);
274         }
275         freerq(rq);
276     }
277     removeclientrqs_sendrq_freeserver_lock(0);
278 }
279
280 void removelockedclient(struct client *client) {
281     struct clsrvconf *conf;
282
283     conf = client->conf;
284     if (conf->clients) {
285         removeclientrqs(client);
286         removequeue(client->replyq);
287         list_removedata(conf->clients, client);
288         free(client->addr);
289         free(client);
290     }
291 }
292
293 void removeclient(struct client *client) {
294     struct clsrvconf *conf;
295
296     if (!client)
297         return;
298
299     conf = client->conf;
300     pthread_mutex_lock(conf->lock);
301     removelockedclient(client);
302     pthread_mutex_unlock(conf->lock);
303 }
304
305 void freeserver(struct server *server, uint8_t destroymutex) {
306     struct rqout *rqout, *end;
307
308     if (!server)
309         return;
310
311     removeclientrqs_sendrq_freeserver_lock(1);
312     if (server->requests) {
313         rqout = server->requests;
314         for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
315             if (rqout->rq)
316                 rqout->rq->to = NULL;
317             freerqoutdata(rqout);
318             pthread_mutex_destroy(rqout->lock);
319             free(rqout->lock);
320         }
321         free(server->requests);
322     }
323     if (server->rbios)
324         freebios(server->rbios);
325     free(server->dynamiclookuparg);
326     if (server->ssl)
327         SSL_free(server->ssl);
328     if (destroymutex) {
329         pthread_mutex_destroy(&server->lock);
330         pthread_cond_destroy(&server->newrq_cond);
331         pthread_mutex_destroy(&server->newrq_mutex);
332     }
333     removeclientrqs_sendrq_freeserver_lock(0);
334     free(server);
335 }
336
337 int addserver(struct clsrvconf *conf) {
338     int i;
339
340     if (conf->servers) {
341         debug(DBG_ERR, "addserver: currently works with just one server per conf");
342         return 0;
343     }
344     conf->servers = malloc(sizeof(struct server));
345     if (!conf->servers) {
346         debug(DBG_ERR, "malloc failed");
347         return 0;
348     }
349     memset(conf->servers, 0, sizeof(struct server));
350     conf->servers->conf = conf;
351
352 #ifdef RADPROT_DTLS
353     if (conf->type == RAD_DTLS)
354         conf->servers->rbios = newqueue();
355 #endif
356     conf->pdef->setsrcres();
357
358     conf->servers->sock = -1;
359     if (conf->pdef->addserverextra)
360         conf->pdef->addserverextra(conf);
361
362     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
363     if (!conf->servers->requests) {
364         debug(DBG_ERR, "malloc failed");
365         goto errexit;
366     }
367     for (i = 0; i < MAX_REQUESTS; i++) {
368         conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
369         if (!conf->servers->requests[i].lock) {
370             debug(DBG_ERR, "malloc failed");
371             goto errexit;
372         }
373         if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
374             debugerrno(errno, DBG_ERR, "mutex init failed");
375             free(conf->servers->requests[i].lock);
376             conf->servers->requests[i].lock = NULL;
377             goto errexit;
378         }
379     }
380     if (pthread_mutex_init(&conf->servers->lock, NULL)) {
381         debugerrno(errno, DBG_ERR, "mutex init failed");
382         goto errexit;
383     }
384     conf->servers->newrq = 0;
385     if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
386         debugerrno(errno, DBG_ERR, "mutex init failed");
387         pthread_mutex_destroy(&conf->servers->lock);
388         goto errexit;
389     }
390     if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
391         debugerrno(errno, DBG_ERR, "mutex init failed");
392         pthread_mutex_destroy(&conf->servers->newrq_mutex);
393         pthread_mutex_destroy(&conf->servers->lock);
394         goto errexit;
395     }
396
397     return 1;
398
399 errexit:
400     freeserver(conf->servers, 0);
401     conf->servers = NULL;
402     return 0;
403 }
404
405 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
406     while (length > 1) {
407         if (ATTRTYPE(attrs) == type)
408             return attrs;
409         length -= ATTRLEN(attrs);
410         attrs += ATTRLEN(attrs);
411     }
412     return NULL;
413 }
414
415 struct request *newrqref(struct request *rq) {
416     if (rq)
417         rq->refcount++;
418     return rq;
419 }
420
421 void freerq(struct request *rq) {
422     if (!rq)
423         return;
424     debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
425     if (--rq->refcount)
426         return;
427     if (rq->origusername)
428         free(rq->origusername);
429     if (rq->buf)
430         free(rq->buf);
431     if (rq->replybuf)
432         free(rq->replybuf);
433     if (rq->msg)
434         radmsg_free(rq->msg);
435     free(rq);
436 }
437
438 void freerqoutdata(struct rqout *rqout) {
439     if (!rqout)
440         return;
441     if (rqout->rq) {
442         if (rqout->rq->buf) {
443             free(rqout->rq->buf);
444             rqout->rq->buf = NULL;
445         }
446         freerq(rqout->rq);
447         rqout->rq = NULL;
448     }
449     rqout->tries = 0;
450     memset(&rqout->expiry, 0, sizeof(struct timeval));
451 }
452
453 void sendrq(struct request *rq) {
454     int i, start;
455     struct server *to;
456
457     removeclientrqs_sendrq_freeserver_lock(1);
458     to = rq->to;
459     if (!to)
460         goto errexit;
461
462     start = to->conf->statusserver ? 1 : 0;
463     pthread_mutex_lock(&to->newrq_mutex);
464     if (start && rq->msg->code == RAD_Status_Server) {
465         pthread_mutex_lock(to->requests[0].lock);
466         if (to->requests[0].rq) {
467             pthread_mutex_unlock(to->requests[0].lock);
468             debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
469             goto errexit;
470         }
471         i = 0;
472     } else {
473         if (!to->nextid)
474             to->nextid = start;
475         /* might simplify if only try nextid, might be ok */
476         for (i = to->nextid; i < MAX_REQUESTS; i++) {
477             if (!to->requests[i].rq) {
478                 pthread_mutex_lock(to->requests[i].lock);
479                 if (!to->requests[i].rq)
480                     break;
481                 pthread_mutex_unlock(to->requests[i].lock);
482             }
483         }
484         if (i == MAX_REQUESTS) {
485             for (i = start; i < to->nextid; i++) {
486                 if (!to->requests[i].rq) {
487                     pthread_mutex_lock(to->requests[i].lock);
488                     if (!to->requests[i].rq)
489                         break;
490                     pthread_mutex_unlock(to->requests[i].lock);
491                 }
492             }
493             if (i == to->nextid) {
494                 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
495                 goto errexit;
496             }
497         }
498     }
499     rq->newid = (uint8_t)i;
500     rq->msg->id = (uint8_t)i;
501     rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
502     if (!rq->buf) {
503         pthread_mutex_unlock(to->requests[i].lock);
504         debug(DBG_ERR, "sendrq: radmsg2buf failed");
505         goto errexit;
506     }
507
508     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
509     to->requests[i].rq = rq;
510     pthread_mutex_unlock(to->requests[i].lock);
511     if (i >= start) /* i is not reserved for statusserver */
512         to->nextid = i + 1;
513
514     if (!to->newrq) {
515         to->newrq = 1;
516         debug(DBG_DBG, "sendrq: signalling client writer");
517         pthread_cond_signal(&to->newrq_cond);
518     }
519
520     pthread_mutex_unlock(&to->newrq_mutex);
521     removeclientrqs_sendrq_freeserver_lock(0);
522     return;
523
524 errexit:
525     if (rq->from)
526         rmclientrq(rq, rq->msg->id);
527     freerq(rq);
528     pthread_mutex_unlock(&to->newrq_mutex);
529     removeclientrqs_sendrq_freeserver_lock(0);
530 }
531
532 void sendreply(struct request *rq) {
533     uint8_t first;
534     struct client *to = rq->from;
535
536     if (!rq->replybuf)
537         rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
538     radmsg_free(rq->msg);
539     rq->msg = NULL;
540     if (!rq->replybuf) {
541         freerq(rq);
542         debug(DBG_ERR, "sendreply: radmsg2buf failed");
543         return;
544     }
545
546     pthread_mutex_lock(&to->replyq->mutex);
547     first = list_first(to->replyq->entries) == NULL;
548
549     if (!list_push(to->replyq->entries, rq)) {
550         pthread_mutex_unlock(&to->replyq->mutex);
551         freerq(rq);
552         debug(DBG_ERR, "sendreply: malloc failed");
553         return;
554     }
555
556     if (first) {
557         debug(DBG_DBG, "signalling server writer");
558         pthread_cond_signal(&to->replyq->cond);
559     }
560     pthread_mutex_unlock(&to->replyq->mutex);
561 }
562
563 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
564     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
565     static unsigned char first = 1;
566     static EVP_MD_CTX mdctx;
567     unsigned char hash[EVP_MAX_MD_SIZE], *input;
568     unsigned int md_len;
569     uint8_t i, offset = 0, out[128];
570
571     pthread_mutex_lock(&lock);
572     if (first) {
573         EVP_MD_CTX_init(&mdctx);
574         first = 0;
575     }
576
577     input = auth;
578     for (;;) {
579         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
580             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
581             !EVP_DigestUpdate(&mdctx, input, 16) ||
582             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
583             md_len != 16) {
584             pthread_mutex_unlock(&lock);
585             return 0;
586         }
587         for (i = 0; i < 16; i++)
588             out[offset + i] = hash[i] ^ in[offset + i];
589         if (encrypt_flag)
590             input = out + offset;
591         else
592             input = in + offset;
593         offset += 16;
594         if (offset == len)
595             break;
596     }
597     memcpy(in, out, len);
598     pthread_mutex_unlock(&lock);
599     return 1;
600 }
601
602 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
603     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
604     static unsigned char first = 1;
605     static EVP_MD_CTX mdctx;
606     unsigned char hash[EVP_MAX_MD_SIZE];
607     unsigned int md_len;
608     uint8_t i, offset;
609
610     pthread_mutex_lock(&lock);
611     if (first) {
612         EVP_MD_CTX_init(&mdctx);
613         first = 0;
614     }
615
616 #if 0
617     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
618     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
619     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
620 #endif
621
622     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
623         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
624         !EVP_DigestUpdate(&mdctx, auth, 16) ||
625         !EVP_DigestUpdate(&mdctx, salt, 2) ||
626         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
627         pthread_mutex_unlock(&lock);
628         return 0;
629     }
630
631 #if 0
632     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
633 #endif
634
635     for (i = 0; i < 16; i++)
636         text[i] ^= hash[i];
637
638     for (offset = 16; offset < len; offset += 16) {
639 #if 0
640         printf("text + offset - 16 c(%d): ", offset / 16);
641         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
642 #endif
643         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
644             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
645             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
646             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
647             md_len != 16) {
648             pthread_mutex_unlock(&lock);
649             return 0;
650         }
651 #if 0
652         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
653 #endif
654
655         for (i = 0; i < 16; i++)
656             text[offset + i] ^= hash[i];
657     }
658
659 #if 0
660     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
661 #endif
662
663     pthread_mutex_unlock(&lock);
664     return 1;
665 }
666
667 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
668     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
669     static unsigned char first = 1;
670     static EVP_MD_CTX mdctx;
671     unsigned char hash[EVP_MAX_MD_SIZE];
672     unsigned int md_len;
673     uint8_t i, offset;
674     char plain[255];
675
676     pthread_mutex_lock(&lock);
677     if (first) {
678         EVP_MD_CTX_init(&mdctx);
679         first = 0;
680     }
681
682 #if 0
683     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
684     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
685     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
686 #endif
687
688     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
689         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
690         !EVP_DigestUpdate(&mdctx, auth, 16) ||
691         !EVP_DigestUpdate(&mdctx, salt, 2) ||
692         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
693         pthread_mutex_unlock(&lock);
694         return 0;
695     }
696
697 #if 0
698     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
699 #endif
700
701     for (i = 0; i < 16; i++)
702         plain[i] = text[i] ^ hash[i];
703
704     for (offset = 16; offset < len; offset += 16) {
705 #if 0
706         printf("text + offset - 16 c(%d): ", offset / 16);
707         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
708 #endif
709         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
710             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
711             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
712             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
713             md_len != 16) {
714             pthread_mutex_unlock(&lock);
715             return 0;
716         }
717 #if 0
718         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
719 #endif
720
721         for (i = 0; i < 16; i++)
722             plain[offset + i] = text[offset + i] ^ hash[i];
723     }
724
725     memcpy(text, plain, len);
726 #if 0
727     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
728 #endif
729
730     pthread_mutex_unlock(&lock);
731     return 1;
732 }
733
734 struct realm *newrealmref(struct realm *r) {
735     if (r)
736         r->refcount++;
737     return r;
738 }
739
740 /* returns with lock on realm */
741 struct realm *id2realm(struct list *realmlist, char *id) {
742     struct list_node *entry;
743     struct realm *realm, *subrealm;
744
745     /* need to do locking for subrealms and check subrealm timers */
746     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
747         realm = (struct realm *)entry->data;
748         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
749             pthread_mutex_lock(&realm->mutex);
750             if (realm->subrealms) {
751                 subrealm = id2realm(realm->subrealms, id);
752                 if (subrealm) {
753                     pthread_mutex_unlock(&realm->mutex);
754                     return subrealm;
755                 }
756             }
757             return newrealmref(realm);
758         }
759     }
760     return NULL;
761 }
762
763 int hasdynamicserver(struct list *srvconfs) {
764     struct list_node *entry;
765
766     for (entry = list_first(srvconfs); entry; entry = list_next(entry))
767         if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
768             return 1;
769     return 0;
770 }
771
772 /* helper function, only used by removeserversubrealms() */
773 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
774     struct list_node *entry, *entry2;
775     struct realm *realm;
776
777     for (entry = list_first(realmlist); entry;) {
778         realm = newrealmref((struct realm *)entry->data);
779         pthread_mutex_lock(&realm->mutex);
780         entry = list_next(entry);
781
782         if (realm->srvconfs) {
783             for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
784                 if (entry2->data == srv)
785                     freerealm(realm);
786             list_removedata(realm->srvconfs, srv);
787         }
788         if (realm->accsrvconfs) {
789             for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
790                 if (entry2->data == srv)
791                     freerealm(realm);
792             list_removedata(realm->accsrvconfs, srv);
793         }
794
795         /* remove subrealm if no dynamic servers left */
796         if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
797             while (list_shift(realm->srvconfs))
798                 freerealm(realm);
799             list_destroy(realm->srvconfs);
800             realm->srvconfs = NULL;
801             while (list_shift(realm->accsrvconfs))
802                 freerealm(realm);
803             list_destroy(realm->accsrvconfs);
804             realm->accsrvconfs = NULL;
805             list_removedata(realmlist, realm);
806         }
807         pthread_mutex_unlock(&realm->mutex);
808         freerealm(realm);
809     }
810 }
811
812 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
813     struct list_node *entry;
814     struct realm *realm;
815
816     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
817         realm = (struct realm *)entry->data;
818         pthread_mutex_lock(&realm->mutex);
819         if (realm->subrealms) {
820             _internal_removeserversubrealms(realm->subrealms, srv);
821             if (!list_first(realm->subrealms)) {
822                 list_destroy(realm->subrealms);
823                 realm->subrealms = NULL;
824             }
825         }
826         pthread_mutex_unlock(&realm->mutex);
827     }
828 }
829
830 int attrvalidate(unsigned char *attrs, int length) {
831     while (length > 1) {
832         if (ATTRLEN(attrs) < 2) {
833             debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
834             return 0;
835         }
836         length -= ATTRLEN(attrs);
837         if (length < 0) {
838             debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
839             return 0;
840         }
841         attrs += ATTRLEN(attrs);
842     }
843     if (length)
844         debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
845     return 1;
846 }
847
848 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
849     if (len < 16 || len > 128 || len % 16) {
850         debug(DBG_WARN, "pwdrecrypt: invalid password length");
851         return 0;
852     }
853
854     if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
855         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
856         return 0;
857     }
858 #ifdef DEBUG
859     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
860 #endif
861     if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
862         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
863         return 0;
864     }
865     return 1;
866 }
867
868 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
869     if (len < 18)
870         return 0;
871     if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
872         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
873         return 0;
874     }
875     if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
876         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
877         return 0;
878     }
879     return 1;
880 }
881
882 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
883            char *oldsecret, char *newsecret) {
884     unsigned char *attr;
885
886     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
887         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
888         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
889             return 0;
890     }
891     return 1;
892 }
893
894 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
895     if (!attrs)
896         return 0;
897
898     for (; attrs[0]; attrs += 2)
899         if (attrs[0] == vendor && attrs[1] == subattr)
900             return 1;
901     return 0;
902 }
903
904 /* returns 1 if entire element is to be removed, else 0 */
905 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
906     uint8_t alen, sublen;
907     uint32_t vendor;
908     uint8_t *subattrs;
909
910     if (!removevendorattrs)
911         return 0;
912
913     memcpy(&vendor, attr->v, 4);
914     vendor = ntohl(vendor);
915     while (*removevendorattrs && *removevendorattrs != vendor)
916         removevendorattrs += 2;
917     if (!*removevendorattrs)
918         return 0;
919
920     if (findvendorsubattr(removevendorattrs, vendor, 256))
921         return 1; /* remove entire vendor attribute */
922
923     sublen = attr->l - 4;
924     subattrs = attr->v + 4;
925
926     if (!attrvalidate(subattrs, sublen)) {
927         debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
928         return 0;
929     }
930
931     while (sublen > 1) {
932         alen = ATTRLEN(subattrs);
933         sublen -= alen;
934         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
935             memmove(subattrs, subattrs + alen, sublen);
936             attr->l -= alen;
937         } else
938             subattrs += alen;
939     }
940     return 0;
941 }
942
943 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
944     struct list_node *n, *p;
945     struct tlv *attr;
946
947     p = NULL;
948     n = list_first(msg->attrs);
949     while (n) {
950         attr = (struct tlv *)n->data;
951         if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
952             (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
953             list_removedata(msg->attrs, attr);
954             freetlv(attr);
955             n = p ? list_next(p) : list_first(msg->attrs);
956         } else {
957             p = n;
958             n = list_next(n);
959         }
960     }
961 }
962
963 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
964     struct list_node *n;
965     struct tlv *a;
966
967     for (n = list_first(addattrs); n; n = list_next(n)) {
968         a = copytlv((struct tlv *)n->data);
969         if (!a)
970             return 0;
971         if (!radmsg_add(msg, a)) {
972             freetlv(a);
973             return 0;
974         }
975     }
976     return 1;
977 }
978
979 int resizeattr(struct tlv *attr, uint8_t newlen) {
980     uint8_t *newv;
981
982     if (newlen != attr->l) {
983         newv = realloc(attr->v, newlen);
984         if (!newv)
985             return 0;
986         attr->v = newv;
987         attr->l = newlen;
988     }
989     return 1;
990 }
991
992 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
993     size_t nmatch = 10, reslen = 0, start = 0;
994     regmatch_t pmatch[10], *pfield;
995     int i;
996     char *in, *out;
997
998     in = stringcopy((char *)attr->v, attr->l);
999     if (!in)
1000         return 0;
1001
1002     if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1003         free(in);
1004         return 1;
1005     }
1006
1007     out = modattr->replacement;
1008
1009     for (i = start; out[i]; i++) {
1010         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1011             pfield = &pmatch[out[i + 1] - '0'];
1012             if (pfield->rm_so >= 0) {
1013                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1014                 start = i + 2;
1015             }
1016             i++;
1017         }
1018     }
1019     reslen += i - start;
1020     if (reslen > 253) {
1021         debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1022         free(in);
1023         return 0;
1024     }
1025
1026     if (!resizeattr(attr, reslen)) {
1027         free(in);
1028         return 0;
1029     }
1030
1031     start = 0;
1032     reslen = 0;
1033     for (i = start; out[i]; i++) {
1034         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1035             pfield = &pmatch[out[i + 1] - '0'];
1036             if (pfield->rm_so >= 0) {
1037                 memcpy(attr->v + reslen, out + start, i - start);
1038                 reslen += i - start;
1039                 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1040                 reslen += pfield->rm_eo - pfield->rm_so;
1041                 start = i + 2;
1042             }
1043             i++;
1044         }
1045     }
1046
1047     memcpy(attr->v + reslen, out + start, i - start);
1048     return 1;
1049 }
1050
1051 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1052     struct list_node *n, *m;
1053
1054     for (n = list_first(msg->attrs); n; n = list_next(n))
1055         for (m = list_first(modattrs); m; m = list_next(m))
1056             if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1057                 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1058                 return 0;
1059     return 1;
1060 }
1061
1062 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1063     int rv = 1;                 /* Success.  */
1064
1065     if (rewrite) {
1066         if (rewrite->removeattrs || rewrite->removevendorattrs)
1067             dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1068         if (rewrite->modattrs)
1069             if (!dorewritemod(msg, rewrite->modattrs))
1070                 rv = 0;
1071         if (rewrite->addattrs)
1072             if (!dorewriteadd(msg, rewrite->addattrs))
1073                 rv = 0;
1074     }
1075     return rv;
1076 }
1077
1078 int rewriteusername(struct request *rq, struct tlv *attr) {
1079     char *orig = (char *)tlv2str(attr);
1080     if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1081         free(orig);
1082         return 0;
1083     }
1084     if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1085         rq->origusername = (char *)orig;
1086     else
1087         free(orig);
1088     return 1;
1089 }
1090
1091 /** Create vendor specific tlv with ATTR.  ATTR is consumed (freed) if
1092  * all is well with the new tlv, i.e. if the function returns
1093  * !NULL.  */
1094 static struct tlv *
1095 makevendortlv(uint32_t vendor, struct tlv *attr)
1096 {
1097     struct tlv *newtlv = NULL;
1098     uint8_t l, *v;
1099
1100     if (!attr)
1101         return NULL;
1102     l = attr->l + 6;
1103     v = malloc(l);
1104     if (v) {
1105         vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1106         memcpy(v, &vendor, 4);
1107         tlv2buf(v + 4, attr);
1108         v[5] += 2; /* Vendor length increased for type and length fields. */
1109         newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1110         if (newtlv == NULL)
1111             free(v);
1112         else
1113             freetlv(attr);
1114     }
1115     return newtlv;
1116 }
1117
1118 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG.  ATTR
1119  * is consumed.  */
1120 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1121     struct tlv *vattr;
1122
1123     vattr = makevendortlv(vendor, attr);
1124     if (!vattr) {
1125         freetlv(attr);
1126         return 0;
1127     }
1128     if (!radmsg_add(msg, vattr)) {
1129         freetlv(vattr);
1130         return 0;
1131     }
1132     return 1;
1133 }
1134
1135 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1136     uint8_t ttl[4];
1137     struct tlv *attr;
1138
1139     memset(ttl, 0, 4);
1140     ttl[3] = addttl;
1141
1142     if (attrtype[1] == 256) { /* not vendor */
1143         attr = maketlv(attrtype[0], 4, ttl);
1144         if (attr && !radmsg_add(msg, attr))
1145             freetlv(attr);
1146     } else {
1147         attr = maketlv(attrtype[1], 4, ttl);
1148         if (attr)
1149             addvendorattr(msg, attrtype[0], attr);
1150     }
1151 }
1152
1153 int decttl(uint8_t l, uint8_t *v) {
1154     int i;
1155
1156     i = l - 1;
1157     if (v[i]) {
1158         if (--v[i--])
1159             return 1;
1160         while (i >= 0 && !v[i])
1161             i--;
1162         return i >= 0;
1163     }
1164     for (i--; i >= 0 && !v[i]; i--);
1165     if (i < 0)
1166         return 0;
1167     v[i]--;
1168     while (++i < l)
1169         v[i] = 255;
1170     return 1;
1171 }
1172
1173 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1174 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1175     uint8_t alen, *subattrs;
1176     struct tlv *attr;
1177     struct list_node *node;
1178     uint32_t vendor;
1179     int sublen;
1180
1181     if (attrtype[1] == 256) { /* not vendor */
1182         attr = radmsg_gettype(msg, attrtype[0]);
1183         if (attr)
1184             return decttl(attr->l, attr->v);
1185     } else
1186         for (node = list_first(msg->attrs); node; node = list_next(node)) {
1187             attr = (struct tlv *)node->data;
1188             if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1189                 continue;
1190             memcpy(&vendor, attr->v, 4);
1191             if (ntohl(vendor) != attrtype[0])
1192                 continue;
1193             sublen = attr->l - 4;
1194             subattrs = attr->v + 4;
1195             if (!attrvalidate(subattrs, sublen))
1196                 continue;
1197             while (sublen > 1) {
1198                 if (ATTRTYPE(subattrs) == attrtype[1])
1199                     return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1200                 alen = ATTRLEN(subattrs);
1201                 sublen -= alen;
1202                 subattrs += alen;
1203             }
1204         }
1205     return -1;
1206 }
1207
1208 const char *radmsgtype2string(uint8_t code) {
1209     static const char *rad_msg_names[] = {
1210         "", "Access-Request", "Access-Accept", "Access-Reject",
1211         "Accounting-Request", "Accounting-Response", "", "",
1212         "", "", "", "Access-Challenge",
1213         "Status-Server", "Status-Client"
1214     };
1215     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1216 }
1217
1218 void char2hex(char *h, unsigned char c) {
1219     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1220                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1221     h[0] = hexdigits[c / 16];
1222     h[1] = hexdigits[c % 16];
1223     return;
1224 }
1225
1226 uint8_t *radattr2ascii(struct tlv *attr) {
1227     int i, l;
1228     uint8_t *a, *d;
1229
1230     if (!attr)
1231         return NULL;
1232
1233     l = attr->l;
1234     for (i = 0; i < attr->l; i++)
1235         if (attr->v[i] < 32 || attr->v[i] > 126)
1236             l += 2;
1237     if (l == attr->l)
1238         return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1239
1240     a = malloc(l + 1);
1241     if (!a)
1242         return NULL;
1243
1244     d = a;
1245     for (i = 0; i < attr->l; i++)
1246         if (attr->v[i] < 32 || attr->v[i] > 126) {
1247             *d++ = '%';
1248             char2hex((char *)d, attr->v[i]);
1249             d += 2;
1250         } else
1251             *d++ = attr->v[i];
1252     *d = '\0';
1253     return a;
1254 }
1255
1256 void acclog(struct radmsg *msg, struct client *from) {
1257     struct tlv *attr;
1258     uint8_t *username;
1259
1260     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1261     if (!attr) {
1262         debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1263         return;
1264     }
1265     username = radattr2ascii(attr);
1266     if (username) {
1267         debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1268
1269         free(username);
1270     }
1271 }
1272
1273 void respond(struct request *rq, uint8_t code, char *message) {
1274     struct radmsg *msg;
1275     struct tlv *attr;
1276
1277     msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1278     if (!msg) {
1279         debug(DBG_ERR, "respond: malloc failed");
1280         return;
1281     }
1282     if (message && *message) {
1283         attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1284         if (!attr || !radmsg_add(msg, attr)) {
1285             freetlv(attr);
1286             radmsg_free(msg);
1287             debug(DBG_ERR, "respond: malloc failed");
1288             return;
1289         }
1290     }
1291
1292     radmsg_free(rq->msg);
1293     rq->msg = msg;
1294     debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1295     sendreply(newrqref(rq));
1296 }
1297
1298 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1299     struct list_node *entry;
1300     struct clsrvconf *server, *best = NULL, *first = NULL;
1301
1302     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1303         server = (struct clsrvconf *)entry->data;
1304         if (!server->servers)
1305             return server;
1306         if (!first)
1307             first = server;
1308         if (!server->servers->connectionok && !server->servers->dynstartup)
1309             continue;
1310         if (!server->servers->lostrqs)
1311             return server;
1312         if (!best) {
1313             best = server;
1314             continue;
1315         }
1316         if (server->servers->lostrqs < best->servers->lostrqs)
1317             best = server;
1318     }
1319     return best ? best : first;
1320 }
1321
1322 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1323 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1324     struct clsrvconf *srvconf;
1325     struct realm *subrealm;
1326     struct server *server = NULL;
1327     char *id = (char *)tlv2str(username);
1328
1329     if (!id)
1330         return NULL;
1331     /* returns with lock on realm */
1332     *realm = id2realm(realms, id);
1333     if (!*realm)
1334         goto exit;
1335     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1336     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1337     if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1338         subrealm = adddynamicrealmserver(*realm, id);
1339         if (subrealm) {
1340             pthread_mutex_lock(&subrealm->mutex);
1341             pthread_mutex_unlock(&(*realm)->mutex);
1342             freerealm(*realm);
1343             *realm = subrealm;
1344             srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1345         }
1346     }
1347     if (srvconf)
1348         server = srvconf->servers;
1349
1350 exit:
1351     free(id);
1352     return server;
1353 }
1354
1355
1356 struct request *newrequest() {
1357     struct request *rq;
1358
1359     rq = malloc(sizeof(struct request));
1360     if (!rq) {
1361         debug(DBG_ERR, "newrequest: malloc failed");
1362         return NULL;
1363     }
1364     memset(rq, 0, sizeof(struct request));
1365     rq->refcount = 1;
1366     gettimeofday(&rq->created, NULL);
1367     return rq;
1368 }
1369
1370 int addclientrq(struct request *rq) {
1371     struct request *r;
1372     struct timeval now;
1373
1374     r = rq->from->rqs[rq->rqid];
1375     if (r) {
1376         if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1377             gettimeofday(&now, NULL);
1378             if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1379                 if (r->replybuf) {
1380                     debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1381                     sendreply(newrqref(r));
1382                 } else
1383                     debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1384                 return 0;
1385             }
1386         }
1387         freerq(r);
1388     }
1389     rq->from->rqs[rq->rqid] = newrqref(rq);
1390     return 1;
1391 }
1392
1393 void rmclientrq(struct request *rq, uint8_t id) {
1394     struct request *r;
1395
1396     r = rq->from->rqs[id];
1397     if (r) {
1398         freerq(r);
1399         rq->from->rqs[id] = NULL;
1400     }
1401 }
1402
1403 /* returns 0 if validation/authentication fails, else 1 */
1404 int radsrv(struct request *rq) {
1405     struct radmsg *msg = NULL;
1406     struct tlv *attr;
1407     uint8_t *userascii = NULL;
1408     struct realm *realm = NULL;
1409     struct server *to = NULL;
1410     struct client *from = rq->from;
1411     int ttlres;
1412
1413     msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1414     free(rq->buf);
1415     rq->buf = NULL;
1416
1417     if (!msg) {
1418         debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1419         freerq(rq);
1420         return 0;
1421     }
1422
1423     rq->msg = msg;
1424     rq->rqid = msg->id;
1425     memcpy(rq->rqauth, msg->auth, 16);
1426
1427     debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1428     if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1429         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1430         goto exit;
1431     }
1432
1433     if (!addclientrq(rq))
1434         goto exit;
1435
1436     if (msg->code == RAD_Status_Server) {
1437         respond(rq, RAD_Access_Accept, NULL);
1438         goto exit;
1439     }
1440
1441     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1442
1443     if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1444         goto rmclrqexit;
1445
1446     ttlres = checkttl(msg, options.ttlattrtype);
1447     if (!ttlres) {
1448         debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1449         goto exit;
1450     }
1451
1452     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1453     if (!attr) {
1454         if (msg->code == RAD_Accounting_Request) {
1455             acclog(msg, from);
1456             respond(rq, RAD_Accounting_Response, NULL);
1457         } else
1458             debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1459         goto exit;
1460     }
1461
1462     if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1463         debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1464         goto rmclrqexit;
1465     }
1466
1467     userascii = radattr2ascii(attr);
1468     if (!userascii)
1469         goto rmclrqexit;
1470     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1471
1472     /* will return with lock on the realm */
1473     to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1474     if (!realm) {
1475         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1476         goto exit;
1477     }
1478
1479     if (!to) {
1480         if (realm->message && msg->code == RAD_Access_Request) {
1481             debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1482             respond(rq, RAD_Access_Reject, realm->message);
1483         } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1484             acclog(msg, from);
1485             respond(rq, RAD_Accounting_Response, NULL);
1486         }
1487         goto exit;
1488     }
1489
1490     if ((to->conf->loopprevention == 1
1491          || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1492         && !strcmp(from->conf->name, to->conf->name)) {
1493         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1494               from->conf->name, addr2string(from->addr), to->conf->name);
1495         goto exit;
1496     }
1497
1498     if (msg->code == RAD_Accounting_Request)
1499         memset(msg->auth, 0, 16);
1500     else if (!RAND_bytes(msg->auth, 16)) {
1501         debug(DBG_WARN, "radsrv: failed to generate random auth");
1502         goto rmclrqexit;
1503     }
1504
1505 #ifdef DEBUG
1506     printfchars(NULL, "auth", "%02x ", auth, 16);
1507 #endif
1508
1509     attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1510     if (attr) {
1511         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1512         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1513             goto rmclrqexit;
1514     }
1515
1516     attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1517     if (attr) {
1518         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1519         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1520             goto rmclrqexit;
1521     }
1522
1523     if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1524         goto rmclrqexit;
1525
1526     if (ttlres == -1 && (options.addttl || to->conf->addttl))
1527         addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1528
1529     free(userascii);
1530     rq->to = to;
1531     sendrq(rq);
1532     pthread_mutex_unlock(&realm->mutex);
1533     freerealm(realm);
1534     return 1;
1535
1536 rmclrqexit:
1537     rmclientrq(rq, msg->id);
1538 exit:
1539     freerq(rq);
1540     free(userascii);
1541     if (realm) {
1542         pthread_mutex_unlock(&realm->mutex);
1543         freerealm(realm);
1544     }
1545     return 1;
1546 }
1547
1548 void replyh(struct server *server, unsigned char *buf) {
1549     struct client *from;
1550     struct rqout *rqout;
1551     int sublen, ttlres;
1552     unsigned char *subattrs;
1553     uint8_t *username, *stationid, *replymsg;
1554     struct radmsg *msg = NULL;
1555     struct tlv *attr;
1556     struct list_node *node;
1557
1558     server->connectionok = 1;
1559     server->lostrqs = 0;
1560
1561     rqout = server->requests + buf[1];
1562     pthread_mutex_lock(rqout->lock);
1563     if (!rqout->tries) {
1564         free(buf);
1565         buf = NULL;
1566         debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1567         goto errunlock;
1568     }
1569
1570     msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1571     free(buf);
1572     buf = NULL;
1573     if (!msg) {
1574         debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1575         goto errunlock;
1576     }
1577     if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1578         && msg->code != RAD_Accounting_Response) {
1579         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1580         goto errunlock;
1581     }
1582     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1583
1584     gettimeofday(&server->lastrcv, NULL);
1585
1586     if (rqout->rq->msg->code == RAD_Status_Server) {
1587         freerqoutdata(rqout);
1588         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1589         goto errunlock;
1590     }
1591
1592     gettimeofday(&server->lastreply, NULL);
1593     from = rqout->rq->from;
1594
1595     if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1596         debug(DBG_INFO, "replyh: rewritein failed");
1597         goto errunlock;
1598     }
1599
1600     ttlres = checkttl(msg, options.ttlattrtype);
1601     if (!ttlres) {
1602         debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1603         goto errunlock;
1604     }
1605
1606     /* MS MPPE */
1607     for (node = list_first(msg->attrs); node; node = list_next(node)) {
1608         attr = (struct tlv *)node->data;
1609         if (attr->t != RAD_Attr_Vendor_Specific)
1610             continue;
1611         if (attr->l <= 4)
1612             break;
1613         if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55)  /* 311 == MS */
1614             continue;
1615
1616         sublen = attr->l - 4;
1617         subattrs = attr->v + 4;
1618         if (!attrvalidate(subattrs, sublen) ||
1619             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1620                     rqout->rq, server->conf->secret, from->conf->secret) ||
1621             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1622                     rqout->rq, server->conf->secret, from->conf->secret))
1623             break;
1624     }
1625     if (node) {
1626         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1627         goto errunlock;
1628     }
1629
1630     if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1631         username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1632         if (username) {
1633             stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1634             replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1635             if (stationid) {
1636                 if (replymsg) {
1637                     debug(DBG_WARN, "%s for user %s stationid %s from %s (%s) to %s (%s)",
1638                           radmsgtype2string(msg->code), username, stationid, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1639                     free(replymsg);
1640                 } else
1641                     debug(DBG_WARN, "%s for user %s stationid %s from %s to %s (%s)",
1642                           radmsgtype2string(msg->code), username, stationid, server->conf->name, from->conf->name, addr2string(from->addr));
1643                 free(stationid);
1644             } else {
1645                 if (replymsg) {
1646                     debug(DBG_WARN, "%s for user %s from %s (%s) to %s (%s)",
1647                           radmsgtype2string(msg->code), username, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1648                     free(replymsg);
1649                 } else
1650                     debug(DBG_WARN, "%s for user %s from %s to %s (%s)",
1651                           radmsgtype2string(msg->code), username, server->conf->name, from->conf->name, addr2string(from->addr));
1652             }
1653             free(username);
1654         }
1655     }
1656
1657     msg->id = (char)rqout->rq->rqid;
1658     memcpy(msg->auth, rqout->rq->rqauth, 16);
1659
1660 #ifdef DEBUG
1661     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1662 #endif
1663
1664     if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1665         if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1666             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1667             goto errunlock;
1668         }
1669         memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1670     }
1671
1672     if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1673         debug(DBG_WARN, "replyh: rewriteout failed");
1674         goto errunlock;
1675     }
1676
1677     if (ttlres == -1 && (options.addttl || from->conf->addttl))
1678         addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1679
1680     debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1681           "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1682
1683     radmsg_free(rqout->rq->msg);
1684     rqout->rq->msg = msg;
1685     sendreply(newrqref(rqout->rq));
1686     freerqoutdata(rqout);
1687     pthread_mutex_unlock(rqout->lock);
1688     return;
1689
1690 errunlock:
1691     radmsg_free(msg);
1692     pthread_mutex_unlock(rqout->lock);
1693     return;
1694 }
1695
1696 struct request *createstatsrvrq() {
1697     struct request *rq;
1698     struct tlv *attr;
1699
1700     rq = newrequest();
1701     if (!rq)
1702         return NULL;
1703     rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1704     if (!rq->msg)
1705         goto exit;
1706     attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1707     if (!attr)
1708         goto exit;
1709     if (!radmsg_add(rq->msg, attr)) {
1710         freetlv(attr);
1711         goto exit;
1712     }
1713     return rq;
1714
1715 exit:
1716     freerq(rq);
1717     return NULL;
1718 }
1719
1720 /* code for removing state not finished */
1721 void *clientwr(void *arg) {
1722     struct server *server = (struct server *)arg;
1723     struct rqout *rqout = NULL;
1724     pthread_t clientrdth;
1725     int i, dynconffail = 0;
1726     time_t secs;
1727     uint8_t rnd;
1728     struct timeval now, laststatsrv;
1729     struct timespec timeout;
1730     struct request *statsrvrq;
1731     struct clsrvconf *conf;
1732
1733     conf = server->conf;
1734
1735     if (server->dynamiclookuparg && !dynamicconfig(server)) {
1736         dynconffail = 1;
1737         server->dynstartup = 0;
1738         sleep(900);
1739         goto errexit;
1740     }
1741
1742     if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1743         debug(DBG_WARN, "clientwr: resolve failed");
1744         server->dynstartup = 0;
1745         sleep(900);
1746         goto errexit;
1747     }
1748
1749     memset(&timeout, 0, sizeof(struct timespec));
1750
1751     if (conf->statusserver) {
1752         gettimeofday(&server->lastrcv, NULL);
1753         gettimeofday(&laststatsrv, NULL);
1754     }
1755
1756     if (conf->pdef->connecter) {
1757         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1758             if (server->dynamiclookuparg) {
1759                 server->dynstartup = 0;
1760                 sleep(900);
1761             }
1762             goto errexit;
1763         }
1764         server->connectionok = 1;
1765         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1766             debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1767             goto errexit;
1768         }
1769     } else
1770         server->connectionok = 1;
1771     server->dynstartup = 0;
1772
1773     for (;;) {
1774         pthread_mutex_lock(&server->newrq_mutex);
1775         if (!server->newrq) {
1776             gettimeofday(&now, NULL);
1777             /* random 0-7 seconds */
1778             RAND_bytes(&rnd, 1);
1779             rnd /= 32;
1780             if (conf->statusserver) {
1781                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1782                 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1783                     secs = now.tv_sec;
1784                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1785                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1786             } else {
1787                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1788                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1789             }
1790 #if 0
1791             if (timeout.tv_sec > now.tv_sec)
1792                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1793 #endif
1794             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1795             timeout.tv_sec = 0;
1796         }
1797         if (server->newrq) {
1798             debug(DBG_DBG, "clientwr: got new request");
1799             server->newrq = 0;
1800         }
1801 #if 0
1802         else
1803             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1804 #endif
1805         pthread_mutex_unlock(&server->newrq_mutex);
1806
1807         for (i = 0; i < MAX_REQUESTS; i++) {
1808             if (server->clientrdgone) {
1809                 pthread_join(clientrdth, NULL);
1810                 goto errexit;
1811             }
1812
1813             for (; i < MAX_REQUESTS; i++) {
1814                 rqout = server->requests + i;
1815                 if (rqout->rq) {
1816                     pthread_mutex_lock(rqout->lock);
1817                     if (rqout->rq)
1818                         break;
1819                     pthread_mutex_unlock(rqout->lock);
1820                 }
1821             }
1822
1823             if (i == MAX_REQUESTS)
1824                 break;
1825
1826             gettimeofday(&now, NULL);
1827             if (now.tv_sec < rqout->expiry.tv_sec) {
1828                 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1829                     timeout.tv_sec = rqout->expiry.tv_sec;
1830                 pthread_mutex_unlock(rqout->lock);
1831                 continue;
1832             }
1833
1834             if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1835                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1836                 if (conf->statusserver) {
1837                     if (*rqout->rq->buf == RAD_Status_Server) {
1838                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1839                         if (server->lostrqs < 255)
1840                             server->lostrqs++;
1841                     }
1842                 } else {
1843                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1844                     if (server->lostrqs < 255)
1845                         server->lostrqs++;
1846                 }
1847                 freerqoutdata(rqout);
1848                 pthread_mutex_unlock(rqout->lock);
1849                 continue;
1850             }
1851
1852             rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1853             if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1854                 timeout.tv_sec = rqout->expiry.tv_sec;
1855             rqout->tries++;
1856             conf->pdef->clientradput(server, rqout->rq->buf);
1857             pthread_mutex_unlock(rqout->lock);
1858         }
1859         if (conf->statusserver && server->connectionok) {
1860             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1861             gettimeofday(&now, NULL);
1862             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1863                 laststatsrv = now;
1864                 statsrvrq = createstatsrvrq();
1865                 if (statsrvrq) {
1866                     statsrvrq->to = server;
1867                     debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1868                     sendrq(statsrvrq);
1869                 }
1870             }
1871         }
1872     }
1873 errexit:
1874     conf->servers = NULL;
1875     if (server->dynamiclookuparg) {
1876         removeserversubrealms(realms, conf);
1877         if (dynconffail)
1878             free(conf);
1879         else
1880             freeclsrvconf(conf);
1881     }
1882     freeserver(server, 1);
1883     ERR_remove_state(0);
1884     return NULL;
1885 }
1886
1887 void createlistener(uint8_t type, char *arg) {
1888     pthread_t th;
1889     struct addrinfo *res;
1890     int s = -1, on = 1, *sp = NULL;
1891     struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1892
1893     if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1894         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1895
1896     for (res = hp->addrinfo; res; res = res->ai_next) {
1897         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1898         if (s < 0) {
1899             debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1900             continue;
1901         }
1902         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1903
1904         disable_DF_bit(s, res);
1905
1906 #ifdef IPV6_V6ONLY
1907         if (res->ai_family == AF_INET6)
1908             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1909 #endif
1910         if (bind(s, res->ai_addr, res->ai_addrlen)) {
1911             debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1912             close(s);
1913             s = -1;
1914             continue;
1915         }
1916
1917         sp = malloc(sizeof(int));
1918         if (!sp)
1919             debugx(1, DBG_ERR, "malloc failed");
1920         *sp = s;
1921         if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1922             debugerrnox(errno, DBG_ERR, "pthread_create failed");
1923         pthread_detach(th);
1924     }
1925     if (!sp)
1926         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1927
1928     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1929     freehostport(hp);
1930 }
1931
1932 void createlisteners(uint8_t type) {
1933     int i;
1934     char **args;
1935
1936     args = protodefs[type]->getlistenerargs();
1937     if (args)
1938         for (i = 0; args[i]; i++)
1939             createlistener(type, args[i]);
1940     else
1941         createlistener(type, NULL);
1942 }
1943
1944 void sslinit() {
1945     int i;
1946     time_t t;
1947     pid_t pid;
1948
1949     ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1950     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1951     for (i = 0; i < CRYPTO_num_locks(); i++) {
1952         ssl_lock_count[i] = 0;
1953         pthread_mutex_init(&ssl_locks[i], NULL);
1954     }
1955     CRYPTO_set_id_callback(ssl_thread_id);
1956     CRYPTO_set_locking_callback(ssl_locking_callback);
1957
1958     SSL_load_error_strings();
1959     SSL_library_init();
1960
1961     while (!RAND_status()) {
1962         t = time(NULL);
1963         pid = getpid();
1964         RAND_seed((unsigned char *)&t, sizeof(time_t));
1965         RAND_seed((unsigned char *)&pid, sizeof(pid));
1966     }
1967 }
1968
1969 struct list *addsrvconfs(char *value, char **names) {
1970     struct list *conflist;
1971     int n;
1972     struct list_node *entry;
1973     struct clsrvconf *conf = NULL;
1974
1975     if (!names || !*names)
1976         return NULL;
1977
1978     conflist = list_create();
1979     if (!conflist) {
1980         debug(DBG_ERR, "malloc failed");
1981         return NULL;
1982     }
1983
1984     for (n = 0; names[n]; n++) {
1985         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1986             conf = (struct clsrvconf *)entry->data;
1987             if (!strcasecmp(names[n], conf->name))
1988                 break;
1989         }
1990         if (!entry) {
1991             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
1992             list_destroy(conflist);
1993             return NULL;
1994         }
1995         if (!list_push(conflist, conf)) {
1996             debug(DBG_ERR, "malloc failed");
1997             list_destroy(conflist);
1998             return NULL;
1999         }
2000         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2001     }
2002     return conflist;
2003 }
2004
2005 void freerealm(struct realm *realm) {
2006     if (!realm)
2007         return;
2008     debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2009     if (--realm->refcount)
2010         return;
2011
2012     free(realm->name);
2013     free(realm->message);
2014     regfree(&realm->regex);
2015     pthread_mutex_destroy(&realm->mutex);
2016     /* if refcount == 0, all subrealms gone */
2017     list_destroy(realm->subrealms);
2018     /* if refcount == 0, all srvconfs gone */
2019     list_destroy(realm->srvconfs);
2020     /* if refcount == 0, all accsrvconfs gone */
2021     list_destroy(realm->accsrvconfs);
2022     freerealm(realm->parent);
2023     free(realm);
2024 }
2025
2026 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2027     int n;
2028     struct realm *realm;
2029     char *s, *regex = NULL;
2030
2031     if (*value == '/') {
2032         /* regexp, remove optional trailing / if present */
2033         if (value[strlen(value) - 1] == '/')
2034             value[strlen(value) - 1] = '\0';
2035     } else {
2036         /* not a regexp, let us make it one */
2037         if (*value == '*' && !value[1])
2038             regex = stringcopy(".*", 0);
2039         else {
2040             for (n = 0, s = value; *s;)
2041                 if (*s++ == '.')
2042                     n++;
2043             regex = malloc(strlen(value) + n + 3);
2044             if (regex) {
2045                 regex[0] = '@';
2046                 for (n = 1, s = value; *s; s++) {
2047                     if (*s == '.')
2048                         regex[n++] = '\\';
2049                     regex[n++] = *s;
2050                 }
2051                 regex[n++] = '$';
2052                 regex[n] = '\0';
2053             }
2054         }
2055         if (!regex) {
2056             debug(DBG_ERR, "malloc failed");
2057             realm = NULL;
2058             goto exit;
2059         }
2060         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2061     }
2062
2063     realm = malloc(sizeof(struct realm));
2064     if (!realm) {
2065         debug(DBG_ERR, "malloc failed");
2066         goto exit;
2067     }
2068     memset(realm, 0, sizeof(struct realm));
2069
2070     if (pthread_mutex_init(&realm->mutex, NULL)) {
2071         debugerrno(errno, DBG_ERR, "mutex init failed");
2072         free(realm);
2073         realm = NULL;
2074         goto exit;
2075     }
2076
2077     realm->name = stringcopy(value, 0);
2078     if (!realm->name) {
2079         debug(DBG_ERR, "malloc failed");
2080         goto errexit;
2081     }
2082     if (message && strlen(message) > 253) {
2083         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2084         goto errexit;
2085     }
2086     realm->message = message;
2087     realm->accresp = accresp;
2088
2089     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2090         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2091         goto errexit;
2092     }
2093
2094     if (servers && *servers) {
2095         realm->srvconfs = addsrvconfs(value, servers);
2096         if (!realm->srvconfs)
2097             goto errexit;
2098     }
2099
2100     if (accservers && *accservers) {
2101         realm->accsrvconfs = addsrvconfs(value, accservers);
2102         if (!realm->accsrvconfs)
2103             goto errexit;
2104     }
2105
2106     if (!list_push(realmlist, realm)) {
2107         debug(DBG_ERR, "malloc failed");
2108         pthread_mutex_destroy(&realm->mutex);
2109         goto errexit;
2110     }
2111
2112     debug(DBG_DBG, "addrealm: added realm %s", value);
2113     goto exit;
2114
2115 errexit:
2116     while (list_shift(realm->srvconfs));
2117     while (list_shift(realm->accsrvconfs));
2118     freerealm(realm);
2119     realm = NULL;
2120 exit:
2121     free(regex);
2122     if (servers) {
2123         if (realm)
2124             for (n = 0; servers[n]; n++)
2125                 newrealmref(realm);
2126         freegconfmstr(servers);
2127     }
2128     if (accservers) {
2129         if (realm)
2130             for (n = 0; accservers[n]; n++)
2131                 newrealmref(realm);
2132         freegconfmstr(accservers);
2133     }
2134     return newrealmref(realm);
2135 }
2136
2137 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2138     struct list_node *entry;
2139     struct clsrvconf *conf, *srvconf;
2140     struct list *subrealmservers = NULL;
2141     pthread_t clientth;
2142
2143     if (list_first(srvconfs)) {
2144         subrealmservers = list_create();
2145         if (!subrealmservers)
2146             return NULL;
2147     }
2148
2149     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2150         conf = (struct clsrvconf *)entry->data;
2151         if (!conf->servers && conf->dynamiclookupcommand) {
2152             srvconf = malloc(sizeof(struct clsrvconf));
2153             if (!srvconf) {
2154                 debug(DBG_ERR, "malloc failed");
2155                 continue;
2156             }
2157             *srvconf = *conf;
2158             if (addserver(srvconf)) {
2159                 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2160                 srvconf->servers->dynstartup = 1;
2161                 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2162                     debugerrno(errno, DBG_ERR, "pthread_create failed");
2163                     freeserver(srvconf->servers, 1);
2164                     srvconf->servers = NULL;
2165                 } else
2166                     pthread_detach(clientth);
2167             }
2168             conf = srvconf;
2169         }
2170         if (conf->servers) {
2171             if (list_push(subrealmservers, conf))
2172                 newrealmref(realm);
2173             else
2174                 debug(DBG_ERR, "malloc failed");
2175         }
2176     }
2177     return subrealmservers;
2178 }
2179
2180 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2181     struct realm *newrealm = NULL;
2182     char *realmname, *s;
2183
2184     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2185     realmname = strrchr(id, '@');
2186     if (!realmname)
2187         return NULL;
2188     realmname++;
2189     if (!*realmname)
2190         return NULL;
2191     for (s = realmname; *s; s++)
2192         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2193             return NULL;
2194
2195     if (!realm->subrealms)
2196         realm->subrealms = list_create();
2197     if (!realm->subrealms)
2198         return NULL;
2199
2200     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2201     if (!newrealm) {
2202         list_destroy(realm->subrealms);
2203         realm->subrealms = NULL;
2204         return NULL;
2205     }
2206
2207     newrealm->parent = newrealmref(realm);
2208     /* add server and accserver to newrealm */
2209     newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2210     newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2211     return newrealm;
2212 }
2213
2214 int dynamicconfig(struct server *server) {
2215     int ok, fd[2], status;
2216     pid_t pid;
2217     struct clsrvconf *conf = server->conf;
2218     struct gconffile *cf = NULL;
2219
2220     /* for now we only learn hostname/address */
2221     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2222
2223     if (pipe(fd) > 0) {
2224         debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2225         goto errexit;
2226     }
2227     pid = fork();
2228     if (pid < 0) {
2229         debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2230         close(fd[0]);
2231         close(fd[1]);
2232         goto errexit;
2233     } else if (pid == 0) {
2234         /* child */
2235         close(fd[0]);
2236         if (fd[1] != STDOUT_FILENO) {
2237             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2238                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2239             close(fd[1]);
2240         }
2241         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2242             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2243     }
2244
2245     close(fd[1]);
2246     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2247     ok = getgenericconfig(&cf, NULL,
2248                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2249                           NULL
2250         );
2251     freegconf(&cf);
2252
2253     if (waitpid(pid, &status, 0) < 0) {
2254         debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2255         goto errexit;
2256     }
2257
2258     if (status) {
2259         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2260         goto errexit;
2261     }
2262
2263     if (ok)
2264         return 1;
2265
2266 errexit:
2267     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2268     return 0;
2269 }
2270
2271 /* should accept both names and numeric values, only numeric right now */
2272 uint8_t attrname2val(char *attrname) {
2273     int val = 0;
2274
2275     val = atoi(attrname);
2276     return val > 0 && val < 256 ? val : 0;
2277 }
2278
2279 /* ATTRNAME is on the form vendor[:type].
2280    If only vendor is found, TYPE is set to 256 and 1 is returned.
2281    If type is >= 256, 1 is returned.
2282    Otherwise, 0 is returned.
2283 */
2284 /* should accept both names and numeric values, only numeric right now */
2285 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2286     char *s;
2287
2288     *vendor = atoi(attrname);
2289     s = strchr(attrname, ':');
2290     if (!s) {                   /* Only vendor was found.  */
2291         *type = 256;
2292         return 1;
2293     }
2294     *type = atoi(s + 1);
2295     return *type < 256;
2296 }
2297
2298 /** Extract attributes from string NAMEVAL, create a struct tlv and
2299  * return the tlv.  If VENDOR_FLAG, NAMEVAL is on the form
2300  * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>".  Return
2301  * NULL if fields are missing or if conversion fails.
2302  *
2303  * FIXME: Should accept both names and numeric values, only numeric
2304  * right now */
2305 struct tlv *extractattr(char *nameval, char vendor_flag) {
2306     int len, name = 0;
2307     int vendor = 0;         /* Vendor 0 is reserved, see RFC 1700.  */
2308     char *s, *s2;
2309     struct tlv *a;
2310
2311     s = strchr(nameval, ':');
2312     if (!s)
2313         return NULL;
2314     name = atoi(nameval);
2315
2316     if (vendor_flag) {
2317         s2 = strchr(s + 1, ':');
2318         if (!s2)
2319             return NULL;
2320         vendor = name;
2321         name = atoi(s + 1);
2322         s = s2;
2323     }
2324     len = strlen(s + 1);
2325     if (len > 253)
2326         return NULL;
2327
2328     if (name < 1 || name > 255)
2329         return NULL;
2330     a = malloc(sizeof(struct tlv));
2331     if (!a)
2332         return NULL;
2333
2334     a->v = (uint8_t *)stringcopy(s + 1, 0);
2335     if (!a->v) {
2336         free(a);
2337         return NULL;
2338     }
2339     a->t = name;
2340     a->l = len;
2341
2342     if (vendor_flag)
2343         a = makevendortlv(vendor, a);
2344
2345     return a;
2346 }
2347
2348 /* should accept both names and numeric values, only numeric right now */
2349 struct modattr *extractmodattr(char *nameval) {
2350     int name = 0;
2351     char *s, *t;
2352     struct modattr *m;
2353
2354     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2355         s = nameval + 11;
2356         name = 1;
2357     } else {
2358         s = strchr(nameval, ':');
2359         name = atoi(nameval);
2360         if (!s || name < 1 || name > 255 || s[1] != '/')
2361             return NULL;
2362         s += 2;
2363     }
2364     /* regexp, remove optional trailing / if present */
2365     if (s[strlen(s) - 1] == '/')
2366         s[strlen(s) - 1] = '\0';
2367
2368     t = strchr(s, '/');
2369     if (!t)
2370         return NULL;
2371     *t = '\0';
2372     t++;
2373
2374     m = malloc(sizeof(struct modattr));
2375     if (!m) {
2376         debug(DBG_ERR, "malloc failed");
2377         return NULL;
2378     }
2379     m->t = name;
2380
2381     m->replacement = stringcopy(t, 0);
2382     if (!m->replacement) {
2383         free(m);
2384         debug(DBG_ERR, "malloc failed");
2385         return NULL;
2386     }
2387
2388     m->regex = malloc(sizeof(regex_t));
2389     if (!m->regex) {
2390         free(m->replacement);
2391         free(m);
2392         debug(DBG_ERR, "malloc failed");
2393         return NULL;
2394     }
2395
2396     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2397         free(m->regex);
2398         free(m->replacement);
2399         free(m);
2400         debug(DBG_ERR, "failed to compile regular expression %s", s);
2401         return NULL;
2402     }
2403
2404     return m;
2405 }
2406
2407 struct rewrite *getrewrite(char *alt1, char *alt2) {
2408     struct rewrite *r;
2409
2410     if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
2411         return r;
2412     if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
2413         return r;
2414     return NULL;
2415 }
2416
2417 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2418 {
2419     struct rewrite *rewrite = NULL;
2420     int i, n;
2421     uint8_t *rma = NULL;
2422     uint32_t *p, *rmva = NULL;
2423     struct list *adda = NULL, *moda = NULL;
2424     struct tlv *a;
2425     struct modattr *m;
2426
2427     if (rmattrs) {
2428         for (n = 0; rmattrs[n]; n++);
2429         rma = calloc(n + 1, sizeof(uint8_t));
2430         if (!rma)
2431             debugx(1, DBG_ERR, "malloc failed");
2432
2433         for (i = 0; i < n; i++)
2434             if (!(rma[i] = attrname2val(rmattrs[i])))
2435                 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2436         freegconfmstr(rmattrs);
2437         rma[i] = 0;
2438     }
2439
2440     if (rmvattrs) {
2441         for (n = 0; rmvattrs[n]; n++);
2442         rmva = calloc(2 * n + 1, sizeof(uint32_t));
2443         if (!rmva)
2444             debugx(1, DBG_ERR, "malloc failed");
2445
2446         for (p = rmva, i = 0; i < n; i++, p += 2)
2447             if (!vattrname2val(rmvattrs[i], p, p + 1))
2448                 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2449         freegconfmstr(rmvattrs);
2450         *p = 0;
2451     }
2452
2453     if (addattrs) {
2454         adda = list_create();
2455         if (!adda)
2456             debugx(1, DBG_ERR, "malloc failed");
2457         for (i = 0; addattrs[i]; i++) {
2458             a = extractattr(addattrs[i], 0);
2459             if (!a)
2460                 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2461             if (!list_push(adda, a))
2462                 debugx(1, DBG_ERR, "malloc failed");
2463         }
2464         freegconfmstr(addattrs);
2465     }
2466
2467     if (addvattrs) {
2468         if (!adda)
2469             adda = list_create();
2470         if (!adda)
2471             debugx(1, DBG_ERR, "malloc failed");
2472         for (i = 0; addvattrs[i]; i++) {
2473             a = extractattr(addvattrs[i], 1);
2474             if (!a)
2475                 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2476             if (!list_push(adda, a))
2477                 debugx(1, DBG_ERR, "malloc failed");
2478         }
2479         freegconfmstr(addvattrs);
2480     }
2481
2482     if (modattrs) {
2483         moda = list_create();
2484         if (!moda)
2485             debugx(1, DBG_ERR, "malloc failed");
2486         for (i = 0; modattrs[i]; i++) {
2487             m = extractmodattr(modattrs[i]);
2488             if (!m)
2489                 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2490             if (!list_push(moda, m))
2491                 debugx(1, DBG_ERR, "malloc failed");
2492         }
2493         freegconfmstr(modattrs);
2494     }
2495
2496     if (rma || rmva || adda || moda) {
2497         rewrite = malloc(sizeof(struct rewrite));
2498         if (!rewrite)
2499             debugx(1, DBG_ERR, "malloc failed");
2500         rewrite->removeattrs = rma;
2501         rewrite->removevendorattrs = rmva;
2502         rewrite->addattrs = adda;
2503         rewrite->modattrs = moda;
2504     }
2505
2506     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2507         debugx(1, DBG_ERR, "malloc failed");
2508     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2509 }
2510
2511 int setttlattr(struct options *opts, char *defaultattr) {
2512     char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2513
2514     if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2515         (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2516         return 1;
2517     debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2518     return 0;
2519 }
2520
2521 void freeclsrvconf(struct clsrvconf *conf) {
2522     free(conf->name);
2523     if (conf->hostsrc)
2524         freegconfmstr(conf->hostsrc);
2525     free(conf->portsrc);
2526     free(conf->secret);
2527     free(conf->tls);
2528     free(conf->matchcertattr);
2529     if (conf->certcnregex)
2530         regfree(conf->certcnregex);
2531     if (conf->certuriregex)
2532         regfree(conf->certuriregex);
2533     free(conf->confrewritein);
2534     free(conf->confrewriteout);
2535     if (conf->rewriteusername) {
2536         if (conf->rewriteusername->regex)
2537             regfree(conf->rewriteusername->regex);
2538         free(conf->rewriteusername->replacement);
2539         free(conf->rewriteusername);
2540     }
2541     free(conf->dynamiclookupcommand);
2542     free(conf->rewritein);
2543     free(conf->rewriteout);
2544     if (conf->hostports)
2545         freehostports(conf->hostports);
2546     if (conf->lock) {
2547         pthread_mutex_destroy(conf->lock);
2548         free(conf->lock);
2549     }
2550     /* not touching ssl_ctx, clients and servers */
2551     free(conf);
2552 }
2553
2554 int mergeconfstring(char **dst, char **src) {
2555     char *t;
2556
2557     if (*src) {
2558         *dst = *src;
2559         *src = NULL;
2560         return 1;
2561     }
2562     if (*dst) {
2563         t = stringcopy(*dst, 0);
2564         if (!t) {
2565             debug(DBG_ERR, "malloc failed");
2566             return 0;
2567         }
2568         *dst = t;
2569     }
2570     return 1;
2571 }
2572
2573 char **mstringcopy(char **in) {
2574     char **out;
2575     int n;
2576
2577     if (!in)
2578         return NULL;
2579
2580     for (n = 0; in[n]; n++);
2581     out = malloc((n + 1) * sizeof(char *));
2582     if (!out)
2583         return NULL;
2584     for (n = 0; in[n]; n++) {
2585         out[n] = stringcopy(in[n], 0);
2586         if (!out[n]) {
2587             freegconfmstr(out);
2588             return NULL;
2589         }
2590     }
2591     out[n] = NULL;
2592     return out;
2593 }
2594
2595 int mergeconfmstring(char ***dst, char ***src) {
2596     char **t;
2597
2598     if (*src) {
2599         *dst = *src;
2600         *src = NULL;
2601         return 1;
2602     }
2603     if (*dst) {
2604         t = mstringcopy(*dst);
2605         if (!t) {
2606             debug(DBG_ERR, "malloc failed");
2607             return 0;
2608         }
2609         *dst = t;
2610     }
2611     return 1;
2612 }
2613
2614 /* assumes dst is a shallow copy */
2615 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2616     if (!mergeconfstring(&dst->name, &src->name) ||
2617         !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2618         !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2619         !mergeconfstring(&dst->secret, &src->secret) ||
2620         !mergeconfstring(&dst->tls, &src->tls) ||
2621         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2622         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2623         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2624         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2625         return 0;
2626     if (src->pdef)
2627         dst->pdef = src->pdef;
2628     dst->statusserver = src->statusserver;
2629     dst->certnamecheck = src->certnamecheck;
2630     if (src->retryinterval != 255)
2631         dst->retryinterval = src->retryinterval;
2632     if (src->retrycount != 255)
2633         dst->retrycount = src->retrycount;
2634     return 1;
2635 }
2636
2637 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2638     struct clsrvconf *conf;
2639     char *conftype = NULL, *rewriteinalias = NULL;
2640     long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2641
2642     debug(DBG_DBG, "confclient_cb called for %s", block);
2643
2644     conf = malloc(sizeof(struct clsrvconf));
2645     if (!conf)
2646         debugx(1, DBG_ERR, "malloc failed");
2647     memset(conf, 0, sizeof(struct clsrvconf));
2648     conf->certnamecheck = 1;
2649
2650     if (!getgenericconfig(cf, block,
2651                           "type", CONF_STR, &conftype,
2652                           "host", CONF_MSTR, &conf->hostsrc,
2653                           "secret", CONF_STR, &conf->secret,
2654 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2655                           "tls", CONF_STR, &conf->tls,
2656                           "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2657                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2658 #endif
2659                           "DuplicateInterval", CONF_LINT, &dupinterval,
2660                           "addTTL", CONF_LINT, &addttl,
2661                           "rewrite", CONF_STR, &rewriteinalias,
2662                           "rewriteIn", CONF_STR, &conf->confrewritein,
2663                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2664                           "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2665                           NULL
2666             ))
2667         debugx(1, DBG_ERR, "configuration error");
2668
2669     conf->name = stringcopy(val, 0);
2670     if (conf->name && !conf->hostsrc) {
2671         conf->hostsrc = malloc(2 * sizeof(char *));
2672         if (conf->hostsrc) {
2673             conf->hostsrc[0] = stringcopy(val, 0);
2674             conf->hostsrc[1] = NULL;
2675         }
2676     }
2677     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2678         debugx(1, DBG_ERR, "malloc failed");
2679
2680     if (!conftype)
2681         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2682     conf->type = protoname2int(conftype);
2683     if (conf->type == 255)
2684         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2685     free(conftype);
2686     conf->pdef = protodefs[conf->type];
2687
2688 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2689     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2690         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2691         if (!conf->tlsconf)
2692             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2693         if (conf->matchcertattr && !addmatchcertattr(conf))
2694             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2695     }
2696 #endif
2697
2698     if (dupinterval != LONG_MIN) {
2699         if (dupinterval < 0 || dupinterval > 255)
2700             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2701         conf->dupinterval = (uint8_t)dupinterval;
2702     } else
2703         conf->dupinterval = conf->pdef->duplicateintervaldefault;
2704
2705     if (addttl != LONG_MIN) {
2706         if (addttl < 1 || addttl > 255)
2707             debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2708         conf->addttl = (uint8_t)addttl;
2709     }
2710
2711     if (!conf->confrewritein)
2712         conf->confrewritein = rewriteinalias;
2713     else
2714         free(rewriteinalias);
2715     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2716     if (conf->confrewriteout)
2717         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2718
2719     if (conf->confrewriteusername) {
2720         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2721         if (!conf->rewriteusername)
2722             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2723     }
2724
2725     if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2726         !resolvehostports(conf->hostports, conf->pdef->socktype))
2727         debugx(1, DBG_ERR, "resolve failed, exiting");
2728
2729     if (!conf->secret) {
2730         if (!conf->pdef->secretdefault)
2731             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2732         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2733         if (!conf->secret)
2734             debugx(1, DBG_ERR, "malloc failed");
2735     }
2736
2737     conf->lock = malloc(sizeof(pthread_mutex_t));
2738     if (!conf->lock)
2739         debugx(1, DBG_ERR, "malloc failed");
2740
2741     pthread_mutex_init(conf->lock, NULL);
2742     if (!list_push(clconfs, conf))
2743         debugx(1, DBG_ERR, "malloc failed");
2744     return 1;
2745 }
2746
2747 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2748 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2749     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2750         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2751         if (!conf->tlsconf) {
2752             debug(DBG_ERR, "error in block %s, no tls context defined", block);
2753             return 0;
2754         }
2755         if (conf->matchcertattr && !addmatchcertattr(conf)) {
2756             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2757             return 0;
2758         }
2759     }
2760 #endif
2761
2762     if (!conf->portsrc) {
2763         conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2764         if (!conf->portsrc) {
2765             debug(DBG_ERR, "malloc failed");
2766             return 0;
2767         }
2768     }
2769
2770     if (conf->retryinterval == 255)
2771         conf->retryinterval = conf->pdef->retryintervaldefault;
2772     if (conf->retrycount == 255)
2773         conf->retrycount = conf->pdef->retrycountdefault;
2774
2775     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2776     if (conf->confrewriteout)
2777         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2778
2779     if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2780         debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2781         return 0;
2782     }
2783
2784     if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2785         debug(DBG_ERR, "resolve failed, exiting");
2786         return 0;
2787     }
2788     return 1;
2789 }
2790
2791 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2792     struct clsrvconf *conf, *resconf;
2793     char *conftype = NULL, *rewriteinalias = NULL;
2794     long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2795
2796     debug(DBG_DBG, "confserver_cb called for %s", block);
2797
2798     conf = malloc(sizeof(struct clsrvconf));
2799     if (!conf) {
2800         debug(DBG_ERR, "malloc failed");
2801         return 0;
2802     }
2803     memset(conf, 0, sizeof(struct clsrvconf));
2804     conf->loopprevention = UCHAR_MAX; /* Uninitialized.  */
2805     resconf = (struct clsrvconf *)arg;
2806     if (resconf) {
2807         conf->statusserver = resconf->statusserver;
2808         conf->certnamecheck = resconf->certnamecheck;
2809     } else
2810         conf->certnamecheck = 1;
2811
2812     if (!getgenericconfig(cf, block,
2813                           "type", CONF_STR, &conftype,
2814                           "host", CONF_MSTR, &conf->hostsrc,
2815                           "port", CONF_STR, &conf->portsrc,
2816                           "secret", CONF_STR, &conf->secret,
2817 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2818                           "tls", CONF_STR, &conf->tls,
2819                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2820                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2821 #endif
2822                           "addTTL", CONF_LINT, &addttl,
2823                           "rewrite", CONF_STR, &rewriteinalias,
2824                           "rewriteIn", CONF_STR, &conf->confrewritein,
2825                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2826                           "StatusServer", CONF_BLN, &conf->statusserver,
2827                           "RetryInterval", CONF_LINT, &retryinterval,
2828                           "RetryCount", CONF_LINT, &retrycount,
2829                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2830                           "LoopPrevention", CONF_BLN, &conf->loopprevention,
2831                           NULL
2832             )) {
2833         debug(DBG_ERR, "configuration error");
2834         goto errexit;
2835     }
2836
2837     conf->name = stringcopy(val, 0);
2838     if (conf->name && !conf->hostsrc) {
2839         conf->hostsrc = malloc(2 * sizeof(char *));
2840         if (conf->hostsrc) {
2841             conf->hostsrc[0] = stringcopy(val, 0);
2842             conf->hostsrc[1] = NULL;
2843         }
2844     }
2845     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2846         debug(DBG_ERR, "malloc failed");
2847         goto errexit;
2848     }
2849
2850     if (!conftype) {
2851         debug(DBG_ERR, "error in block %s, option type missing", block);
2852         goto errexit;
2853     }
2854     conf->type = protoname2int(conftype);
2855     if (conf->type == 255) {
2856         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2857         goto errexit;
2858     }
2859     free(conftype);
2860     conftype = NULL;
2861
2862     conf->pdef = protodefs[conf->type];
2863
2864     if (!conf->confrewritein)
2865         conf->confrewritein = rewriteinalias;
2866     else
2867         free(rewriteinalias);
2868     rewriteinalias = NULL;
2869
2870     if (retryinterval != LONG_MIN) {
2871         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2872             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2873             goto errexit;
2874         }
2875         conf->retryinterval = (uint8_t)retryinterval;
2876     } else
2877         conf->retryinterval = 255;
2878
2879     if (retrycount != LONG_MIN) {
2880         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2881             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2882             goto errexit;
2883         }
2884         conf->retrycount = (uint8_t)retrycount;
2885     } else
2886         conf->retrycount = 255;
2887
2888     if (addttl != LONG_MIN) {
2889         if (addttl < 1 || addttl > 255) {
2890             debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2891             goto errexit;
2892         }
2893         conf->addttl = (uint8_t)addttl;
2894     }
2895
2896     if (resconf) {
2897         if (!mergesrvconf(resconf, conf))
2898             goto errexit;
2899         free(conf);
2900         conf = resconf;
2901         if (conf->dynamiclookupcommand) {
2902             free(conf->dynamiclookupcommand);
2903             conf->dynamiclookupcommand = NULL;
2904         }
2905     }
2906
2907     if (resconf || !conf->dynamiclookupcommand) {
2908         if (!compileserverconfig(conf, block))
2909             goto errexit;
2910     }
2911
2912     if (!conf->secret) {
2913         if (!conf->pdef->secretdefault) {
2914             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2915             return 0;
2916         }
2917         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2918         if (!conf->secret) {
2919             debug(DBG_ERR, "malloc failed");
2920             return 0;
2921         }
2922     }
2923
2924     if (resconf)
2925         return 1;
2926
2927     if (!list_push(srvconfs, conf)) {
2928         debug(DBG_ERR, "malloc failed");
2929         goto errexit;
2930     }
2931     return 1;
2932
2933 errexit:
2934     free(conftype);
2935     free(rewriteinalias);
2936     freeclsrvconf(conf);
2937     return 0;
2938 }
2939
2940 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2941     char **servers = NULL, **accservers = NULL, *msg = NULL;
2942     uint8_t accresp = 0;
2943
2944     debug(DBG_DBG, "confrealm_cb called for %s", block);
2945
2946     if (!getgenericconfig(cf, block,
2947                           "server", CONF_MSTR, &servers,
2948                           "accountingServer", CONF_MSTR, &accservers,
2949                           "ReplyMessage", CONF_STR, &msg,
2950                           "AccountingResponse", CONF_BLN, &accresp,
2951                           NULL
2952             ))
2953         debugx(1, DBG_ERR, "configuration error");
2954
2955     addrealm(realms, val, servers, accservers, msg, accresp);
2956     return 1;
2957 }
2958
2959 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2960     char **rmattrs = NULL, **rmvattrs = NULL;
2961     char **addattrs = NULL, **addvattrs = NULL;
2962     char **modattrs = NULL;
2963
2964     debug(DBG_DBG, "confrewrite_cb called for %s", block);
2965
2966     if (!getgenericconfig(cf, block,
2967                           "removeAttribute", CONF_MSTR, &rmattrs,
2968                           "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2969                           "addAttribute", CONF_MSTR, &addattrs,
2970                           "addVendorAttribute", CONF_MSTR, &addvattrs,
2971                           "modifyAttribute", CONF_MSTR, &modattrs,
2972                           NULL
2973             ))
2974         debugx(1, DBG_ERR, "configuration error");
2975     addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2976     return 1;
2977 }
2978
2979 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2980     struct commonprotoopts *protoopts;
2981
2982     protoopts = malloc(sizeof(struct commonprotoopts));
2983     if (!protoopts)
2984         return 0;
2985     memset(protoopts, 0, sizeof(struct commonprotoopts));
2986     protoopts->listenargs = listenargs;
2987     protoopts->sourcearg = sourcearg;
2988     protodefs[type]->setprotoopts(protoopts);
2989     return 1;
2990 }
2991
2992 void getmainconfig(const char *configfile) {
2993     long int addttl = LONG_MIN, loglevel = LONG_MIN;
2994     struct gconffile *cfs;
2995     char **listenargs[RAD_PROTOCOUNT];
2996     char *sourcearg[RAD_PROTOCOUNT];
2997     int i;
2998
2999     cfs = openconfigfile(configfile);
3000     memset(&options, 0, sizeof(options));
3001     memset(&listenargs, 0, sizeof(listenargs));
3002     memset(&sourcearg, 0, sizeof(sourcearg));
3003
3004     clconfs = list_create();
3005     if (!clconfs)
3006         debugx(1, DBG_ERR, "malloc failed");
3007
3008     srvconfs = list_create();
3009     if (!srvconfs)
3010         debugx(1, DBG_ERR, "malloc failed");
3011
3012     realms = list_create();
3013     if (!realms)
3014         debugx(1, DBG_ERR, "malloc failed");
3015
3016     rewriteconfs = hash_create();
3017     if (!rewriteconfs)
3018         debugx(1, DBG_ERR, "malloc failed");
3019
3020     if (!getgenericconfig(&cfs, NULL,
3021 #ifdef RADPROT_UDP
3022                           "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3023                           "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3024 #endif
3025 #ifdef RADPROT_TCP
3026                           "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3027                           "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3028 #endif
3029 #ifdef RADPROT_TLS
3030                           "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3031                           "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3032 #endif
3033 #ifdef RADPROT_DTLS
3034                           "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3035                           "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3036 #endif
3037                           "TTLAttribute", CONF_STR, &options.ttlattr,
3038                           "addTTL", CONF_LINT, &addttl,
3039                           "LogLevel", CONF_LINT, &loglevel,
3040                           "LogDestination", CONF_STR, &options.logdestination,
3041                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3042                           "Client", CONF_CBK, confclient_cb, NULL,
3043                           "Server", CONF_CBK, confserver_cb, NULL,
3044                           "Realm", CONF_CBK, confrealm_cb, NULL,
3045 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3046                           "TLS", CONF_CBK, conftls_cb, NULL,
3047 #endif
3048                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3049                           NULL
3050             ))
3051         debugx(1, DBG_ERR, "configuration error");
3052
3053     if (loglevel != LONG_MIN) {
3054         if (loglevel < 1 || loglevel > 4)
3055             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3056         options.loglevel = (uint8_t)loglevel;
3057     }
3058     if (addttl != LONG_MIN) {
3059         if (addttl < 1 || addttl > 255)
3060             debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3061         options.addttl = (uint8_t)addttl;
3062     }
3063     if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3064         debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3065
3066     for (i = 0; i < RAD_PROTOCOUNT; i++)
3067         if (listenargs[i] || sourcearg[i])
3068             setprotoopts(i, listenargs[i], sourcearg[i]);
3069 }
3070
3071 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3072     int c;
3073
3074     while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3075         switch (c) {
3076         case 'c':
3077             *configfile = optarg;
3078             break;
3079         case 'd':
3080             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3081                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3082             *loglevel = *optarg - '0';
3083             break;
3084         case 'f':
3085             *foreground = 1;
3086             break;
3087         case 'i':
3088             *pidfile = optarg;
3089             break;
3090         case 'p':
3091             *pretend = 1;
3092             break;
3093         case 'v':
3094             debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3095             debug(DBG_ERR, "This binary was built with support for the following transports:");
3096 #ifdef RADPROT_UDP
3097             debug(DBG_ERR, "  UDP");
3098 #endif
3099 #ifdef RADPROT_TCP
3100             debug(DBG_ERR, "  TCP");
3101 #endif
3102 #ifdef RADPROT_TLS
3103             debug(DBG_ERR, "  TLS");
3104 #endif
3105 #ifdef RADPROT_DTLS
3106             debug(DBG_ERR, "  DTLS");
3107 #endif
3108             exit(0);
3109         default:
3110             goto usage;
3111         }
3112     }
3113     if (!(argc - optind))
3114         return;
3115
3116 usage:
3117     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3118 }
3119
3120 #ifdef SYS_SOLARIS9
3121 int daemon(int a, int b) {
3122     int i;
3123
3124     if (fork())
3125         exit(0);
3126
3127     setsid();
3128
3129     for (i = 0; i < 3; i++) {
3130         close(i);
3131         open("/dev/null", O_RDWR);
3132     }
3133     return 1;
3134 }
3135 #endif
3136
3137 void *sighandler(void *arg) {
3138     sigset_t sigset;
3139     int sig;
3140
3141     for(;;) {
3142         sigemptyset(&sigset);
3143         sigaddset(&sigset, SIGHUP);
3144         sigaddset(&sigset, SIGPIPE);
3145         sigwait(&sigset, &sig);
3146         switch (sig) {
3147         case 0:
3148             /* completely ignoring this */
3149             break;
3150         case SIGHUP:
3151             debug(DBG_INFO, "sighandler: got SIGHUP");
3152             debug_reopen_log();
3153             break;
3154         case SIGPIPE:
3155             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3156             break;
3157         default:
3158             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3159         }
3160     }
3161 }
3162
3163 int createpidfile(const char *pidfile) {
3164     int r;
3165     FILE *f = fopen(pidfile, "w");
3166     if (f)
3167         r = fprintf(f, "%ld\n", (long) getpid());
3168     return f && !fclose(f) && r >= 0;
3169 }
3170
3171 int main(int argc, char **argv) {
3172     pthread_t sigth;
3173     sigset_t sigset;
3174     struct list_node *entry;
3175     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3176     char *configfile = NULL, *pidfile = NULL;
3177     struct clsrvconf *srvconf;
3178     int i;
3179
3180     debug_init("radsecproxy");
3181     debug_set_level(DEBUG_LEVEL);
3182
3183     for (i = 0; i < RAD_PROTOCOUNT; i++)
3184         protodefs[i] = protoinits[i](i);
3185
3186     /* needed even if no TLS/DTLS transport */
3187     sslinit();
3188
3189     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3190     if (loglevel)
3191         debug_set_level(loglevel);
3192     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3193     if (loglevel)
3194         options.loglevel = loglevel;
3195     else if (options.loglevel)
3196         debug_set_level(options.loglevel);
3197     if (!foreground)
3198         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3199     free(options.logdestination);
3200
3201     if (!list_first(clconfs))
3202         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3203     if (!list_first(realms))
3204         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3205
3206     if (pretend)
3207         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3208
3209     if (!foreground && (daemon(0, 0) < 0))
3210         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3211
3212     debug_timestamp_on();
3213     debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3214     if (pidfile && !createpidfile(pidfile))
3215         debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3216
3217     sigemptyset(&sigset);
3218     /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3219     sigaddset(&sigset, SIGHUP);
3220     sigaddset(&sigset, SIGPIPE);
3221     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3222     pthread_create(&sigth, NULL, sighandler, NULL);
3223
3224     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3225         srvconf = (struct clsrvconf *)entry->data;
3226         if (srvconf->dynamiclookupcommand)
3227             continue;
3228         if (!addserver(srvconf))
3229             debugx(1, DBG_ERR, "failed to add server");
3230         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3231                            (void *)(srvconf->servers)))
3232             debugx(1, DBG_ERR, "pthread_create failed");
3233     }
3234
3235     for (i = 0; i < RAD_PROTOCOUNT; i++) {
3236         if (!protodefs[i])
3237             continue;
3238         if (protodefs[i]->initextra)
3239             protodefs[i]->initextra();
3240         if (find_clconf_type(i, NULL))
3241             createlisteners(i);
3242     }
3243
3244     /* just hang around doing nothing, anything to do here? */
3245     for (;;)
3246         sleep(1000);
3247 }
3248
3249 /* Local Variables: */
3250 /* c-file-style: "stroustrup" */
3251 /* End: */