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