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