Move configure_fticks to fticks.c.
[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         fticks_log(&options, from, msg, rqout);
1697
1698     radmsg_free(rqout->rq->msg);
1699     rqout->rq->msg = msg;
1700     sendreply(newrqref(rqout->rq));
1701     freerqoutdata(rqout);
1702     pthread_mutex_unlock(rqout->lock);
1703     return;
1704
1705 errunlock:
1706     radmsg_free(msg);
1707     pthread_mutex_unlock(rqout->lock);
1708     return;
1709 }
1710
1711 struct request *createstatsrvrq() {
1712     struct request *rq;
1713     struct tlv *attr;
1714
1715     rq = newrequest();
1716     if (!rq)
1717         return NULL;
1718     rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1719     if (!rq->msg)
1720         goto exit;
1721     attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1722     if (!attr)
1723         goto exit;
1724     if (!radmsg_add(rq->msg, attr)) {
1725         freetlv(attr);
1726         goto exit;
1727     }
1728     return rq;
1729
1730 exit:
1731     freerq(rq);
1732     return NULL;
1733 }
1734
1735 /* code for removing state not finished */
1736 void *clientwr(void *arg) {
1737     struct server *server = (struct server *)arg;
1738     struct rqout *rqout = NULL;
1739     pthread_t clientrdth;
1740     int i, dynconffail = 0;
1741     time_t secs;
1742     uint8_t rnd;
1743     struct timeval now, laststatsrv;
1744     struct timespec timeout;
1745     struct request *statsrvrq;
1746     struct clsrvconf *conf;
1747
1748     conf = server->conf;
1749
1750     if (server->dynamiclookuparg && !dynamicconfig(server)) {
1751         dynconffail = 1;
1752         server->dynstartup = 0;
1753         sleep(900);
1754         goto errexit;
1755     }
1756
1757     if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1758         debug(DBG_WARN, "clientwr: resolve failed");
1759         server->dynstartup = 0;
1760         sleep(900);
1761         goto errexit;
1762     }
1763
1764     memset(&timeout, 0, sizeof(struct timespec));
1765
1766     if (conf->statusserver) {
1767         gettimeofday(&server->lastrcv, NULL);
1768         gettimeofday(&laststatsrv, NULL);
1769     }
1770
1771     if (conf->pdef->connecter) {
1772         if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1773             if (server->dynamiclookuparg) {
1774                 server->dynstartup = 0;
1775                 sleep(900);
1776             }
1777             goto errexit;
1778         }
1779         server->connectionok = 1;
1780         if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1781             debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1782             goto errexit;
1783         }
1784     } else
1785         server->connectionok = 1;
1786     server->dynstartup = 0;
1787
1788     for (;;) {
1789         pthread_mutex_lock(&server->newrq_mutex);
1790         if (!server->newrq) {
1791             gettimeofday(&now, NULL);
1792             /* random 0-7 seconds */
1793             RAND_bytes(&rnd, 1);
1794             rnd /= 32;
1795             if (conf->statusserver) {
1796                 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1797                 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1798                     secs = now.tv_sec;
1799                 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1800                     timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1801             } else {
1802                 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1803                     timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1804             }
1805 #if 0
1806             if (timeout.tv_sec > now.tv_sec)
1807                 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1808 #endif
1809             pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1810             timeout.tv_sec = 0;
1811         }
1812         if (server->newrq) {
1813             debug(DBG_DBG, "clientwr: got new request");
1814             server->newrq = 0;
1815         }
1816 #if 0
1817         else
1818             debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1819 #endif
1820         pthread_mutex_unlock(&server->newrq_mutex);
1821
1822         for (i = 0; i < MAX_REQUESTS; i++) {
1823             if (server->clientrdgone) {
1824                 pthread_join(clientrdth, NULL);
1825                 goto errexit;
1826             }
1827
1828             for (; i < MAX_REQUESTS; i++) {
1829                 rqout = server->requests + i;
1830                 if (rqout->rq) {
1831                     pthread_mutex_lock(rqout->lock);
1832                     if (rqout->rq)
1833                         break;
1834                     pthread_mutex_unlock(rqout->lock);
1835                 }
1836             }
1837
1838             if (i == MAX_REQUESTS)
1839                 break;
1840
1841             gettimeofday(&now, NULL);
1842             if (now.tv_sec < rqout->expiry.tv_sec) {
1843                 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1844                     timeout.tv_sec = rqout->expiry.tv_sec;
1845                 pthread_mutex_unlock(rqout->lock);
1846                 continue;
1847             }
1848
1849             if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1850                 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1851                 if (conf->statusserver) {
1852                     if (*rqout->rq->buf == RAD_Status_Server) {
1853                         debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1854                         if (server->lostrqs < 255)
1855                             server->lostrqs++;
1856                     }
1857                 } else {
1858                     debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1859                     if (server->lostrqs < 255)
1860                         server->lostrqs++;
1861                 }
1862                 freerqoutdata(rqout);
1863                 pthread_mutex_unlock(rqout->lock);
1864                 continue;
1865             }
1866
1867             rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1868             if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1869                 timeout.tv_sec = rqout->expiry.tv_sec;
1870             rqout->tries++;
1871             conf->pdef->clientradput(server, rqout->rq->buf);
1872             pthread_mutex_unlock(rqout->lock);
1873         }
1874         if (conf->statusserver && server->connectionok) {
1875             secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1876             gettimeofday(&now, NULL);
1877             if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1878                 laststatsrv = now;
1879                 statsrvrq = createstatsrvrq();
1880                 if (statsrvrq) {
1881                     statsrvrq->to = server;
1882                     debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1883                     sendrq(statsrvrq);
1884                 }
1885             }
1886         }
1887     }
1888 errexit:
1889     conf->servers = NULL;
1890     if (server->dynamiclookuparg) {
1891         removeserversubrealms(realms, conf);
1892         if (dynconffail)
1893             free(conf);
1894         else
1895             freeclsrvconf(conf);
1896     }
1897     freeserver(server, 1);
1898     ERR_remove_state(0);
1899     return NULL;
1900 }
1901
1902 void createlistener(uint8_t type, char *arg) {
1903     pthread_t th;
1904     struct addrinfo *res;
1905     int s = -1, on = 1, *sp = NULL;
1906     struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1907
1908     if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1909         debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1910
1911     for (res = hp->addrinfo; res; res = res->ai_next) {
1912         s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1913         if (s < 0) {
1914             debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1915             continue;
1916         }
1917         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1918
1919         disable_DF_bit(s, res);
1920
1921 #ifdef IPV6_V6ONLY
1922         if (res->ai_family == AF_INET6)
1923             setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1924 #endif
1925         if (bind(s, res->ai_addr, res->ai_addrlen)) {
1926             debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1927             close(s);
1928             s = -1;
1929             continue;
1930         }
1931
1932         sp = malloc(sizeof(int));
1933         if (!sp)
1934             debugx(1, DBG_ERR, "malloc failed");
1935         *sp = s;
1936         if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1937             debugerrnox(errno, DBG_ERR, "pthread_create failed");
1938         pthread_detach(th);
1939     }
1940     if (!sp)
1941         debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1942
1943     debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1944     freehostport(hp);
1945 }
1946
1947 void createlisteners(uint8_t type) {
1948     int i;
1949     char **args;
1950
1951     args = protodefs[type]->getlistenerargs();
1952     if (args)
1953         for (i = 0; args[i]; i++)
1954             createlistener(type, args[i]);
1955     else
1956         createlistener(type, NULL);
1957 }
1958
1959 void sslinit() {
1960     int i;
1961     time_t t;
1962     pid_t pid;
1963
1964     ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1965     ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1966     for (i = 0; i < CRYPTO_num_locks(); i++) {
1967         ssl_lock_count[i] = 0;
1968         pthread_mutex_init(&ssl_locks[i], NULL);
1969     }
1970     CRYPTO_set_id_callback(ssl_thread_id);
1971     CRYPTO_set_locking_callback(ssl_locking_callback);
1972
1973     SSL_load_error_strings();
1974     SSL_library_init();
1975
1976     while (!RAND_status()) {
1977         t = time(NULL);
1978         pid = getpid();
1979         RAND_seed((unsigned char *)&t, sizeof(time_t));
1980         RAND_seed((unsigned char *)&pid, sizeof(pid));
1981     }
1982 }
1983
1984 struct list *addsrvconfs(char *value, char **names) {
1985     struct list *conflist;
1986     int n;
1987     struct list_node *entry;
1988     struct clsrvconf *conf = NULL;
1989
1990     if (!names || !*names)
1991         return NULL;
1992
1993     conflist = list_create();
1994     if (!conflist) {
1995         debug(DBG_ERR, "malloc failed");
1996         return NULL;
1997     }
1998
1999     for (n = 0; names[n]; n++) {
2000         for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2001             conf = (struct clsrvconf *)entry->data;
2002             if (!strcasecmp(names[n], conf->name))
2003                 break;
2004         }
2005         if (!entry) {
2006             debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2007             list_destroy(conflist);
2008             return NULL;
2009         }
2010         if (!list_push(conflist, conf)) {
2011             debug(DBG_ERR, "malloc failed");
2012             list_destroy(conflist);
2013             return NULL;
2014         }
2015         debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2016     }
2017     return conflist;
2018 }
2019
2020 void freerealm(struct realm *realm) {
2021     if (!realm)
2022         return;
2023     debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2024     if (--realm->refcount)
2025         return;
2026
2027     free(realm->name);
2028     free(realm->message);
2029     regfree(&realm->regex);
2030     pthread_mutex_destroy(&realm->mutex);
2031     /* if refcount == 0, all subrealms gone */
2032     list_destroy(realm->subrealms);
2033     /* if refcount == 0, all srvconfs gone */
2034     list_destroy(realm->srvconfs);
2035     /* if refcount == 0, all accsrvconfs gone */
2036     list_destroy(realm->accsrvconfs);
2037     freerealm(realm->parent);
2038     free(realm);
2039 }
2040
2041 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2042     int n;
2043     struct realm *realm;
2044     char *s, *regex = NULL;
2045
2046     if (*value == '/') {
2047         /* regexp, remove optional trailing / if present */
2048         if (value[strlen(value) - 1] == '/')
2049             value[strlen(value) - 1] = '\0';
2050     } else {
2051         /* not a regexp, let us make it one */
2052         if (*value == '*' && !value[1])
2053             regex = stringcopy(".*", 0);
2054         else {
2055             for (n = 0, s = value; *s;)
2056                 if (*s++ == '.')
2057                     n++;
2058             regex = malloc(strlen(value) + n + 3);
2059             if (regex) {
2060                 regex[0] = '@';
2061                 for (n = 1, s = value; *s; s++) {
2062                     if (*s == '.')
2063                         regex[n++] = '\\';
2064                     regex[n++] = *s;
2065                 }
2066                 regex[n++] = '$';
2067                 regex[n] = '\0';
2068             }
2069         }
2070         if (!regex) {
2071             debug(DBG_ERR, "malloc failed");
2072             realm = NULL;
2073             goto exit;
2074         }
2075         debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2076     }
2077
2078     realm = malloc(sizeof(struct realm));
2079     if (!realm) {
2080         debug(DBG_ERR, "malloc failed");
2081         goto exit;
2082     }
2083     memset(realm, 0, sizeof(struct realm));
2084
2085     if (pthread_mutex_init(&realm->mutex, NULL)) {
2086         debugerrno(errno, DBG_ERR, "mutex init failed");
2087         free(realm);
2088         realm = NULL;
2089         goto exit;
2090     }
2091
2092     realm->name = stringcopy(value, 0);
2093     if (!realm->name) {
2094         debug(DBG_ERR, "malloc failed");
2095         goto errexit;
2096     }
2097     if (message && strlen(message) > 253) {
2098         debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2099         goto errexit;
2100     }
2101     realm->message = message;
2102     realm->accresp = accresp;
2103
2104     if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2105         debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2106         goto errexit;
2107     }
2108
2109     if (servers && *servers) {
2110         realm->srvconfs = addsrvconfs(value, servers);
2111         if (!realm->srvconfs)
2112             goto errexit;
2113     }
2114
2115     if (accservers && *accservers) {
2116         realm->accsrvconfs = addsrvconfs(value, accservers);
2117         if (!realm->accsrvconfs)
2118             goto errexit;
2119     }
2120
2121     if (!list_push(realmlist, realm)) {
2122         debug(DBG_ERR, "malloc failed");
2123         pthread_mutex_destroy(&realm->mutex);
2124         goto errexit;
2125     }
2126
2127     debug(DBG_DBG, "addrealm: added realm %s", value);
2128     goto exit;
2129
2130 errexit:
2131     while (list_shift(realm->srvconfs));
2132     while (list_shift(realm->accsrvconfs));
2133     freerealm(realm);
2134     realm = NULL;
2135 exit:
2136     free(regex);
2137     if (servers) {
2138         if (realm)
2139             for (n = 0; servers[n]; n++)
2140                 newrealmref(realm);
2141         freegconfmstr(servers);
2142     }
2143     if (accservers) {
2144         if (realm)
2145             for (n = 0; accservers[n]; n++)
2146                 newrealmref(realm);
2147         freegconfmstr(accservers);
2148     }
2149     return newrealmref(realm);
2150 }
2151
2152 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2153     struct list_node *entry;
2154     struct clsrvconf *conf, *srvconf;
2155     struct list *subrealmservers = NULL;
2156     pthread_t clientth;
2157
2158     if (list_first(srvconfs)) {
2159         subrealmservers = list_create();
2160         if (!subrealmservers)
2161             return NULL;
2162     }
2163
2164     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2165         conf = (struct clsrvconf *)entry->data;
2166         if (!conf->servers && conf->dynamiclookupcommand) {
2167             srvconf = malloc(sizeof(struct clsrvconf));
2168             if (!srvconf) {
2169                 debug(DBG_ERR, "malloc failed");
2170                 continue;
2171             }
2172             *srvconf = *conf;
2173             if (addserver(srvconf)) {
2174                 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2175                 srvconf->servers->dynstartup = 1;
2176                 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2177                     debugerrno(errno, DBG_ERR, "pthread_create failed");
2178                     freeserver(srvconf->servers, 1);
2179                     srvconf->servers = NULL;
2180                 } else
2181                     pthread_detach(clientth);
2182             }
2183             conf = srvconf;
2184         }
2185         if (conf->servers) {
2186             if (list_push(subrealmservers, conf))
2187                 newrealmref(realm);
2188             else
2189                 debug(DBG_ERR, "malloc failed");
2190         }
2191     }
2192     return subrealmservers;
2193 }
2194
2195 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2196     struct realm *newrealm = NULL;
2197     char *realmname, *s;
2198
2199     /* create dynamic for the realm (string after last @, exit if nothing after @ */
2200     realmname = strrchr(id, '@');
2201     if (!realmname)
2202         return NULL;
2203     realmname++;
2204     if (!*realmname)
2205         return NULL;
2206     for (s = realmname; *s; s++)
2207         if (*s != '.' && *s != '-' && !isalnum((int)*s))
2208             return NULL;
2209
2210     if (!realm->subrealms)
2211         realm->subrealms = list_create();
2212     if (!realm->subrealms)
2213         return NULL;
2214
2215     newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2216     if (!newrealm) {
2217         list_destroy(realm->subrealms);
2218         realm->subrealms = NULL;
2219         return NULL;
2220     }
2221
2222     newrealm->parent = newrealmref(realm);
2223     /* add server and accserver to newrealm */
2224     newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2225     newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2226     return newrealm;
2227 }
2228
2229 int dynamicconfig(struct server *server) {
2230     int ok, fd[2], status;
2231     pid_t pid;
2232     struct clsrvconf *conf = server->conf;
2233     struct gconffile *cf = NULL;
2234
2235     /* for now we only learn hostname/address */
2236     debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2237
2238     if (pipe(fd) > 0) {
2239         debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2240         goto errexit;
2241     }
2242     pid = fork();
2243     if (pid < 0) {
2244         debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2245         close(fd[0]);
2246         close(fd[1]);
2247         goto errexit;
2248     } else if (pid == 0) {
2249         /* child */
2250         close(fd[0]);
2251         if (fd[1] != STDOUT_FILENO) {
2252             if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2253                 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2254             close(fd[1]);
2255         }
2256         if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2257             debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2258     }
2259
2260     close(fd[1]);
2261     pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2262     ok = getgenericconfig(&cf, NULL,
2263                           "Server", CONF_CBK, confserver_cb, (void *)conf,
2264                           NULL
2265         );
2266     freegconf(&cf);
2267
2268     if (waitpid(pid, &status, 0) < 0) {
2269         debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2270         goto errexit;
2271     }
2272
2273     if (status) {
2274         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2275         goto errexit;
2276     }
2277
2278     if (ok)
2279         return 1;
2280
2281 errexit:
2282     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2283     return 0;
2284 }
2285
2286 /* should accept both names and numeric values, only numeric right now */
2287 uint8_t attrname2val(char *attrname) {
2288     int val = 0;
2289
2290     val = atoi(attrname);
2291     return val > 0 && val < 256 ? val : 0;
2292 }
2293
2294 /* ATTRNAME is on the form vendor[:type].
2295    If only vendor is found, TYPE is set to 256 and 1 is returned.
2296    If type is >= 256, 1 is returned.
2297    Otherwise, 0 is returned.
2298 */
2299 /* should accept both names and numeric values, only numeric right now */
2300 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2301     char *s;
2302
2303     *vendor = atoi(attrname);
2304     s = strchr(attrname, ':');
2305     if (!s) {                   /* Only vendor was found.  */
2306         *type = 256;
2307         return 1;
2308     }
2309     *type = atoi(s + 1);
2310     return *type < 256;
2311 }
2312
2313 /** Extract attributes from string NAMEVAL, create a struct tlv and
2314  * return the tlv.  If VENDOR_FLAG, NAMEVAL is on the form
2315  * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>".  Return
2316  * NULL if fields are missing or if conversion fails.
2317  *
2318  * FIXME: Should accept both names and numeric values, only numeric
2319  * right now */
2320 struct tlv *extractattr(char *nameval, char vendor_flag) {
2321     int len, name = 0;
2322     int vendor = 0;         /* Vendor 0 is reserved, see RFC 1700.  */
2323     char *s, *s2;
2324     struct tlv *a;
2325
2326     s = strchr(nameval, ':');
2327     if (!s)
2328         return NULL;
2329     name = atoi(nameval);
2330
2331     if (vendor_flag) {
2332         s2 = strchr(s + 1, ':');
2333         if (!s2)
2334             return NULL;
2335         vendor = name;
2336         name = atoi(s + 1);
2337         s = s2;
2338     }
2339     len = strlen(s + 1);
2340     if (len > 253)
2341         return NULL;
2342
2343     if (name < 1 || name > 255)
2344         return NULL;
2345     a = malloc(sizeof(struct tlv));
2346     if (!a)
2347         return NULL;
2348
2349     a->v = (uint8_t *)stringcopy(s + 1, 0);
2350     if (!a->v) {
2351         free(a);
2352         return NULL;
2353     }
2354     a->t = name;
2355     a->l = len;
2356
2357     if (vendor_flag)
2358         a = makevendortlv(vendor, a);
2359
2360     return a;
2361 }
2362
2363 /* should accept both names and numeric values, only numeric right now */
2364 struct modattr *extractmodattr(char *nameval) {
2365     int name = 0;
2366     char *s, *t;
2367     struct modattr *m;
2368
2369     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2370         s = nameval + 11;
2371         name = 1;
2372     } else {
2373         s = strchr(nameval, ':');
2374         name = atoi(nameval);
2375         if (!s || name < 1 || name > 255 || s[1] != '/')
2376             return NULL;
2377         s += 2;
2378     }
2379     /* regexp, remove optional trailing / if present */
2380     if (s[strlen(s) - 1] == '/')
2381         s[strlen(s) - 1] = '\0';
2382
2383     t = strchr(s, '/');
2384     if (!t)
2385         return NULL;
2386     *t = '\0';
2387     t++;
2388
2389     m = malloc(sizeof(struct modattr));
2390     if (!m) {
2391         debug(DBG_ERR, "malloc failed");
2392         return NULL;
2393     }
2394     m->t = name;
2395
2396     m->replacement = stringcopy(t, 0);
2397     if (!m->replacement) {
2398         free(m);
2399         debug(DBG_ERR, "malloc failed");
2400         return NULL;
2401     }
2402
2403     m->regex = malloc(sizeof(regex_t));
2404     if (!m->regex) {
2405         free(m->replacement);
2406         free(m);
2407         debug(DBG_ERR, "malloc failed");
2408         return NULL;
2409     }
2410
2411     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2412         free(m->regex);
2413         free(m->replacement);
2414         free(m);
2415         debug(DBG_ERR, "failed to compile regular expression %s", s);
2416         return NULL;
2417     }
2418
2419     return m;
2420 }
2421
2422 struct rewrite *getrewrite(char *alt1, char *alt2) {
2423     struct rewrite *r;
2424
2425     if (alt1)
2426         if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
2427             return r;
2428     if (alt2)
2429         if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
2430             return r;
2431     return NULL;
2432 }
2433
2434 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2435 {
2436     struct rewrite *rewrite = NULL;
2437     int i, n;
2438     uint8_t *rma = NULL;
2439     uint32_t *p, *rmva = NULL;
2440     struct list *adda = NULL, *moda = NULL;
2441     struct tlv *a;
2442     struct modattr *m;
2443
2444     if (rmattrs) {
2445         for (n = 0; rmattrs[n]; n++);
2446         rma = calloc(n + 1, sizeof(uint8_t));
2447         if (!rma)
2448             debugx(1, DBG_ERR, "malloc failed");
2449
2450         for (i = 0; i < n; i++)
2451             if (!(rma[i] = attrname2val(rmattrs[i])))
2452                 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2453         freegconfmstr(rmattrs);
2454         rma[i] = 0;
2455     }
2456
2457     if (rmvattrs) {
2458         for (n = 0; rmvattrs[n]; n++);
2459         rmva = calloc(2 * n + 1, sizeof(uint32_t));
2460         if (!rmva)
2461             debugx(1, DBG_ERR, "malloc failed");
2462
2463         for (p = rmva, i = 0; i < n; i++, p += 2)
2464             if (!vattrname2val(rmvattrs[i], p, p + 1))
2465                 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2466         freegconfmstr(rmvattrs);
2467         *p = 0;
2468     }
2469
2470     if (addattrs) {
2471         adda = list_create();
2472         if (!adda)
2473             debugx(1, DBG_ERR, "malloc failed");
2474         for (i = 0; addattrs[i]; i++) {
2475             a = extractattr(addattrs[i], 0);
2476             if (!a)
2477                 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2478             if (!list_push(adda, a))
2479                 debugx(1, DBG_ERR, "malloc failed");
2480         }
2481         freegconfmstr(addattrs);
2482     }
2483
2484     if (addvattrs) {
2485         if (!adda)
2486             adda = list_create();
2487         if (!adda)
2488             debugx(1, DBG_ERR, "malloc failed");
2489         for (i = 0; addvattrs[i]; i++) {
2490             a = extractattr(addvattrs[i], 1);
2491             if (!a)
2492                 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2493             if (!list_push(adda, a))
2494                 debugx(1, DBG_ERR, "malloc failed");
2495         }
2496         freegconfmstr(addvattrs);
2497     }
2498
2499     if (modattrs) {
2500         moda = list_create();
2501         if (!moda)
2502             debugx(1, DBG_ERR, "malloc failed");
2503         for (i = 0; modattrs[i]; i++) {
2504             m = extractmodattr(modattrs[i]);
2505             if (!m)
2506                 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2507             if (!list_push(moda, m))
2508                 debugx(1, DBG_ERR, "malloc failed");
2509         }
2510         freegconfmstr(modattrs);
2511     }
2512
2513     if (rma || rmva || adda || moda) {
2514         rewrite = malloc(sizeof(struct rewrite));
2515         if (!rewrite)
2516             debugx(1, DBG_ERR, "malloc failed");
2517         rewrite->removeattrs = rma;
2518         rewrite->removevendorattrs = rmva;
2519         rewrite->addattrs = adda;
2520         rewrite->modattrs = moda;
2521     }
2522
2523     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2524         debugx(1, DBG_ERR, "malloc failed");
2525     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2526 }
2527
2528 int setttlattr(struct options *opts, char *defaultattr) {
2529     char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2530
2531     if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2532         (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2533         return 1;
2534     debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2535     return 0;
2536 }
2537
2538 void freeclsrvconf(struct clsrvconf *conf) {
2539     free(conf->name);
2540     if (conf->hostsrc)
2541         freegconfmstr(conf->hostsrc);
2542     free(conf->portsrc);
2543     free(conf->secret);
2544     free(conf->tls);
2545     free(conf->matchcertattr);
2546     if (conf->certcnregex)
2547         regfree(conf->certcnregex);
2548     if (conf->certuriregex)
2549         regfree(conf->certuriregex);
2550     free(conf->confrewritein);
2551     free(conf->confrewriteout);
2552     if (conf->rewriteusername) {
2553         if (conf->rewriteusername->regex)
2554             regfree(conf->rewriteusername->regex);
2555         free(conf->rewriteusername->replacement);
2556         free(conf->rewriteusername);
2557     }
2558     free(conf->dynamiclookupcommand);
2559     free(conf->rewritein);
2560     free(conf->rewriteout);
2561     if (conf->hostports)
2562         freehostports(conf->hostports);
2563     if (conf->lock) {
2564         pthread_mutex_destroy(conf->lock);
2565         free(conf->lock);
2566     }
2567     /* not touching ssl_ctx, clients and servers */
2568     free(conf);
2569 }
2570
2571 int mergeconfstring(char **dst, char **src) {
2572     char *t;
2573
2574     if (*src) {
2575         *dst = *src;
2576         *src = NULL;
2577         return 1;
2578     }
2579     if (*dst) {
2580         t = stringcopy(*dst, 0);
2581         if (!t) {
2582             debug(DBG_ERR, "malloc failed");
2583             return 0;
2584         }
2585         *dst = t;
2586     }
2587     return 1;
2588 }
2589
2590 char **mstringcopy(char **in) {
2591     char **out;
2592     int n;
2593
2594     if (!in)
2595         return NULL;
2596
2597     for (n = 0; in[n]; n++);
2598     out = malloc((n + 1) * sizeof(char *));
2599     if (!out)
2600         return NULL;
2601     for (n = 0; in[n]; n++) {
2602         out[n] = stringcopy(in[n], 0);
2603         if (!out[n]) {
2604             freegconfmstr(out);
2605             return NULL;
2606         }
2607     }
2608     out[n] = NULL;
2609     return out;
2610 }
2611
2612 int mergeconfmstring(char ***dst, char ***src) {
2613     char **t;
2614
2615     if (*src) {
2616         *dst = *src;
2617         *src = NULL;
2618         return 1;
2619     }
2620     if (*dst) {
2621         t = mstringcopy(*dst);
2622         if (!t) {
2623             debug(DBG_ERR, "malloc failed");
2624             return 0;
2625         }
2626         *dst = t;
2627     }
2628     return 1;
2629 }
2630
2631 /* assumes dst is a shallow copy */
2632 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2633     if (!mergeconfstring(&dst->name, &src->name) ||
2634         !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2635         !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2636         !mergeconfstring(&dst->secret, &src->secret) ||
2637         !mergeconfstring(&dst->tls, &src->tls) ||
2638         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2639         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2640         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2641         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2642         return 0;
2643     if (src->pdef)
2644         dst->pdef = src->pdef;
2645     dst->statusserver = src->statusserver;
2646     dst->certnamecheck = src->certnamecheck;
2647     if (src->retryinterval != 255)
2648         dst->retryinterval = src->retryinterval;
2649     if (src->retrycount != 255)
2650         dst->retrycount = src->retrycount;
2651     return 1;
2652 }
2653
2654 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2655     struct clsrvconf *conf;
2656     char *conftype = NULL, *rewriteinalias = NULL;
2657     long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2658
2659     debug(DBG_DBG, "confclient_cb called for %s", block);
2660
2661     conf = malloc(sizeof(struct clsrvconf));
2662     if (!conf)
2663         debugx(1, DBG_ERR, "malloc failed");
2664     memset(conf, 0, sizeof(struct clsrvconf));
2665     conf->certnamecheck = 1;
2666
2667     if (!getgenericconfig(
2668             cf, block,
2669             "type", CONF_STR, &conftype,
2670             "host", CONF_MSTR, &conf->hostsrc,
2671             "secret", CONF_STR, &conf->secret,
2672 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2673             "tls", CONF_STR, &conf->tls,
2674             "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2675             "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2676 #endif
2677             "DuplicateInterval", CONF_LINT, &dupinterval,
2678             "addTTL", CONF_LINT, &addttl,
2679             "rewrite", CONF_STR, &rewriteinalias,
2680             "rewriteIn", CONF_STR, &conf->confrewritein,
2681             "rewriteOut", CONF_STR, &conf->confrewriteout,
2682             "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2683             "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2684             NULL
2685             ))
2686         debugx(1, DBG_ERR, "configuration error");
2687
2688     conf->name = stringcopy(val, 0);
2689     if (conf->name && !conf->hostsrc) {
2690         conf->hostsrc = malloc(2 * sizeof(char *));
2691         if (conf->hostsrc) {
2692             conf->hostsrc[0] = stringcopy(val, 0);
2693             conf->hostsrc[1] = NULL;
2694         }
2695     }
2696     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2697         debugx(1, DBG_ERR, "malloc failed");
2698
2699     if (!conftype)
2700         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2701     conf->type = protoname2int(conftype);
2702     if (conf->type == 255)
2703         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2704     free(conftype);
2705     conf->pdef = protodefs[conf->type];
2706
2707 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2708     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2709         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2710         if (!conf->tlsconf)
2711             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2712         if (conf->matchcertattr && !addmatchcertattr(conf))
2713             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2714     }
2715 #endif
2716
2717     if (dupinterval != LONG_MIN) {
2718         if (dupinterval < 0 || dupinterval > 255)
2719             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2720         conf->dupinterval = (uint8_t)dupinterval;
2721     } else
2722         conf->dupinterval = conf->pdef->duplicateintervaldefault;
2723
2724     if (addttl != LONG_MIN) {
2725         if (addttl < 1 || addttl > 255)
2726             debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2727         conf->addttl = (uint8_t)addttl;
2728     }
2729
2730     if (!conf->confrewritein)
2731         conf->confrewritein = rewriteinalias;
2732     else
2733         free(rewriteinalias);
2734     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2735     if (conf->confrewriteout)
2736         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2737
2738     if (conf->confrewriteusername) {
2739         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2740         if (!conf->rewriteusername)
2741             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2742     }
2743
2744     if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2745         !resolvehostports(conf->hostports, conf->pdef->socktype))
2746         debugx(1, DBG_ERR, "resolve failed, exiting");
2747
2748     if (!conf->secret) {
2749         if (!conf->pdef->secretdefault)
2750             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2751         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2752         if (!conf->secret)
2753             debugx(1, DBG_ERR, "malloc failed");
2754     }
2755
2756     conf->lock = malloc(sizeof(pthread_mutex_t));
2757     if (!conf->lock)
2758         debugx(1, DBG_ERR, "malloc failed");
2759
2760     pthread_mutex_init(conf->lock, NULL);
2761     if (!list_push(clconfs, conf))
2762         debugx(1, DBG_ERR, "malloc failed");
2763     return 1;
2764 }
2765
2766 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2767 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2768     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2769         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2770         if (!conf->tlsconf) {
2771             debug(DBG_ERR, "error in block %s, no tls context defined", block);
2772             return 0;
2773         }
2774         if (conf->matchcertattr && !addmatchcertattr(conf)) {
2775             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2776             return 0;
2777         }
2778     }
2779 #endif
2780
2781     if (!conf->portsrc) {
2782         conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2783         if (!conf->portsrc) {
2784             debug(DBG_ERR, "malloc failed");
2785             return 0;
2786         }
2787     }
2788
2789     if (conf->retryinterval == 255)
2790         conf->retryinterval = conf->pdef->retryintervaldefault;
2791     if (conf->retrycount == 255)
2792         conf->retrycount = conf->pdef->retrycountdefault;
2793
2794     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2795     if (conf->confrewriteout)
2796         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2797
2798     if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2799         debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2800         return 0;
2801     }
2802
2803     if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2804         debug(DBG_ERR, "resolve failed, exiting");
2805         return 0;
2806     }
2807     return 1;
2808 }
2809
2810 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2811     struct clsrvconf *conf, *resconf;
2812     char *conftype = NULL, *rewriteinalias = NULL;
2813     long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2814
2815     debug(DBG_DBG, "confserver_cb called for %s", block);
2816
2817     conf = malloc(sizeof(struct clsrvconf));
2818     if (!conf) {
2819         debug(DBG_ERR, "malloc failed");
2820         return 0;
2821     }
2822     memset(conf, 0, sizeof(struct clsrvconf));
2823     conf->loopprevention = UCHAR_MAX; /* Uninitialized.  */
2824     resconf = (struct clsrvconf *)arg;
2825     if (resconf) {
2826         conf->statusserver = resconf->statusserver;
2827         conf->certnamecheck = resconf->certnamecheck;
2828     } else
2829         conf->certnamecheck = 1;
2830
2831     if (!getgenericconfig(cf, block,
2832                           "type", CONF_STR, &conftype,
2833                           "host", CONF_MSTR, &conf->hostsrc,
2834                           "port", CONF_STR, &conf->portsrc,
2835                           "secret", CONF_STR, &conf->secret,
2836 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2837                           "tls", CONF_STR, &conf->tls,
2838                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2839                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2840 #endif
2841                           "addTTL", CONF_LINT, &addttl,
2842                           "rewrite", CONF_STR, &rewriteinalias,
2843                           "rewriteIn", CONF_STR, &conf->confrewritein,
2844                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2845                           "StatusServer", CONF_BLN, &conf->statusserver,
2846                           "RetryInterval", CONF_LINT, &retryinterval,
2847                           "RetryCount", CONF_LINT, &retrycount,
2848                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2849                           "LoopPrevention", CONF_BLN, &conf->loopprevention,
2850                           NULL
2851             )) {
2852         debug(DBG_ERR, "configuration error");
2853         goto errexit;
2854     }
2855
2856     conf->name = stringcopy(val, 0);
2857     if (conf->name && !conf->hostsrc) {
2858         conf->hostsrc = malloc(2 * sizeof(char *));
2859         if (conf->hostsrc) {
2860             conf->hostsrc[0] = stringcopy(val, 0);
2861             conf->hostsrc[1] = NULL;
2862         }
2863     }
2864     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2865         debug(DBG_ERR, "malloc failed");
2866         goto errexit;
2867     }
2868
2869     if (!conftype) {
2870         debug(DBG_ERR, "error in block %s, option type missing", block);
2871         goto errexit;
2872     }
2873     conf->type = protoname2int(conftype);
2874     if (conf->type == 255) {
2875         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2876         goto errexit;
2877     }
2878     free(conftype);
2879     conftype = NULL;
2880
2881     conf->pdef = protodefs[conf->type];
2882
2883     if (!conf->confrewritein)
2884         conf->confrewritein = rewriteinalias;
2885     else
2886         free(rewriteinalias);
2887     rewriteinalias = NULL;
2888
2889     if (retryinterval != LONG_MIN) {
2890         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2891             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2892             goto errexit;
2893         }
2894         conf->retryinterval = (uint8_t)retryinterval;
2895     } else
2896         conf->retryinterval = 255;
2897
2898     if (retrycount != LONG_MIN) {
2899         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2900             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2901             goto errexit;
2902         }
2903         conf->retrycount = (uint8_t)retrycount;
2904     } else
2905         conf->retrycount = 255;
2906
2907     if (addttl != LONG_MIN) {
2908         if (addttl < 1 || addttl > 255) {
2909             debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2910             goto errexit;
2911         }
2912         conf->addttl = (uint8_t)addttl;
2913     }
2914
2915     if (resconf) {
2916         if (!mergesrvconf(resconf, conf))
2917             goto errexit;
2918         free(conf);
2919         conf = resconf;
2920         if (conf->dynamiclookupcommand) {
2921             free(conf->dynamiclookupcommand);
2922             conf->dynamiclookupcommand = NULL;
2923         }
2924     }
2925
2926     if (resconf || !conf->dynamiclookupcommand) {
2927         if (!compileserverconfig(conf, block))
2928             goto errexit;
2929     }
2930
2931     if (!conf->secret) {
2932         if (!conf->pdef->secretdefault) {
2933             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2934             return 0;
2935         }
2936         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2937         if (!conf->secret) {
2938             debug(DBG_ERR, "malloc failed");
2939             return 0;
2940         }
2941     }
2942
2943     if (resconf)
2944         return 1;
2945
2946     if (!list_push(srvconfs, conf)) {
2947         debug(DBG_ERR, "malloc failed");
2948         goto errexit;
2949     }
2950     return 1;
2951
2952 errexit:
2953     free(conftype);
2954     free(rewriteinalias);
2955     freeclsrvconf(conf);
2956     return 0;
2957 }
2958
2959 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2960     char **servers = NULL, **accservers = NULL, *msg = NULL;
2961     uint8_t accresp = 0;
2962
2963     debug(DBG_DBG, "confrealm_cb called for %s", block);
2964
2965     if (!getgenericconfig(cf, block,
2966                           "server", CONF_MSTR, &servers,
2967                           "accountingServer", CONF_MSTR, &accservers,
2968                           "ReplyMessage", CONF_STR, &msg,
2969                           "AccountingResponse", CONF_BLN, &accresp,
2970                           NULL
2971             ))
2972         debugx(1, DBG_ERR, "configuration error");
2973
2974     addrealm(realms, val, servers, accservers, msg, accresp);
2975     return 1;
2976 }
2977
2978 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2979     char **rmattrs = NULL, **rmvattrs = NULL;
2980     char **addattrs = NULL, **addvattrs = NULL;
2981     char **modattrs = NULL;
2982
2983     debug(DBG_DBG, "confrewrite_cb called for %s", block);
2984
2985     if (!getgenericconfig(cf, block,
2986                           "removeAttribute", CONF_MSTR, &rmattrs,
2987                           "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2988                           "addAttribute", CONF_MSTR, &addattrs,
2989                           "addVendorAttribute", CONF_MSTR, &addvattrs,
2990                           "modifyAttribute", CONF_MSTR, &modattrs,
2991                           NULL
2992             ))
2993         debugx(1, DBG_ERR, "configuration error");
2994     addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2995     return 1;
2996 }
2997
2998 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2999     struct commonprotoopts *protoopts;
3000
3001     protoopts = malloc(sizeof(struct commonprotoopts));
3002     if (!protoopts)
3003         return 0;
3004     memset(protoopts, 0, sizeof(struct commonprotoopts));
3005     protoopts->listenargs = listenargs;
3006     protoopts->sourcearg = sourcearg;
3007     protodefs[type]->setprotoopts(protoopts);
3008     return 1;
3009 }
3010
3011 void getmainconfig(const char *configfile) {
3012     long int addttl = LONG_MIN, loglevel = LONG_MIN;
3013     struct gconffile *cfs;
3014     char **listenargs[RAD_PROTOCOUNT];
3015     char *sourcearg[RAD_PROTOCOUNT];
3016     uint8_t *fticks_reporting_str = NULL;
3017     uint8_t *fticks_mac_str = NULL;
3018     uint8_t *fticks_key_str = NULL;
3019     int i;
3020
3021     cfs = openconfigfile(configfile);
3022     memset(&options, 0, sizeof(options));
3023     memset(&listenargs, 0, sizeof(listenargs));
3024     memset(&sourcearg, 0, sizeof(sourcearg));
3025
3026     clconfs = list_create();
3027     if (!clconfs)
3028         debugx(1, DBG_ERR, "malloc failed");
3029
3030     srvconfs = list_create();
3031     if (!srvconfs)
3032         debugx(1, DBG_ERR, "malloc failed");
3033
3034     realms = list_create();
3035     if (!realms)
3036         debugx(1, DBG_ERR, "malloc failed");
3037
3038     rewriteconfs = hash_create();
3039     if (!rewriteconfs)
3040         debugx(1, DBG_ERR, "malloc failed");
3041
3042     if (!getgenericconfig(
3043             &cfs, NULL,
3044 #ifdef RADPROT_UDP
3045             "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3046             "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3047 #endif
3048 #ifdef RADPROT_TCP
3049             "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3050             "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3051 #endif
3052 #ifdef RADPROT_TLS
3053             "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3054             "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3055 #endif
3056 #ifdef RADPROT_DTLS
3057             "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3058             "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3059 #endif
3060             "TTLAttribute", CONF_STR, &options.ttlattr,
3061             "addTTL", CONF_LINT, &addttl,
3062             "LogLevel", CONF_LINT, &loglevel,
3063             "LogDestination", CONF_STR, &options.logdestination,
3064             "LoopPrevention", CONF_BLN, &options.loopprevention,
3065             "Client", CONF_CBK, confclient_cb, NULL,
3066             "Server", CONF_CBK, confserver_cb, NULL,
3067             "Realm", CONF_CBK, confrealm_cb, NULL,
3068 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3069             "TLS", CONF_CBK, conftls_cb, NULL,
3070 #endif
3071             "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3072             "FTicksReporting", CONF_STR, &fticks_reporting_str,
3073             "FTicksMAC", CONF_STR, &fticks_mac_str,
3074             "FTicksKey", CONF_STR, &fticks_key_str,
3075             NULL
3076             ))
3077         debugx(1, DBG_ERR, "configuration error");
3078
3079     if (loglevel != LONG_MIN) {
3080         if (loglevel < 1 || loglevel > 5)
3081             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3082         options.loglevel = (uint8_t)loglevel;
3083     }
3084     if (addttl != LONG_MIN) {
3085         if (addttl < 1 || addttl > 255)
3086             debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3087         options.addttl = (uint8_t)addttl;
3088     }
3089     if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3090         debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3091
3092     fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3093                      &fticks_key_str);
3094
3095     for (i = 0; i < RAD_PROTOCOUNT; i++)
3096         if (listenargs[i] || sourcearg[i])
3097             setprotoopts(i, listenargs[i], sourcearg[i]);
3098 }
3099
3100 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3101     int c;
3102
3103     while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3104         switch (c) {
3105         case 'c':
3106             *configfile = optarg;
3107             break;
3108         case 'd':
3109             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3110                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3111             *loglevel = *optarg - '0';
3112             break;
3113         case 'f':
3114             *foreground = 1;
3115             break;
3116         case 'i':
3117             *pidfile = optarg;
3118             break;
3119         case 'p':
3120             *pretend = 1;
3121             break;
3122         case 'v':
3123             debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3124             debug(DBG_ERR, "This binary was built with support for the following transports:");
3125 #ifdef RADPROT_UDP
3126             debug(DBG_ERR, "  UDP");
3127 #endif
3128 #ifdef RADPROT_TCP
3129             debug(DBG_ERR, "  TCP");
3130 #endif
3131 #ifdef RADPROT_TLS
3132             debug(DBG_ERR, "  TLS");
3133 #endif
3134 #ifdef RADPROT_DTLS
3135             debug(DBG_ERR, "  DTLS");
3136 #endif
3137             exit(0);
3138         default:
3139             goto usage;
3140         }
3141     }
3142     if (!(argc - optind))
3143         return;
3144
3145 usage:
3146     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3147 }
3148
3149 #ifdef SYS_SOLARIS9
3150 int daemon(int a, int b) {
3151     int i;
3152
3153     if (fork())
3154         exit(0);
3155
3156     setsid();
3157
3158     for (i = 0; i < 3; i++) {
3159         close(i);
3160         open("/dev/null", O_RDWR);
3161     }
3162     return 1;
3163 }
3164 #endif
3165
3166 void *sighandler(void *arg) {
3167     sigset_t sigset;
3168     int sig;
3169
3170     for(;;) {
3171         sigemptyset(&sigset);
3172         sigaddset(&sigset, SIGHUP);
3173         sigaddset(&sigset, SIGPIPE);
3174         sigwait(&sigset, &sig);
3175         switch (sig) {
3176         case 0:
3177             /* completely ignoring this */
3178             break;
3179         case SIGHUP:
3180             debug(DBG_INFO, "sighandler: got SIGHUP");
3181             debug_reopen_log();
3182             break;
3183         case SIGPIPE:
3184             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3185             break;
3186         default:
3187             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3188         }
3189     }
3190 }
3191
3192 int createpidfile(const char *pidfile) {
3193     int r = 0;
3194     FILE *f = fopen(pidfile, "w");
3195     if (f)
3196         r = fprintf(f, "%ld\n", (long) getpid());
3197     return f && !fclose(f) && r >= 0;
3198 }
3199
3200 int main(int argc, char **argv) {
3201     pthread_t sigth;
3202     sigset_t sigset;
3203     struct list_node *entry;
3204     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3205     char *configfile = NULL, *pidfile = NULL;
3206     struct clsrvconf *srvconf;
3207     int i;
3208
3209     debug_init("radsecproxy");
3210     debug_set_level(DEBUG_LEVEL);
3211
3212     for (i = 0; i < RAD_PROTOCOUNT; i++)
3213         protodefs[i] = protoinits[i](i);
3214
3215     /* needed even if no TLS/DTLS transport */
3216     sslinit();
3217
3218     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3219     if (loglevel)
3220         debug_set_level(loglevel);
3221     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3222     if (loglevel)
3223         options.loglevel = loglevel;
3224     else if (options.loglevel)
3225         debug_set_level(options.loglevel);
3226     if (!foreground)
3227         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3228     free(options.logdestination);
3229
3230     if (!list_first(clconfs))
3231         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3232     if (!list_first(realms))
3233         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3234
3235     if (pretend)
3236         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3237
3238     if (!foreground && (daemon(0, 0) < 0))
3239         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3240
3241     debug_timestamp_on();
3242     debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3243     if (pidfile && !createpidfile(pidfile))
3244         debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3245
3246     sigemptyset(&sigset);
3247     /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3248     sigaddset(&sigset, SIGHUP);
3249     sigaddset(&sigset, SIGPIPE);
3250     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3251     pthread_create(&sigth, NULL, sighandler, NULL);
3252
3253     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3254         srvconf = (struct clsrvconf *)entry->data;
3255         if (srvconf->dynamiclookupcommand)
3256             continue;
3257         if (!addserver(srvconf))
3258             debugx(1, DBG_ERR, "failed to add server");
3259         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3260                            (void *)(srvconf->servers)))
3261             debugx(1, DBG_ERR, "pthread_create failed");
3262     }
3263
3264     for (i = 0; i < RAD_PROTOCOUNT; i++) {
3265         if (!protodefs[i])
3266             continue;
3267         if (protodefs[i]->initextra)
3268             protodefs[i]->initextra();
3269         if (find_clconf_type(i, NULL))
3270             createlisteners(i);
3271     }
3272
3273     /* just hang around doing nothing, anything to do here? */
3274     for (;;)
3275         sleep(1000);
3276 }
3277
3278 /* Local Variables: */
3279 /* c-file-style: "stroustrup" */
3280 /* End: */