Handle failing rs_context_create().
[libradsec.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_NOTICE,
1638                           "%s for user %s stationid %s from %s (%s) to %s (%s)",
1639                           radmsgtype2string(msg->code), username, stationid,
1640                           server->conf->name, replymsg, from->conf->name,
1641                           addr2string(from->addr));
1642                     free(replymsg);
1643                 } else
1644                     debug(DBG_NOTICE,
1645                           "%s for user %s stationid %s from %s to %s (%s)",
1646                           radmsgtype2string(msg->code), username, stationid,
1647                           server->conf->name, from->conf->name,
1648                           addr2string(from->addr));
1649                 free(stationid);
1650             } else {
1651                 if (replymsg) {
1652                     debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1653                           radmsgtype2string(msg->code), username,
1654                           server->conf->name, replymsg, from->conf->name,
1655                           addr2string(from->addr));
1656                     free(replymsg);
1657                 } else
1658                     debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1659                           radmsgtype2string(msg->code), username,
1660                           server->conf->name, from->conf->name,
1661                           addr2string(from->addr));
1662             }
1663             free(username);
1664         }
1665     }
1666
1667     msg->id = (char)rqout->rq->rqid;
1668     memcpy(msg->auth, rqout->rq->rqauth, 16);
1669
1670 #ifdef DEBUG
1671     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1672 #endif
1673
1674     if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1675         if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1676             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1677             goto errunlock;
1678         }
1679         memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1680     }
1681
1682     if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1683         debug(DBG_WARN, "replyh: rewriteout failed");
1684         goto errunlock;
1685     }
1686
1687     if (ttlres == -1 && (options.addttl || from->conf->addttl))
1688         addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1689
1690     debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1691           "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1692
1693     radmsg_free(rqout->rq->msg);
1694     rqout->rq->msg = msg;
1695     sendreply(newrqref(rqout->rq));
1696     freerqoutdata(rqout);
1697     pthread_mutex_unlock(rqout->lock);
1698     return;
1699
1700 errunlock:
1701     radmsg_free(msg);
1702     pthread_mutex_unlock(rqout->lock);
1703     return;
1704 }
1705
1706 struct request *createstatsrvrq() {
1707     struct request *rq;
1708     struct tlv *attr;
1709
1710     rq = newrequest();
1711     if (!rq)
1712         return NULL;
1713     rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1714     if (!rq->msg)
1715         goto exit;
1716     attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1717     if (!attr)
1718         goto exit;
1719     if (!radmsg_add(rq->msg, attr)) {
1720         freetlv(attr);
1721         goto exit;
1722     }
1723     return rq;
1724
1725 exit:
1726     freerq(rq);
1727     return NULL;
1728 }
1729
1730 /* code for removing state not finished */
1731 void *clientwr(void *arg) {
1732     struct server *server = (struct server *)arg;
1733     struct rqout *rqout = NULL;
1734     pthread_t clientrdth;
1735     int i, dynconffail = 0;
1736     time_t secs;
1737     uint8_t rnd;
1738     struct timeval now, laststatsrv;
1739     struct timespec timeout;
1740     struct request *statsrvrq;
1741     struct clsrvconf *conf;
1742
1743     conf = server->conf;
1744
1745     if (server->dynamiclookuparg && !dynamicconfig(server)) {
1746         dynconffail = 1;
1747         server->dynstartup = 0;
1748         sleep(900);
1749         goto errexit;
1750     }
1751
1752     if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1753         debug(DBG_WARN, "clientwr: resolve failed");
1754         server->dynstartup = 0;
1755         sleep(900);
1756         goto errexit;
1757     }
1758
1759     memset(&timeout, 0, sizeof(struct timespec));
1760
1761     if (conf->statusserver) {
1762         gettimeofday(&server->lastrcv, NULL);
1763         gettimeofday(&laststatsrv, NULL);
1764     }
1765
1766     if (conf->pdef->connecter) {
1767         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1768             if (server->dynamiclookuparg) {
1769                 server->dynstartup = 0;
1770                 sleep(900);
1771             }
1772             goto errexit;
1773         }
1774         server->connectionok = 1;
1775         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1776             debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1777             goto errexit;
1778         }
1779     } else
1780         server->connectionok = 1;
1781     server->dynstartup = 0;
1782
1783     for (;;) {
1784         pthread_mutex_lock(&server->newrq_mutex);
1785         if (!server->newrq) {
1786             gettimeofday(&now, NULL);
1787             /* random 0-7 seconds */
1788             RAND_bytes(&rnd, 1);
1789             rnd /= 32;
1790             if (conf->statusserver) {
1791                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1792                 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1793                     secs = now.tv_sec;
1794                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1795                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1796             } else {
1797                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1798                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1799             }
1800 #if 0
1801             if (timeout.tv_sec > now.tv_sec)
1802                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1803 #endif
1804             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1805             timeout.tv_sec = 0;
1806         }
1807         if (server->newrq) {
1808             debug(DBG_DBG, "clientwr: got new request");
1809             server->newrq = 0;
1810         }
1811 #if 0
1812         else
1813             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1814 #endif
1815         pthread_mutex_unlock(&server->newrq_mutex);
1816
1817         for (i = 0; i < MAX_REQUESTS; i++) {
1818             if (server->clientrdgone) {
1819                 pthread_join(clientrdth, NULL);
1820                 goto errexit;
1821             }
1822
1823             for (; i < MAX_REQUESTS; i++) {
1824                 rqout = server->requests + i;
1825                 if (rqout->rq) {
1826                     pthread_mutex_lock(rqout->lock);
1827                     if (rqout->rq)
1828                         break;
1829                     pthread_mutex_unlock(rqout->lock);
1830                 }
1831             }
1832
1833             if (i == MAX_REQUESTS)
1834                 break;
1835
1836             gettimeofday(&now, NULL);
1837             if (now.tv_sec < rqout->expiry.tv_sec) {
1838                 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1839                     timeout.tv_sec = rqout->expiry.tv_sec;
1840                 pthread_mutex_unlock(rqout->lock);
1841                 continue;
1842             }
1843
1844             if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1845                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1846                 if (conf->statusserver) {
1847                     if (*rqout->rq->buf == RAD_Status_Server) {
1848                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1849                         if (server->lostrqs < 255)
1850                             server->lostrqs++;
1851                     }
1852                 } else {
1853                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1854                     if (server->lostrqs < 255)
1855                         server->lostrqs++;
1856                 }
1857                 freerqoutdata(rqout);
1858                 pthread_mutex_unlock(rqout->lock);
1859                 continue;
1860             }
1861
1862             rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1863             if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1864                 timeout.tv_sec = rqout->expiry.tv_sec;
1865             rqout->tries++;
1866             conf->pdef->clientradput(server, rqout->rq->buf);
1867             pthread_mutex_unlock(rqout->lock);
1868         }
1869         if (conf->statusserver && server->connectionok) {
1870             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1871             gettimeofday(&now, NULL);
1872             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1873                 laststatsrv = now;
1874                 statsrvrq = createstatsrvrq();
1875                 if (statsrvrq) {
1876                     statsrvrq->to = server;
1877                     debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1878                     sendrq(statsrvrq);
1879                 }
1880             }
1881         }
1882     }
1883 errexit:
1884     conf->servers = NULL;
1885     if (server->dynamiclookuparg) {
1886         removeserversubrealms(realms, conf);
1887         if (dynconffail)
1888             free(conf);
1889         else
1890             freeclsrvconf(conf);
1891     }
1892     freeserver(server, 1);
1893     ERR_remove_state(0);
1894     return NULL;
1895 }
1896
1897 void createlistener(uint8_t type, char *arg) {
1898     pthread_t th;
1899     struct addrinfo *res;
1900     int s = -1, on = 1, *sp = NULL;
1901     struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1902
1903     if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1904         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1905
1906     for (res = hp->addrinfo; res; res = res->ai_next) {
1907         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1908         if (s < 0) {
1909             debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1910             continue;
1911         }
1912         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1913
1914         disable_DF_bit(s, res);
1915
1916 #ifdef IPV6_V6ONLY
1917         if (res->ai_family == AF_INET6)
1918             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1919 #endif
1920         if (bind(s, res->ai_addr, res->ai_addrlen)) {
1921             debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1922             close(s);
1923             s = -1;
1924             continue;
1925         }
1926
1927         sp = malloc(sizeof(int));
1928         if (!sp)
1929             debugx(1, DBG_ERR, "malloc failed");
1930         *sp = s;
1931         if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1932             debugerrnox(errno, DBG_ERR, "pthread_create failed");
1933         pthread_detach(th);
1934     }
1935     if (!sp)
1936         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1937
1938     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1939     freehostport(hp);
1940 }
1941
1942 void createlisteners(uint8_t type) {
1943     int i;
1944     char **args;
1945
1946     args = protodefs[type]->getlistenerargs();
1947     if (args)
1948         for (i = 0; args[i]; i++)
1949             createlistener(type, args[i]);
1950     else
1951         createlistener(type, NULL);
1952 }
1953
1954 void sslinit() {
1955     int i;
1956     time_t t;
1957     pid_t pid;
1958
1959     ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1960     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1961     for (i = 0; i < CRYPTO_num_locks(); i++) {
1962         ssl_lock_count[i] = 0;
1963         pthread_mutex_init(&ssl_locks[i], NULL);
1964     }
1965     CRYPTO_set_id_callback(ssl_thread_id);
1966     CRYPTO_set_locking_callback(ssl_locking_callback);
1967
1968     SSL_load_error_strings();
1969     SSL_library_init();
1970
1971     while (!RAND_status()) {
1972         t = time(NULL);
1973         pid = getpid();
1974         RAND_seed((unsigned char *)&t, sizeof(time_t));
1975         RAND_seed((unsigned char *)&pid, sizeof(pid));
1976     }
1977 }
1978
1979 struct list *addsrvconfs(char *value, char **names) {
1980     struct list *conflist;
1981     int n;
1982     struct list_node *entry;
1983     struct clsrvconf *conf = NULL;
1984
1985     if (!names || !*names)
1986         return NULL;
1987
1988     conflist = list_create();
1989     if (!conflist) {
1990         debug(DBG_ERR, "malloc failed");
1991         return NULL;
1992     }
1993
1994     for (n = 0; names[n]; n++) {
1995         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1996             conf = (struct clsrvconf *)entry->data;
1997             if (!strcasecmp(names[n], conf->name))
1998                 break;
1999         }
2000         if (!entry) {
2001             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2002             list_destroy(conflist);
2003             return NULL;
2004         }
2005         if (!list_push(conflist, conf)) {
2006             debug(DBG_ERR, "malloc failed");
2007             list_destroy(conflist);
2008             return NULL;
2009         }
2010         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2011     }
2012     return conflist;
2013 }
2014
2015 void freerealm(struct realm *realm) {
2016     if (!realm)
2017         return;
2018     debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2019     if (--realm->refcount)
2020         return;
2021
2022     free(realm->name);
2023     free(realm->message);
2024     regfree(&realm->regex);
2025     pthread_mutex_destroy(&realm->mutex);
2026     /* if refcount == 0, all subrealms gone */
2027     list_destroy(realm->subrealms);
2028     /* if refcount == 0, all srvconfs gone */
2029     list_destroy(realm->srvconfs);
2030     /* if refcount == 0, all accsrvconfs gone */
2031     list_destroy(realm->accsrvconfs);
2032     freerealm(realm->parent);
2033     free(realm);
2034 }
2035
2036 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2037     int n;
2038     struct realm *realm;
2039     char *s, *regex = NULL;
2040
2041     if (*value == '/') {
2042         /* regexp, remove optional trailing / if present */
2043         if (value[strlen(value) - 1] == '/')
2044             value[strlen(value) - 1] = '\0';
2045     } else {
2046         /* not a regexp, let us make it one */
2047         if (*value == '*' && !value[1])
2048             regex = stringcopy(".*", 0);
2049         else {
2050             for (n = 0, s = value; *s;)
2051                 if (*s++ == '.')
2052                     n++;
2053             regex = malloc(strlen(value) + n + 3);
2054             if (regex) {
2055                 regex[0] = '@';
2056                 for (n = 1, s = value; *s; s++) {
2057                     if (*s == '.')
2058                         regex[n++] = '\\';
2059                     regex[n++] = *s;
2060                 }
2061                 regex[n++] = '$';
2062                 regex[n] = '\0';
2063             }
2064         }
2065         if (!regex) {
2066             debug(DBG_ERR, "malloc failed");
2067             realm = NULL;
2068             goto exit;
2069         }
2070         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2071     }
2072
2073     realm = malloc(sizeof(struct realm));
2074     if (!realm) {
2075         debug(DBG_ERR, "malloc failed");
2076         goto exit;
2077     }
2078     memset(realm, 0, sizeof(struct realm));
2079
2080     if (pthread_mutex_init(&realm->mutex, NULL)) {
2081         debugerrno(errno, DBG_ERR, "mutex init failed");
2082         free(realm);
2083         realm = NULL;
2084         goto exit;
2085     }
2086
2087     realm->name = stringcopy(value, 0);
2088     if (!realm->name) {
2089         debug(DBG_ERR, "malloc failed");
2090         goto errexit;
2091     }
2092     if (message && strlen(message) > 253) {
2093         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2094         goto errexit;
2095     }
2096     realm->message = message;
2097     realm->accresp = accresp;
2098
2099     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2100         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2101         goto errexit;
2102     }
2103
2104     if (servers && *servers) {
2105         realm->srvconfs = addsrvconfs(value, servers);
2106         if (!realm->srvconfs)
2107             goto errexit;
2108     }
2109
2110     if (accservers && *accservers) {
2111         realm->accsrvconfs = addsrvconfs(value, accservers);
2112         if (!realm->accsrvconfs)
2113             goto errexit;
2114     }
2115
2116     if (!list_push(realmlist, realm)) {
2117         debug(DBG_ERR, "malloc failed");
2118         pthread_mutex_destroy(&realm->mutex);
2119         goto errexit;
2120     }
2121
2122     debug(DBG_DBG, "addrealm: added realm %s", value);
2123     goto exit;
2124
2125 errexit:
2126     while (list_shift(realm->srvconfs));
2127     while (list_shift(realm->accsrvconfs));
2128     freerealm(realm);
2129     realm = NULL;
2130 exit:
2131     free(regex);
2132     if (servers) {
2133         if (realm)
2134             for (n = 0; servers[n]; n++)
2135                 newrealmref(realm);
2136         freegconfmstr(servers);
2137     }
2138     if (accservers) {
2139         if (realm)
2140             for (n = 0; accservers[n]; n++)
2141                 newrealmref(realm);
2142         freegconfmstr(accservers);
2143     }
2144     return newrealmref(realm);
2145 }
2146
2147 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2148     struct list_node *entry;
2149     struct clsrvconf *conf, *srvconf;
2150     struct list *subrealmservers = NULL;
2151     pthread_t clientth;
2152
2153     if (list_first(srvconfs)) {
2154         subrealmservers = list_create();
2155         if (!subrealmservers)
2156             return NULL;
2157     }
2158
2159     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2160         conf = (struct clsrvconf *)entry->data;
2161         if (!conf->servers && conf->dynamiclookupcommand) {
2162             srvconf = malloc(sizeof(struct clsrvconf));
2163             if (!srvconf) {
2164                 debug(DBG_ERR, "malloc failed");
2165                 continue;
2166             }
2167             *srvconf = *conf;
2168             if (addserver(srvconf)) {
2169                 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2170                 srvconf->servers->dynstartup = 1;
2171                 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2172                     debugerrno(errno, DBG_ERR, "pthread_create failed");
2173                     freeserver(srvconf->servers, 1);
2174                     srvconf->servers = NULL;
2175                 } else
2176                     pthread_detach(clientth);
2177             }
2178             conf = srvconf;
2179         }
2180         if (conf->servers) {
2181             if (list_push(subrealmservers, conf))
2182                 newrealmref(realm);
2183             else
2184                 debug(DBG_ERR, "malloc failed");
2185         }
2186     }
2187     return subrealmservers;
2188 }
2189
2190 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2191     struct realm *newrealm = NULL;
2192     char *realmname, *s;
2193
2194     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2195     realmname = strrchr(id, '@');
2196     if (!realmname)
2197         return NULL;
2198     realmname++;
2199     if (!*realmname)
2200         return NULL;
2201     for (s = realmname; *s; s++)
2202         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2203             return NULL;
2204
2205     if (!realm->subrealms)
2206         realm->subrealms = list_create();
2207     if (!realm->subrealms)
2208         return NULL;
2209
2210     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2211     if (!newrealm) {
2212         list_destroy(realm->subrealms);
2213         realm->subrealms = NULL;
2214         return NULL;
2215     }
2216
2217     newrealm->parent = newrealmref(realm);
2218     /* add server and accserver to newrealm */
2219     newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2220     newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2221     return newrealm;
2222 }
2223
2224 int dynamicconfig(struct server *server) {
2225     int ok, fd[2], status;
2226     pid_t pid;
2227     struct clsrvconf *conf = server->conf;
2228     struct gconffile *cf = NULL;
2229
2230     /* for now we only learn hostname/address */
2231     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2232
2233     if (pipe(fd) > 0) {
2234         debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2235         goto errexit;
2236     }
2237     pid = fork();
2238     if (pid < 0) {
2239         debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2240         close(fd[0]);
2241         close(fd[1]);
2242         goto errexit;
2243     } else if (pid == 0) {
2244         /* child */
2245         close(fd[0]);
2246         if (fd[1] != STDOUT_FILENO) {
2247             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2248                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2249             close(fd[1]);
2250         }
2251         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2252             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2253     }
2254
2255     close(fd[1]);
2256     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2257     ok = getgenericconfig(&cf, NULL,
2258                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2259                           NULL
2260         );
2261     freegconf(&cf);
2262
2263     if (waitpid(pid, &status, 0) < 0) {
2264         debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2265         goto errexit;
2266     }
2267
2268     if (status) {
2269         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2270         goto errexit;
2271     }
2272
2273     if (ok)
2274         return 1;
2275
2276 errexit:
2277     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2278     return 0;
2279 }
2280
2281 /* should accept both names and numeric values, only numeric right now */
2282 uint8_t attrname2val(char *attrname) {
2283     int val = 0;
2284
2285     val = atoi(attrname);
2286     return val > 0 && val < 256 ? val : 0;
2287 }
2288
2289 /* ATTRNAME is on the form vendor[:type].
2290    If only vendor is found, TYPE is set to 256 and 1 is returned.
2291    If type is >= 256, 1 is returned.
2292    Otherwise, 0 is returned.
2293 */
2294 /* should accept both names and numeric values, only numeric right now */
2295 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2296     char *s;
2297
2298     *vendor = atoi(attrname);
2299     s = strchr(attrname, ':');
2300     if (!s) {                   /* Only vendor was found.  */
2301         *type = 256;
2302         return 1;
2303     }
2304     *type = atoi(s + 1);
2305     return *type < 256;
2306 }
2307
2308 /** Extract attributes from string NAMEVAL, create a struct tlv and
2309  * return the tlv.  If VENDOR_FLAG, NAMEVAL is on the form
2310  * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>".  Return
2311  * NULL if fields are missing or if conversion fails.
2312  *
2313  * FIXME: Should accept both names and numeric values, only numeric
2314  * right now */
2315 struct tlv *extractattr(char *nameval, char vendor_flag) {
2316     int len, name = 0;
2317     int vendor = 0;         /* Vendor 0 is reserved, see RFC 1700.  */
2318     char *s, *s2;
2319     struct tlv *a;
2320
2321     s = strchr(nameval, ':');
2322     if (!s)
2323         return NULL;
2324     name = atoi(nameval);
2325
2326     if (vendor_flag) {
2327         s2 = strchr(s + 1, ':');
2328         if (!s2)
2329             return NULL;
2330         vendor = name;
2331         name = atoi(s + 1);
2332         s = s2;
2333     }
2334     len = strlen(s + 1);
2335     if (len > 253)
2336         return NULL;
2337
2338     if (name < 1 || name > 255)
2339         return NULL;
2340     a = malloc(sizeof(struct tlv));
2341     if (!a)
2342         return NULL;
2343
2344     a->v = (uint8_t *)stringcopy(s + 1, 0);
2345     if (!a->v) {
2346         free(a);
2347         return NULL;
2348     }
2349     a->t = name;
2350     a->l = len;
2351
2352     if (vendor_flag)
2353         a = makevendortlv(vendor, a);
2354
2355     return a;
2356 }
2357
2358 /* should accept both names and numeric values, only numeric right now */
2359 struct modattr *extractmodattr(char *nameval) {
2360     int name = 0;
2361     char *s, *t;
2362     struct modattr *m;
2363
2364     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2365         s = nameval + 11;
2366         name = 1;
2367     } else {
2368         s = strchr(nameval, ':');
2369         name = atoi(nameval);
2370         if (!s || name < 1 || name > 255 || s[1] != '/')
2371             return NULL;
2372         s += 2;
2373     }
2374     /* regexp, remove optional trailing / if present */
2375     if (s[strlen(s) - 1] == '/')
2376         s[strlen(s) - 1] = '\0';
2377
2378     t = strchr(s, '/');
2379     if (!t)
2380         return NULL;
2381     *t = '\0';
2382     t++;
2383
2384     m = malloc(sizeof(struct modattr));
2385     if (!m) {
2386         debug(DBG_ERR, "malloc failed");
2387         return NULL;
2388     }
2389     m->t = name;
2390
2391     m->replacement = stringcopy(t, 0);
2392     if (!m->replacement) {
2393         free(m);
2394         debug(DBG_ERR, "malloc failed");
2395         return NULL;
2396     }
2397
2398     m->regex = malloc(sizeof(regex_t));
2399     if (!m->regex) {
2400         free(m->replacement);
2401         free(m);
2402         debug(DBG_ERR, "malloc failed");
2403         return NULL;
2404     }
2405
2406     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2407         free(m->regex);
2408         free(m->replacement);
2409         free(m);
2410         debug(DBG_ERR, "failed to compile regular expression %s", s);
2411         return NULL;
2412     }
2413
2414     return m;
2415 }
2416
2417 struct rewrite *getrewrite(char *alt1, char *alt2) {
2418     struct rewrite *r;
2419
2420     if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
2421         return r;
2422     if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
2423         return r;
2424     return NULL;
2425 }
2426
2427 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2428 {
2429     struct rewrite *rewrite = NULL;
2430     int i, n;
2431     uint8_t *rma = NULL;
2432     uint32_t *p, *rmva = NULL;
2433     struct list *adda = NULL, *moda = NULL;
2434     struct tlv *a;
2435     struct modattr *m;
2436
2437     if (rmattrs) {
2438         for (n = 0; rmattrs[n]; n++);
2439         rma = calloc(n + 1, sizeof(uint8_t));
2440         if (!rma)
2441             debugx(1, DBG_ERR, "malloc failed");
2442
2443         for (i = 0; i < n; i++)
2444             if (!(rma[i] = attrname2val(rmattrs[i])))
2445                 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2446         freegconfmstr(rmattrs);
2447         rma[i] = 0;
2448     }
2449
2450     if (rmvattrs) {
2451         for (n = 0; rmvattrs[n]; n++);
2452         rmva = calloc(2 * n + 1, sizeof(uint32_t));
2453         if (!rmva)
2454             debugx(1, DBG_ERR, "malloc failed");
2455
2456         for (p = rmva, i = 0; i < n; i++, p += 2)
2457             if (!vattrname2val(rmvattrs[i], p, p + 1))
2458                 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2459         freegconfmstr(rmvattrs);
2460         *p = 0;
2461     }
2462
2463     if (addattrs) {
2464         adda = list_create();
2465         if (!adda)
2466             debugx(1, DBG_ERR, "malloc failed");
2467         for (i = 0; addattrs[i]; i++) {
2468             a = extractattr(addattrs[i], 0);
2469             if (!a)
2470                 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2471             if (!list_push(adda, a))
2472                 debugx(1, DBG_ERR, "malloc failed");
2473         }
2474         freegconfmstr(addattrs);
2475     }
2476
2477     if (addvattrs) {
2478         if (!adda)
2479             adda = list_create();
2480         if (!adda)
2481             debugx(1, DBG_ERR, "malloc failed");
2482         for (i = 0; addvattrs[i]; i++) {
2483             a = extractattr(addvattrs[i], 1);
2484             if (!a)
2485                 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2486             if (!list_push(adda, a))
2487                 debugx(1, DBG_ERR, "malloc failed");
2488         }
2489         freegconfmstr(addvattrs);
2490     }
2491
2492     if (modattrs) {
2493         moda = list_create();
2494         if (!moda)
2495             debugx(1, DBG_ERR, "malloc failed");
2496         for (i = 0; modattrs[i]; i++) {
2497             m = extractmodattr(modattrs[i]);
2498             if (!m)
2499                 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2500             if (!list_push(moda, m))
2501                 debugx(1, DBG_ERR, "malloc failed");
2502         }
2503         freegconfmstr(modattrs);
2504     }
2505
2506     if (rma || rmva || adda || moda) {
2507         rewrite = malloc(sizeof(struct rewrite));
2508         if (!rewrite)
2509             debugx(1, DBG_ERR, "malloc failed");
2510         rewrite->removeattrs = rma;
2511         rewrite->removevendorattrs = rmva;
2512         rewrite->addattrs = adda;
2513         rewrite->modattrs = moda;
2514     }
2515
2516     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2517         debugx(1, DBG_ERR, "malloc failed");
2518     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2519 }
2520
2521 int setttlattr(struct options *opts, char *defaultattr) {
2522     char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2523
2524     if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2525         (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2526         return 1;
2527     debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2528     return 0;
2529 }
2530
2531 void freeclsrvconf(struct clsrvconf *conf) {
2532     free(conf->name);
2533     if (conf->hostsrc)
2534         freegconfmstr(conf->hostsrc);
2535     free(conf->portsrc);
2536     free(conf->secret);
2537     free(conf->tls);
2538     free(conf->matchcertattr);
2539     if (conf->certcnregex)
2540         regfree(conf->certcnregex);
2541     if (conf->certuriregex)
2542         regfree(conf->certuriregex);
2543     free(conf->confrewritein);
2544     free(conf->confrewriteout);
2545     if (conf->rewriteusername) {
2546         if (conf->rewriteusername->regex)
2547             regfree(conf->rewriteusername->regex);
2548         free(conf->rewriteusername->replacement);
2549         free(conf->rewriteusername);
2550     }
2551     free(conf->dynamiclookupcommand);
2552     free(conf->rewritein);
2553     free(conf->rewriteout);
2554     if (conf->hostports)
2555         freehostports(conf->hostports);
2556     if (conf->lock) {
2557         pthread_mutex_destroy(conf->lock);
2558         free(conf->lock);
2559     }
2560     /* not touching ssl_ctx, clients and servers */
2561     free(conf);
2562 }
2563
2564 int mergeconfstring(char **dst, char **src) {
2565     char *t;
2566
2567     if (*src) {
2568         *dst = *src;
2569         *src = NULL;
2570         return 1;
2571     }
2572     if (*dst) {
2573         t = stringcopy(*dst, 0);
2574         if (!t) {
2575             debug(DBG_ERR, "malloc failed");
2576             return 0;
2577         }
2578         *dst = t;
2579     }
2580     return 1;
2581 }
2582
2583 char **mstringcopy(char **in) {
2584     char **out;
2585     int n;
2586
2587     if (!in)
2588         return NULL;
2589
2590     for (n = 0; in[n]; n++);
2591     out = malloc((n + 1) * sizeof(char *));
2592     if (!out)
2593         return NULL;
2594     for (n = 0; in[n]; n++) {
2595         out[n] = stringcopy(in[n], 0);
2596         if (!out[n]) {
2597             freegconfmstr(out);
2598             return NULL;
2599         }
2600     }
2601     out[n] = NULL;
2602     return out;
2603 }
2604
2605 int mergeconfmstring(char ***dst, char ***src) {
2606     char **t;
2607
2608     if (*src) {
2609         *dst = *src;
2610         *src = NULL;
2611         return 1;
2612     }
2613     if (*dst) {
2614         t = mstringcopy(*dst);
2615         if (!t) {
2616             debug(DBG_ERR, "malloc failed");
2617             return 0;
2618         }
2619         *dst = t;
2620     }
2621     return 1;
2622 }
2623
2624 /* assumes dst is a shallow copy */
2625 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2626     if (!mergeconfstring(&dst->name, &src->name) ||
2627         !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2628         !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2629         !mergeconfstring(&dst->secret, &src->secret) ||
2630         !mergeconfstring(&dst->tls, &src->tls) ||
2631         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2632         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2633         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2634         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2635         return 0;
2636     if (src->pdef)
2637         dst->pdef = src->pdef;
2638     dst->statusserver = src->statusserver;
2639     dst->certnamecheck = src->certnamecheck;
2640     if (src->retryinterval != 255)
2641         dst->retryinterval = src->retryinterval;
2642     if (src->retrycount != 255)
2643         dst->retrycount = src->retrycount;
2644     return 1;
2645 }
2646
2647 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2648     struct clsrvconf *conf;
2649     char *conftype = NULL, *rewriteinalias = NULL;
2650     long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2651
2652     debug(DBG_DBG, "confclient_cb called for %s", block);
2653
2654     conf = malloc(sizeof(struct clsrvconf));
2655     if (!conf)
2656         debugx(1, DBG_ERR, "malloc failed");
2657     memset(conf, 0, sizeof(struct clsrvconf));
2658     conf->certnamecheck = 1;
2659
2660     if (!getgenericconfig(cf, block,
2661                           "type", CONF_STR, &conftype,
2662                           "host", CONF_MSTR, &conf->hostsrc,
2663                           "secret", CONF_STR, &conf->secret,
2664 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2665                           "tls", CONF_STR, &conf->tls,
2666                           "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2667                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2668 #endif
2669                           "DuplicateInterval", CONF_LINT, &dupinterval,
2670                           "addTTL", CONF_LINT, &addttl,
2671                           "rewrite", CONF_STR, &rewriteinalias,
2672                           "rewriteIn", CONF_STR, &conf->confrewritein,
2673                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2674                           "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2675                           NULL
2676             ))
2677         debugx(1, DBG_ERR, "configuration error");
2678
2679     conf->name = stringcopy(val, 0);
2680     if (conf->name && !conf->hostsrc) {
2681         conf->hostsrc = malloc(2 * sizeof(char *));
2682         if (conf->hostsrc) {
2683             conf->hostsrc[0] = stringcopy(val, 0);
2684             conf->hostsrc[1] = NULL;
2685         }
2686     }
2687     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2688         debugx(1, DBG_ERR, "malloc failed");
2689
2690     if (!conftype)
2691         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2692     conf->type = protoname2int(conftype);
2693     if (conf->type == 255)
2694         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2695     free(conftype);
2696     conf->pdef = protodefs[conf->type];
2697
2698 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2699     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2700         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2701         if (!conf->tlsconf)
2702             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2703         if (conf->matchcertattr && !addmatchcertattr(conf))
2704             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2705     }
2706 #endif
2707
2708     if (dupinterval != LONG_MIN) {
2709         if (dupinterval < 0 || dupinterval > 255)
2710             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2711         conf->dupinterval = (uint8_t)dupinterval;
2712     } else
2713         conf->dupinterval = conf->pdef->duplicateintervaldefault;
2714
2715     if (addttl != LONG_MIN) {
2716         if (addttl < 1 || addttl > 255)
2717             debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2718         conf->addttl = (uint8_t)addttl;
2719     }
2720
2721     if (!conf->confrewritein)
2722         conf->confrewritein = rewriteinalias;
2723     else
2724         free(rewriteinalias);
2725     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2726     if (conf->confrewriteout)
2727         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2728
2729     if (conf->confrewriteusername) {
2730         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2731         if (!conf->rewriteusername)
2732             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2733     }
2734
2735     if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2736         !resolvehostports(conf->hostports, conf->pdef->socktype))
2737         debugx(1, DBG_ERR, "resolve failed, exiting");
2738
2739     if (!conf->secret) {
2740         if (!conf->pdef->secretdefault)
2741             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2742         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2743         if (!conf->secret)
2744             debugx(1, DBG_ERR, "malloc failed");
2745     }
2746
2747     conf->lock = malloc(sizeof(pthread_mutex_t));
2748     if (!conf->lock)
2749         debugx(1, DBG_ERR, "malloc failed");
2750
2751     pthread_mutex_init(conf->lock, NULL);
2752     if (!list_push(clconfs, conf))
2753         debugx(1, DBG_ERR, "malloc failed");
2754     return 1;
2755 }
2756
2757 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2758 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2759     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2760         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2761         if (!conf->tlsconf) {
2762             debug(DBG_ERR, "error in block %s, no tls context defined", block);
2763             return 0;
2764         }
2765         if (conf->matchcertattr && !addmatchcertattr(conf)) {
2766             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2767             return 0;
2768         }
2769     }
2770 #endif
2771
2772     if (!conf->portsrc) {
2773         conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2774         if (!conf->portsrc) {
2775             debug(DBG_ERR, "malloc failed");
2776             return 0;
2777         }
2778     }
2779
2780     if (conf->retryinterval == 255)
2781         conf->retryinterval = conf->pdef->retryintervaldefault;
2782     if (conf->retrycount == 255)
2783         conf->retrycount = conf->pdef->retrycountdefault;
2784
2785     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2786     if (conf->confrewriteout)
2787         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2788
2789     if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2790         debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2791         return 0;
2792     }
2793
2794     if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2795         debug(DBG_ERR, "resolve failed, exiting");
2796         return 0;
2797     }
2798     return 1;
2799 }
2800
2801 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2802     struct clsrvconf *conf, *resconf;
2803     char *conftype = NULL, *rewriteinalias = NULL;
2804     long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2805
2806     debug(DBG_DBG, "confserver_cb called for %s", block);
2807
2808     conf = malloc(sizeof(struct clsrvconf));
2809     if (!conf) {
2810         debug(DBG_ERR, "malloc failed");
2811         return 0;
2812     }
2813     memset(conf, 0, sizeof(struct clsrvconf));
2814     conf->loopprevention = UCHAR_MAX; /* Uninitialized.  */
2815     resconf = (struct clsrvconf *)arg;
2816     if (resconf) {
2817         conf->statusserver = resconf->statusserver;
2818         conf->certnamecheck = resconf->certnamecheck;
2819     } else
2820         conf->certnamecheck = 1;
2821
2822     if (!getgenericconfig(cf, block,
2823                           "type", CONF_STR, &conftype,
2824                           "host", CONF_MSTR, &conf->hostsrc,
2825                           "port", CONF_STR, &conf->portsrc,
2826                           "secret", CONF_STR, &conf->secret,
2827 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2828                           "tls", CONF_STR, &conf->tls,
2829                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2830                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2831 #endif
2832                           "addTTL", CONF_LINT, &addttl,
2833                           "rewrite", CONF_STR, &rewriteinalias,
2834                           "rewriteIn", CONF_STR, &conf->confrewritein,
2835                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2836                           "StatusServer", CONF_BLN, &conf->statusserver,
2837                           "RetryInterval", CONF_LINT, &retryinterval,
2838                           "RetryCount", CONF_LINT, &retrycount,
2839                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2840                           "LoopPrevention", CONF_BLN, &conf->loopprevention,
2841                           NULL
2842             )) {
2843         debug(DBG_ERR, "configuration error");
2844         goto errexit;
2845     }
2846
2847     conf->name = stringcopy(val, 0);
2848     if (conf->name && !conf->hostsrc) {
2849         conf->hostsrc = malloc(2 * sizeof(char *));
2850         if (conf->hostsrc) {
2851             conf->hostsrc[0] = stringcopy(val, 0);
2852             conf->hostsrc[1] = NULL;
2853         }
2854     }
2855     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2856         debug(DBG_ERR, "malloc failed");
2857         goto errexit;
2858     }
2859
2860     if (!conftype) {
2861         debug(DBG_ERR, "error in block %s, option type missing", block);
2862         goto errexit;
2863     }
2864     conf->type = protoname2int(conftype);
2865     if (conf->type == 255) {
2866         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2867         goto errexit;
2868     }
2869     free(conftype);
2870     conftype = NULL;
2871
2872     conf->pdef = protodefs[conf->type];
2873
2874     if (!conf->confrewritein)
2875         conf->confrewritein = rewriteinalias;
2876     else
2877         free(rewriteinalias);
2878     rewriteinalias = NULL;
2879
2880     if (retryinterval != LONG_MIN) {
2881         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2882             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2883             goto errexit;
2884         }
2885         conf->retryinterval = (uint8_t)retryinterval;
2886     } else
2887         conf->retryinterval = 255;
2888
2889     if (retrycount != LONG_MIN) {
2890         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2891             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2892             goto errexit;
2893         }
2894         conf->retrycount = (uint8_t)retrycount;
2895     } else
2896         conf->retrycount = 255;
2897
2898     if (addttl != LONG_MIN) {
2899         if (addttl < 1 || addttl > 255) {
2900             debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2901             goto errexit;
2902         }
2903         conf->addttl = (uint8_t)addttl;
2904     }
2905
2906     if (resconf) {
2907         if (!mergesrvconf(resconf, conf))
2908             goto errexit;
2909         free(conf);
2910         conf = resconf;
2911         if (conf->dynamiclookupcommand) {
2912             free(conf->dynamiclookupcommand);
2913             conf->dynamiclookupcommand = NULL;
2914         }
2915     }
2916
2917     if (resconf || !conf->dynamiclookupcommand) {
2918         if (!compileserverconfig(conf, block))
2919             goto errexit;
2920     }
2921
2922     if (!conf->secret) {
2923         if (!conf->pdef->secretdefault) {
2924             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2925             return 0;
2926         }
2927         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2928         if (!conf->secret) {
2929             debug(DBG_ERR, "malloc failed");
2930             return 0;
2931         }
2932     }
2933
2934     if (resconf)
2935         return 1;
2936
2937     if (!list_push(srvconfs, conf)) {
2938         debug(DBG_ERR, "malloc failed");
2939         goto errexit;
2940     }
2941     return 1;
2942
2943 errexit:
2944     free(conftype);
2945     free(rewriteinalias);
2946     freeclsrvconf(conf);
2947     return 0;
2948 }
2949
2950 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2951     char **servers = NULL, **accservers = NULL, *msg = NULL;
2952     uint8_t accresp = 0;
2953
2954     debug(DBG_DBG, "confrealm_cb called for %s", block);
2955
2956     if (!getgenericconfig(cf, block,
2957                           "server", CONF_MSTR, &servers,
2958                           "accountingServer", CONF_MSTR, &accservers,
2959                           "ReplyMessage", CONF_STR, &msg,
2960                           "AccountingResponse", CONF_BLN, &accresp,
2961                           NULL
2962             ))
2963         debugx(1, DBG_ERR, "configuration error");
2964
2965     addrealm(realms, val, servers, accservers, msg, accresp);
2966     return 1;
2967 }
2968
2969 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2970     char **rmattrs = NULL, **rmvattrs = NULL;
2971     char **addattrs = NULL, **addvattrs = NULL;
2972     char **modattrs = NULL;
2973
2974     debug(DBG_DBG, "confrewrite_cb called for %s", block);
2975
2976     if (!getgenericconfig(cf, block,
2977                           "removeAttribute", CONF_MSTR, &rmattrs,
2978                           "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2979                           "addAttribute", CONF_MSTR, &addattrs,
2980                           "addVendorAttribute", CONF_MSTR, &addvattrs,
2981                           "modifyAttribute", CONF_MSTR, &modattrs,
2982                           NULL
2983             ))
2984         debugx(1, DBG_ERR, "configuration error");
2985     addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2986     return 1;
2987 }
2988
2989 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2990     struct commonprotoopts *protoopts;
2991
2992     protoopts = malloc(sizeof(struct commonprotoopts));
2993     if (!protoopts)
2994         return 0;
2995     memset(protoopts, 0, sizeof(struct commonprotoopts));
2996     protoopts->listenargs = listenargs;
2997     protoopts->sourcearg = sourcearg;
2998     protodefs[type]->setprotoopts(protoopts);
2999     return 1;
3000 }
3001
3002 void getmainconfig(const char *configfile) {
3003     long int addttl = LONG_MIN, loglevel = LONG_MIN;
3004     struct gconffile *cfs;
3005     char **listenargs[RAD_PROTOCOUNT];
3006     char *sourcearg[RAD_PROTOCOUNT];
3007     int i;
3008
3009     cfs = openconfigfile(configfile);
3010     memset(&options, 0, sizeof(options));
3011     memset(&listenargs, 0, sizeof(listenargs));
3012     memset(&sourcearg, 0, sizeof(sourcearg));
3013
3014     clconfs = list_create();
3015     if (!clconfs)
3016         debugx(1, DBG_ERR, "malloc failed");
3017
3018     srvconfs = list_create();
3019     if (!srvconfs)
3020         debugx(1, DBG_ERR, "malloc failed");
3021
3022     realms = list_create();
3023     if (!realms)
3024         debugx(1, DBG_ERR, "malloc failed");
3025
3026     rewriteconfs = hash_create();
3027     if (!rewriteconfs)
3028         debugx(1, DBG_ERR, "malloc failed");
3029
3030     if (!getgenericconfig(&cfs, NULL,
3031 #ifdef RADPROT_UDP
3032                           "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3033                           "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3034 #endif
3035 #ifdef RADPROT_TCP
3036                           "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3037                           "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3038 #endif
3039 #ifdef RADPROT_TLS
3040                           "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3041                           "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3042 #endif
3043 #ifdef RADPROT_DTLS
3044                           "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3045                           "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3046 #endif
3047                           "TTLAttribute", CONF_STR, &options.ttlattr,
3048                           "addTTL", CONF_LINT, &addttl,
3049                           "LogLevel", CONF_LINT, &loglevel,
3050                           "LogDestination", CONF_STR, &options.logdestination,
3051                           "LoopPrevention", CONF_BLN, &options.loopprevention,
3052                           "Client", CONF_CBK, confclient_cb, NULL,
3053                           "Server", CONF_CBK, confserver_cb, NULL,
3054                           "Realm", CONF_CBK, confrealm_cb, NULL,
3055 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3056                           "TLS", CONF_CBK, conftls_cb, NULL,
3057 #endif
3058                           "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3059                           NULL
3060             ))
3061         debugx(1, DBG_ERR, "configuration error");
3062
3063     if (loglevel != LONG_MIN) {
3064         if (loglevel < 1 || loglevel > 5)
3065             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3066         options.loglevel = (uint8_t)loglevel;
3067     }
3068     if (addttl != LONG_MIN) {
3069         if (addttl < 1 || addttl > 255)
3070             debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3071         options.addttl = (uint8_t)addttl;
3072     }
3073     if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3074         debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3075
3076     for (i = 0; i < RAD_PROTOCOUNT; i++)
3077         if (listenargs[i] || sourcearg[i])
3078             setprotoopts(i, listenargs[i], sourcearg[i]);
3079 }
3080
3081 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3082     int c;
3083
3084     while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3085         switch (c) {
3086         case 'c':
3087             *configfile = optarg;
3088             break;
3089         case 'd':
3090             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3091                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3092             *loglevel = *optarg - '0';
3093             break;
3094         case 'f':
3095             *foreground = 1;
3096             break;
3097         case 'i':
3098             *pidfile = optarg;
3099             break;
3100         case 'p':
3101             *pretend = 1;
3102             break;
3103         case 'v':
3104             debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3105             debug(DBG_ERR, "This binary was built with support for the following transports:");
3106 #ifdef RADPROT_UDP
3107             debug(DBG_ERR, "  UDP");
3108 #endif
3109 #ifdef RADPROT_TCP
3110             debug(DBG_ERR, "  TCP");
3111 #endif
3112 #ifdef RADPROT_TLS
3113             debug(DBG_ERR, "  TLS");
3114 #endif
3115 #ifdef RADPROT_DTLS
3116             debug(DBG_ERR, "  DTLS");
3117 #endif
3118             exit(0);
3119         default:
3120             goto usage;
3121         }
3122     }
3123     if (!(argc - optind))
3124         return;
3125
3126 usage:
3127     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3128 }
3129
3130 #ifdef SYS_SOLARIS9
3131 int daemon(int a, int b) {
3132     int i;
3133
3134     if (fork())
3135         exit(0);
3136
3137     setsid();
3138
3139     for (i = 0; i < 3; i++) {
3140         close(i);
3141         open("/dev/null", O_RDWR);
3142     }
3143     return 1;
3144 }
3145 #endif
3146
3147 void *sighandler(void *arg) {
3148     sigset_t sigset;
3149     int sig;
3150
3151     for(;;) {
3152         sigemptyset(&sigset);
3153         sigaddset(&sigset, SIGHUP);
3154         sigaddset(&sigset, SIGPIPE);
3155         sigwait(&sigset, &sig);
3156         switch (sig) {
3157         case 0:
3158             /* completely ignoring this */
3159             break;
3160         case SIGHUP:
3161             debug(DBG_INFO, "sighandler: got SIGHUP");
3162             debug_reopen_log();
3163             break;
3164         case SIGPIPE:
3165             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3166             break;
3167         default:
3168             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3169         }
3170     }
3171 }
3172
3173 int createpidfile(const char *pidfile) {
3174     int r = 0;
3175     FILE *f = fopen(pidfile, "w");
3176     if (f)
3177         r = fprintf(f, "%ld\n", (long) getpid());
3178     return f && !fclose(f) && r >= 0;
3179 }
3180
3181 int main(int argc, char **argv) {
3182     pthread_t sigth;
3183     sigset_t sigset;
3184     struct list_node *entry;
3185     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3186     char *configfile = NULL, *pidfile = NULL;
3187     struct clsrvconf *srvconf;
3188     int i;
3189
3190     debug_init("radsecproxy");
3191     debug_set_level(DEBUG_LEVEL);
3192
3193     for (i = 0; i < RAD_PROTOCOUNT; i++)
3194         protodefs[i] = protoinits[i](i);
3195
3196     /* needed even if no TLS/DTLS transport */
3197     sslinit();
3198
3199     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3200     if (loglevel)
3201         debug_set_level(loglevel);
3202     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3203     if (loglevel)
3204         options.loglevel = loglevel;
3205     else if (options.loglevel)
3206         debug_set_level(options.loglevel);
3207     if (!foreground)
3208         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3209     free(options.logdestination);
3210
3211     if (!list_first(clconfs))
3212         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3213     if (!list_first(realms))
3214         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3215
3216     if (pretend)
3217         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3218
3219     if (!foreground && (daemon(0, 0) < 0))
3220         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3221
3222     debug_timestamp_on();
3223     debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3224     if (pidfile && !createpidfile(pidfile))
3225         debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3226
3227     sigemptyset(&sigset);
3228     /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3229     sigaddset(&sigset, SIGHUP);
3230     sigaddset(&sigset, SIGPIPE);
3231     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3232     pthread_create(&sigth, NULL, sighandler, NULL);
3233
3234     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3235         srvconf = (struct clsrvconf *)entry->data;
3236         if (srvconf->dynamiclookupcommand)
3237             continue;
3238         if (!addserver(srvconf))
3239             debugx(1, DBG_ERR, "failed to add server");
3240         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3241                            (void *)(srvconf->servers)))
3242             debugx(1, DBG_ERR, "pthread_create failed");
3243     }
3244
3245     for (i = 0; i < RAD_PROTOCOUNT; i++) {
3246         if (!protodefs[i])
3247             continue;
3248         if (protodefs[i]->initextra)
3249             protodefs[i]->initextra();
3250         if (find_clconf_type(i, NULL))
3251             createlisteners(i);
3252     }
3253
3254     /* just hang around doing nothing, anything to do here? */
3255     for (;;)
3256         sleep(1000);
3257 }
3258
3259 /* Local Variables: */
3260 /* c-file-style: "stroustrup" */
3261 /* End: */