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