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