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