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