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