Prepare for building tests.
[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 "hash.h"
73 #include "util.h"
74 #include "hostport.h"
75 #include "radsecproxy.h"
76 #include "udp.h"
77 #include "tcp.h"
78 #include "tls.h"
79 #include "dtls.h"
80 #include "fticks.h"
81
82 static struct options options;
83 static struct list *clconfs, *srvconfs;
84 static struct list *realms;
85 static struct hash *rewriteconfs;
86
87 static pthread_mutex_t *ssl_locks = NULL;
88 static long *ssl_lock_count;
89 extern int optind;
90 extern char *optarg;
91 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
92
93 /* minimum required declarations to avoid reordering code */
94 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
95 int dynamicconfig(struct server *server);
96 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
97 void freerealm(struct realm *realm);
98 void freeclsrvconf(struct clsrvconf *conf);
99 void freerq(struct request *rq);
100 void freerqoutdata(struct rqout *rqout);
101 void rmclientrq(struct request *rq, uint8_t id);
102
103 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
104
105 uint8_t protoname2int(const char *name) {
106     uint8_t i;
107
108     for (i = 0; i < RAD_PROTOCOUNT; i++)
109         if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
110             return i;
111     return 255;
112 }
113
114 /* callbacks for making OpenSSL thread safe */
115 unsigned long ssl_thread_id() {
116     return (unsigned long)pthread_self();
117 }
118
119 void ssl_locking_callback(int mode, int type, const char *file, int line) {
120     if (mode & CRYPTO_LOCK) {
121         pthread_mutex_lock(&ssl_locks[type]);
122         ssl_lock_count[type]++;
123     } else
124         pthread_mutex_unlock(&ssl_locks[type]);
125 }
126
127 /* returns 1 if the len first bits are equal, else 0 */
128 int prefixmatch(void *a1, void *a2, uint8_t len) {
129     static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
130     uint8_t r, l = len / 8;
131     if (l && memcmp(a1, a2, l))
132         return 0;
133     r = len % 8;
134     if (!r)
135         return 1;
136     return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
137 }
138
139 /* returns next config with matching address, or NULL */
140 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
141     struct list_node *entry;
142     struct clsrvconf *conf;
143
144     for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
145         conf = (struct clsrvconf *)entry->data;
146         if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
147             if (cur)
148                 *cur = entry;
149             return conf;
150         }
151     }
152     return NULL;
153 }
154
155 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
156     return find_conf(type, addr, clconfs, cur, 0);
157 }
158
159 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
160     return find_conf(type, addr, srvconfs, cur, 1);
161 }
162
163 /* returns next config of given type, or NULL */
164 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
165     struct list_node *entry;
166     struct clsrvconf *conf;
167
168     for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
169         conf = (struct clsrvconf *)entry->data;
170         if (conf->type == type) {
171             if (cur)
172                 *cur = entry;
173             return conf;
174         }
175     }
176     return NULL;
177 }
178
179 struct gqueue *newqueue() {
180     struct gqueue *q;
181
182     q = malloc(sizeof(struct gqueue));
183     if (!q)
184         debugx(1, DBG_ERR, "malloc failed");
185     q->entries = list_create();
186     if (!q->entries)
187         debugx(1, DBG_ERR, "malloc failed");
188     pthread_mutex_init(&q->mutex, NULL);
189     pthread_cond_init(&q->cond, NULL);
190     return q;
191 }
192
193 void removequeue(struct gqueue *q) {
194     struct list_node *entry;
195
196     if (!q)
197         return;
198     pthread_mutex_lock(&q->mutex);
199     for (entry = list_first(q->entries); entry; entry = list_next(entry))
200         freerq((struct request *)entry);
201     list_destroy(q->entries);
202     pthread_cond_destroy(&q->cond);
203     pthread_mutex_unlock(&q->mutex);
204     pthread_mutex_destroy(&q->mutex);
205     free(q);
206 }
207
208 void freebios(struct gqueue *q) {
209     BIO *bio;
210
211     pthread_mutex_lock(&q->mutex);
212     while ((bio = (BIO *)list_shift(q->entries)))
213         BIO_free(bio);
214     pthread_mutex_unlock(&q->mutex);
215     removequeue(q);
216 }
217
218 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
219     struct client *new = malloc(sizeof(struct client));
220
221     if (!new) {
222         debug(DBG_ERR, "malloc failed");
223         return NULL;
224     }
225
226     if (lock)
227         pthread_mutex_lock(conf->lock);
228     if (!conf->clients) {
229         conf->clients = list_create();
230         if (!conf->clients) {
231             if (lock)
232                 pthread_mutex_unlock(conf->lock);
233             debug(DBG_ERR, "malloc failed");
234             return NULL;
235         }
236     }
237
238     memset(new, 0, sizeof(struct client));
239     new->conf = conf;
240     if (conf->pdef->addclient)
241         conf->pdef->addclient(new);
242     else
243         new->replyq = newqueue();
244     list_push(conf->clients, new);
245     if (lock)
246         pthread_mutex_unlock(conf->lock);
247     return new;
248 }
249
250 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
251     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
252
253     if (wantlock)
254         pthread_mutex_lock(&lock);
255     else
256         pthread_mutex_unlock(&lock);
257 }
258
259 void removeclientrqs(struct client *client) {
260     struct request *rq;
261     struct rqout *rqout;
262     int i;
263
264     removeclientrqs_sendrq_freeserver_lock(1);
265     for (i = 0; i < MAX_REQUESTS; i++) {
266         rq = client->rqs[i];
267         if (!rq)
268             continue;
269         if (rq->to) {
270             rqout = rq->to->requests + rq->newid;
271             pthread_mutex_lock(rqout->lock);
272             if (rqout->rq == rq) /* still pointing to our request */
273                 freerqoutdata(rqout);
274             pthread_mutex_unlock(rqout->lock);
275         }
276         freerq(rq);
277     }
278     removeclientrqs_sendrq_freeserver_lock(0);
279 }
280
281 void removelockedclient(struct client *client) {
282     struct clsrvconf *conf;
283
284     conf = client->conf;
285     if (conf->clients) {
286         removeclientrqs(client);
287         removequeue(client->replyq);
288         list_removedata(conf->clients, client);
289         free(client->addr);
290         free(client);
291     }
292 }
293
294 void removeclient(struct client *client) {
295     struct clsrvconf *conf;
296
297     if (!client)
298         return;
299
300     conf = client->conf;
301     pthread_mutex_lock(conf->lock);
302     removelockedclient(client);
303     pthread_mutex_unlock(conf->lock);
304 }
305
306 void freeserver(struct server *server, uint8_t destroymutex) {
307     struct rqout *rqout, *end;
308
309     if (!server)
310         return;
311
312     removeclientrqs_sendrq_freeserver_lock(1);
313     if (server->requests) {
314         rqout = server->requests;
315         for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
316             if (rqout->rq)
317                 rqout->rq->to = NULL;
318             freerqoutdata(rqout);
319             pthread_mutex_destroy(rqout->lock);
320             free(rqout->lock);
321         }
322         free(server->requests);
323     }
324     if (server->rbios)
325         freebios(server->rbios);
326     free(server->dynamiclookuparg);
327     if (server->ssl)
328         SSL_free(server->ssl);
329     if (destroymutex) {
330         pthread_mutex_destroy(&server->lock);
331         pthread_cond_destroy(&server->newrq_cond);
332         pthread_mutex_destroy(&server->newrq_mutex);
333     }
334     removeclientrqs_sendrq_freeserver_lock(0);
335     free(server);
336 }
337
338 int addserver(struct clsrvconf *conf) {
339     int i;
340
341     if (conf->servers) {
342         debug(DBG_ERR, "addserver: currently works with just one server per conf");
343         return 0;
344     }
345     conf->servers = malloc(sizeof(struct server));
346     if (!conf->servers) {
347         debug(DBG_ERR, "malloc failed");
348         return 0;
349     }
350     memset(conf->servers, 0, sizeof(struct server));
351     conf->servers->conf = conf;
352
353 #ifdef RADPROT_DTLS
354     if (conf->type == RAD_DTLS)
355         conf->servers->rbios = newqueue();
356 #endif
357     conf->pdef->setsrcres();
358
359     conf->servers->sock = -1;
360     if (conf->pdef->addserverextra)
361         conf->pdef->addserverextra(conf);
362
363     conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
364     if (!conf->servers->requests) {
365         debug(DBG_ERR, "malloc failed");
366         goto errexit;
367     }
368     for (i = 0; i < MAX_REQUESTS; i++) {
369         conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
370         if (!conf->servers->requests[i].lock) {
371             debug(DBG_ERR, "malloc failed");
372             goto errexit;
373         }
374         if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
375             debugerrno(errno, DBG_ERR, "mutex init failed");
376             free(conf->servers->requests[i].lock);
377             conf->servers->requests[i].lock = NULL;
378             goto errexit;
379         }
380     }
381     if (pthread_mutex_init(&conf->servers->lock, NULL)) {
382         debugerrno(errno, DBG_ERR, "mutex init failed");
383         goto errexit;
384     }
385     conf->servers->newrq = 0;
386     if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
387         debugerrno(errno, DBG_ERR, "mutex init failed");
388         pthread_mutex_destroy(&conf->servers->lock);
389         goto errexit;
390     }
391     if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
392         debugerrno(errno, DBG_ERR, "mutex init failed");
393         pthread_mutex_destroy(&conf->servers->newrq_mutex);
394         pthread_mutex_destroy(&conf->servers->lock);
395         goto errexit;
396     }
397
398     return 1;
399
400 errexit:
401     freeserver(conf->servers, 0);
402     conf->servers = NULL;
403     return 0;
404 }
405
406 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
407     while (length > 1) {
408         if (ATTRTYPE(attrs) == type)
409             return attrs;
410         length -= ATTRLEN(attrs);
411         attrs += ATTRLEN(attrs);
412     }
413     return NULL;
414 }
415
416 struct request *newrqref(struct request *rq) {
417     if (rq)
418         rq->refcount++;
419     return rq;
420 }
421
422 void freerq(struct request *rq) {
423     if (!rq)
424         return;
425     debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
426     if (--rq->refcount)
427         return;
428     if (rq->origusername)
429         free(rq->origusername);
430     if (rq->buf)
431         free(rq->buf);
432     if (rq->replybuf)
433         free(rq->replybuf);
434     if (rq->msg)
435         radmsg_free(rq->msg);
436     free(rq);
437 }
438
439 void freerqoutdata(struct rqout *rqout) {
440     if (!rqout)
441         return;
442     if (rqout->rq) {
443         if (rqout->rq->buf) {
444             free(rqout->rq->buf);
445             rqout->rq->buf = NULL;
446         }
447         freerq(rqout->rq);
448         rqout->rq = NULL;
449     }
450     rqout->tries = 0;
451     memset(&rqout->expiry, 0, sizeof(struct timeval));
452 }
453
454 void sendrq(struct request *rq) {
455     int i, start;
456     struct server *to;
457
458     removeclientrqs_sendrq_freeserver_lock(1);
459     to = rq->to;
460     if (!to)
461         goto errexit;
462
463     start = to->conf->statusserver ? 1 : 0;
464     pthread_mutex_lock(&to->newrq_mutex);
465     if (start && rq->msg->code == RAD_Status_Server) {
466         pthread_mutex_lock(to->requests[0].lock);
467         if (to->requests[0].rq) {
468             pthread_mutex_unlock(to->requests[0].lock);
469             debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
470             goto errexit;
471         }
472         i = 0;
473     } else {
474         if (!to->nextid)
475             to->nextid = start;
476         /* might simplify if only try nextid, might be ok */
477         for (i = to->nextid; i < MAX_REQUESTS; i++) {
478             if (!to->requests[i].rq) {
479                 pthread_mutex_lock(to->requests[i].lock);
480                 if (!to->requests[i].rq)
481                     break;
482                 pthread_mutex_unlock(to->requests[i].lock);
483             }
484         }
485         if (i == MAX_REQUESTS) {
486             for (i = start; i < to->nextid; i++) {
487                 if (!to->requests[i].rq) {
488                     pthread_mutex_lock(to->requests[i].lock);
489                     if (!to->requests[i].rq)
490                         break;
491                     pthread_mutex_unlock(to->requests[i].lock);
492                 }
493             }
494             if (i == to->nextid) {
495                 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
496                 goto errexit;
497             }
498         }
499     }
500     rq->newid = (uint8_t)i;
501     rq->msg->id = (uint8_t)i;
502     rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
503     if (!rq->buf) {
504         pthread_mutex_unlock(to->requests[i].lock);
505         debug(DBG_ERR, "sendrq: radmsg2buf failed");
506         goto errexit;
507     }
508
509     debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
510     to->requests[i].rq = rq;
511     pthread_mutex_unlock(to->requests[i].lock);
512     if (i >= start) /* i is not reserved for statusserver */
513         to->nextid = i + 1;
514
515     if (!to->newrq) {
516         to->newrq = 1;
517         debug(DBG_DBG, "sendrq: signalling client writer");
518         pthread_cond_signal(&to->newrq_cond);
519     }
520
521     pthread_mutex_unlock(&to->newrq_mutex);
522     removeclientrqs_sendrq_freeserver_lock(0);
523     return;
524
525 errexit:
526     if (rq->from)
527         rmclientrq(rq, rq->msg->id);
528     freerq(rq);
529     pthread_mutex_unlock(&to->newrq_mutex);
530     removeclientrqs_sendrq_freeserver_lock(0);
531 }
532
533 void sendreply(struct request *rq) {
534     uint8_t first;
535     struct client *to = rq->from;
536
537     if (!rq->replybuf)
538         rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
539     radmsg_free(rq->msg);
540     rq->msg = NULL;
541     if (!rq->replybuf) {
542         freerq(rq);
543         debug(DBG_ERR, "sendreply: radmsg2buf failed");
544         return;
545     }
546
547     pthread_mutex_lock(&to->replyq->mutex);
548     first = list_first(to->replyq->entries) == NULL;
549
550     if (!list_push(to->replyq->entries, rq)) {
551         pthread_mutex_unlock(&to->replyq->mutex);
552         freerq(rq);
553         debug(DBG_ERR, "sendreply: malloc failed");
554         return;
555     }
556
557     if (first) {
558         debug(DBG_DBG, "signalling server writer");
559         pthread_cond_signal(&to->replyq->cond);
560     }
561     pthread_mutex_unlock(&to->replyq->mutex);
562 }
563
564 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
565     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
566     static unsigned char first = 1;
567     static EVP_MD_CTX mdctx;
568     unsigned char hash[EVP_MAX_MD_SIZE], *input;
569     unsigned int md_len;
570     uint8_t i, offset = 0, out[128];
571
572     pthread_mutex_lock(&lock);
573     if (first) {
574         EVP_MD_CTX_init(&mdctx);
575         first = 0;
576     }
577
578     input = auth;
579     for (;;) {
580         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
581             !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
582             !EVP_DigestUpdate(&mdctx, input, 16) ||
583             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
584             md_len != 16) {
585             pthread_mutex_unlock(&lock);
586             return 0;
587         }
588         for (i = 0; i < 16; i++)
589             out[offset + i] = hash[i] ^ in[offset + i];
590         if (encrypt_flag)
591             input = out + offset;
592         else
593             input = in + offset;
594         offset += 16;
595         if (offset == len)
596             break;
597     }
598     memcpy(in, out, len);
599     pthread_mutex_unlock(&lock);
600     return 1;
601 }
602
603 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
604     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
605     static unsigned char first = 1;
606     static EVP_MD_CTX mdctx;
607     unsigned char hash[EVP_MAX_MD_SIZE];
608     unsigned int md_len;
609     uint8_t i, offset;
610
611     pthread_mutex_lock(&lock);
612     if (first) {
613         EVP_MD_CTX_init(&mdctx);
614         first = 0;
615     }
616
617 #if 0
618     printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
619     printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
620     printfchars(NULL, "msppencrypt in", "%02x ", text, len);
621 #endif
622
623     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
624         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
625         !EVP_DigestUpdate(&mdctx, auth, 16) ||
626         !EVP_DigestUpdate(&mdctx, salt, 2) ||
627         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
628         pthread_mutex_unlock(&lock);
629         return 0;
630     }
631
632 #if 0
633     printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
634 #endif
635
636     for (i = 0; i < 16; i++)
637         text[i] ^= hash[i];
638
639     for (offset = 16; offset < len; offset += 16) {
640 #if 0
641         printf("text + offset - 16 c(%d): ", offset / 16);
642         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
643 #endif
644         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
645             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
646             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
647             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
648             md_len != 16) {
649             pthread_mutex_unlock(&lock);
650             return 0;
651         }
652 #if 0
653         printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
654 #endif
655
656         for (i = 0; i < 16; i++)
657             text[offset + i] ^= hash[i];
658     }
659
660 #if 0
661     printfchars(NULL, "msppencrypt out", "%02x ", text, len);
662 #endif
663
664     pthread_mutex_unlock(&lock);
665     return 1;
666 }
667
668 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
669     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
670     static unsigned char first = 1;
671     static EVP_MD_CTX mdctx;
672     unsigned char hash[EVP_MAX_MD_SIZE];
673     unsigned int md_len;
674     uint8_t i, offset;
675     char plain[255];
676
677     pthread_mutex_lock(&lock);
678     if (first) {
679         EVP_MD_CTX_init(&mdctx);
680         first = 0;
681     }
682
683 #if 0
684     printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
685     printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
686     printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
687 #endif
688
689     if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
690         !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
691         !EVP_DigestUpdate(&mdctx, auth, 16) ||
692         !EVP_DigestUpdate(&mdctx, salt, 2) ||
693         !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
694         pthread_mutex_unlock(&lock);
695         return 0;
696     }
697
698 #if 0
699     printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
700 #endif
701
702     for (i = 0; i < 16; i++)
703         plain[i] = text[i] ^ hash[i];
704
705     for (offset = 16; offset < len; offset += 16) {
706 #if 0
707         printf("text + offset - 16 c(%d): ", offset / 16);
708         printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
709 #endif
710         if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
711             !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
712             !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
713             !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
714             md_len != 16) {
715             pthread_mutex_unlock(&lock);
716             return 0;
717         }
718 #if 0
719         printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
720 #endif
721
722         for (i = 0; i < 16; i++)
723             plain[offset + i] = text[offset + i] ^ hash[i];
724     }
725
726     memcpy(text, plain, len);
727 #if 0
728     printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
729 #endif
730
731     pthread_mutex_unlock(&lock);
732     return 1;
733 }
734
735 struct realm *newrealmref(struct realm *r) {
736     if (r)
737         r->refcount++;
738     return r;
739 }
740
741 /* returns with lock on realm */
742 struct realm *id2realm(struct list *realmlist, char *id) {
743     struct list_node *entry;
744     struct realm *realm, *subrealm;
745
746     /* need to do locking for subrealms and check subrealm timers */
747     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
748         realm = (struct realm *)entry->data;
749         if (!regexec(&realm->regex, id, 0, NULL, 0)) {
750             pthread_mutex_lock(&realm->mutex);
751             if (realm->subrealms) {
752                 subrealm = id2realm(realm->subrealms, id);
753                 if (subrealm) {
754                     pthread_mutex_unlock(&realm->mutex);
755                     return subrealm;
756                 }
757             }
758             return newrealmref(realm);
759         }
760     }
761     return NULL;
762 }
763
764 int hasdynamicserver(struct list *srvconfs) {
765     struct list_node *entry;
766
767     for (entry = list_first(srvconfs); entry; entry = list_next(entry))
768         if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
769             return 1;
770     return 0;
771 }
772
773 /* helper function, only used by removeserversubrealms() */
774 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
775     struct list_node *entry, *entry2;
776     struct realm *realm;
777
778     for (entry = list_first(realmlist); entry;) {
779         realm = newrealmref((struct realm *)entry->data);
780         pthread_mutex_lock(&realm->mutex);
781         entry = list_next(entry);
782
783         if (realm->srvconfs) {
784             for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
785                 if (entry2->data == srv)
786                     freerealm(realm);
787             list_removedata(realm->srvconfs, srv);
788         }
789         if (realm->accsrvconfs) {
790             for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
791                 if (entry2->data == srv)
792                     freerealm(realm);
793             list_removedata(realm->accsrvconfs, srv);
794         }
795
796         /* remove subrealm if no dynamic servers left */
797         if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
798             while (list_shift(realm->srvconfs))
799                 freerealm(realm);
800             list_destroy(realm->srvconfs);
801             realm->srvconfs = NULL;
802             while (list_shift(realm->accsrvconfs))
803                 freerealm(realm);
804             list_destroy(realm->accsrvconfs);
805             realm->accsrvconfs = NULL;
806             list_removedata(realmlist, realm);
807         }
808         pthread_mutex_unlock(&realm->mutex);
809         freerealm(realm);
810     }
811 }
812
813 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
814     struct list_node *entry;
815     struct realm *realm;
816
817     for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
818         realm = (struct realm *)entry->data;
819         pthread_mutex_lock(&realm->mutex);
820         if (realm->subrealms) {
821             _internal_removeserversubrealms(realm->subrealms, srv);
822             if (!list_first(realm->subrealms)) {
823                 list_destroy(realm->subrealms);
824                 realm->subrealms = NULL;
825             }
826         }
827         pthread_mutex_unlock(&realm->mutex);
828     }
829 }
830
831 int attrvalidate(unsigned char *attrs, int length) {
832     while (length > 1) {
833         if (ATTRLEN(attrs) < 2) {
834             debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
835             return 0;
836         }
837         length -= ATTRLEN(attrs);
838         if (length < 0) {
839             debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
840             return 0;
841         }
842         attrs += ATTRLEN(attrs);
843     }
844     if (length)
845         debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
846     return 1;
847 }
848
849 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
850     if (len < 16 || len > 128 || len % 16) {
851         debug(DBG_WARN, "pwdrecrypt: invalid password length");
852         return 0;
853     }
854
855     if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
856         debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
857         return 0;
858     }
859 #ifdef DEBUG
860     printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
861 #endif
862     if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
863         debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
864         return 0;
865     }
866     return 1;
867 }
868
869 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
870     if (len < 18)
871         return 0;
872     if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
873         debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
874         return 0;
875     }
876     if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
877         debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
878         return 0;
879     }
880     return 1;
881 }
882
883 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
884            char *oldsecret, char *newsecret) {
885     unsigned char *attr;
886
887     for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
888         debug(DBG_DBG, "msmppe: Got %s", attrtxt);
889         if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
890             return 0;
891     }
892     return 1;
893 }
894
895 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
896     if (!attrs)
897         return 0;
898
899     for (; attrs[0]; attrs += 2)
900         if (attrs[0] == vendor && attrs[1] == subattr)
901             return 1;
902     return 0;
903 }
904
905 /* returns 1 if entire element is to be removed, else 0 */
906 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
907     uint8_t alen, sublen;
908     uint32_t vendor;
909     uint8_t *subattrs;
910
911     if (!removevendorattrs)
912         return 0;
913
914     memcpy(&vendor, attr->v, 4);
915     vendor = ntohl(vendor);
916     while (*removevendorattrs && *removevendorattrs != vendor)
917         removevendorattrs += 2;
918     if (!*removevendorattrs)
919         return 0;
920
921     if (findvendorsubattr(removevendorattrs, vendor, 256))
922         return 1; /* remove entire vendor attribute */
923
924     sublen = attr->l - 4;
925     subattrs = attr->v + 4;
926
927     if (!attrvalidate(subattrs, sublen)) {
928         debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
929         return 0;
930     }
931
932     while (sublen > 1) {
933         alen = ATTRLEN(subattrs);
934         sublen -= alen;
935         if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
936             memmove(subattrs, subattrs + alen, sublen);
937             attr->l -= alen;
938         } else
939             subattrs += alen;
940     }
941     return 0;
942 }
943
944 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
945     struct list_node *n, *p;
946     struct tlv *attr;
947
948     p = NULL;
949     n = list_first(msg->attrs);
950     while (n) {
951         attr = (struct tlv *)n->data;
952         if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
953             (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
954             list_removedata(msg->attrs, attr);
955             freetlv(attr);
956             n = p ? list_next(p) : list_first(msg->attrs);
957         } else {
958             p = n;
959             n = list_next(n);
960         }
961     }
962 }
963
964 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
965     struct list_node *n;
966     struct tlv *a;
967
968     for (n = list_first(addattrs); n; n = list_next(n)) {
969         a = copytlv((struct tlv *)n->data);
970         if (!a)
971             return 0;
972         if (!radmsg_add(msg, a)) {
973             freetlv(a);
974             return 0;
975         }
976     }
977     return 1;
978 }
979
980 int resizeattr(struct tlv *attr, uint8_t newlen) {
981     uint8_t *newv;
982
983     if (newlen != attr->l) {
984         newv = realloc(attr->v, newlen);
985         if (!newv)
986             return 0;
987         attr->v = newv;
988         attr->l = newlen;
989     }
990     return 1;
991 }
992
993 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
994     size_t nmatch = 10, reslen = 0, start = 0;
995     regmatch_t pmatch[10], *pfield;
996     int i;
997     char *in, *out;
998
999     in = stringcopy((char *)attr->v, attr->l);
1000     if (!in)
1001         return 0;
1002
1003     if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1004         free(in);
1005         return 1;
1006     }
1007
1008     out = modattr->replacement;
1009
1010     for (i = start; out[i]; i++) {
1011         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1012             pfield = &pmatch[out[i + 1] - '0'];
1013             if (pfield->rm_so >= 0) {
1014                 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1015                 start = i + 2;
1016             }
1017             i++;
1018         }
1019     }
1020     reslen += i - start;
1021     if (reslen > 253) {
1022         debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1023         free(in);
1024         return 0;
1025     }
1026
1027     if (!resizeattr(attr, reslen)) {
1028         free(in);
1029         return 0;
1030     }
1031
1032     start = 0;
1033     reslen = 0;
1034     for (i = start; out[i]; i++) {
1035         if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1036             pfield = &pmatch[out[i + 1] - '0'];
1037             if (pfield->rm_so >= 0) {
1038                 memcpy(attr->v + reslen, out + start, i - start);
1039                 reslen += i - start;
1040                 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1041                 reslen += pfield->rm_eo - pfield->rm_so;
1042                 start = i + 2;
1043             }
1044             i++;
1045         }
1046     }
1047
1048     memcpy(attr->v + reslen, out + start, i - start);
1049     return 1;
1050 }
1051
1052 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1053     struct list_node *n, *m;
1054
1055     for (n = list_first(msg->attrs); n; n = list_next(n))
1056         for (m = list_first(modattrs); m; m = list_next(m))
1057             if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1058                 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1059                 return 0;
1060     return 1;
1061 }
1062
1063 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1064     int rv = 1;                 /* Success.  */
1065
1066     if (rewrite) {
1067         if (rewrite->removeattrs || rewrite->removevendorattrs)
1068             dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1069         if (rewrite->modattrs)
1070             if (!dorewritemod(msg, rewrite->modattrs))
1071                 rv = 0;
1072         if (rewrite->addattrs)
1073             if (!dorewriteadd(msg, rewrite->addattrs))
1074                 rv = 0;
1075     }
1076     return rv;
1077 }
1078
1079 int rewriteusername(struct request *rq, struct tlv *attr) {
1080     char *orig = (char *)tlv2str(attr);
1081     if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1082         free(orig);
1083         return 0;
1084     }
1085     if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1086         rq->origusername = (char *)orig;
1087     else
1088         free(orig);
1089     return 1;
1090 }
1091
1092 /** Create vendor specific tlv with ATTR.  ATTR is consumed (freed) if
1093  * all is well with the new tlv, i.e. if the function returns
1094  * !NULL.  */
1095 static struct tlv *
1096 makevendortlv(uint32_t vendor, struct tlv *attr)
1097 {
1098     struct tlv *newtlv = NULL;
1099     uint8_t l, *v;
1100
1101     if (!attr)
1102         return NULL;
1103     l = attr->l + 6;
1104     v = malloc(l);
1105     if (v) {
1106         vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1107         memcpy(v, &vendor, 4);
1108         tlv2buf(v + 4, attr);
1109         v[5] += 2; /* Vendor length increased for type and length fields. */
1110         newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1111         if (newtlv == NULL)
1112             free(v);
1113         else
1114             freetlv(attr);
1115     }
1116     return newtlv;
1117 }
1118
1119 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG.  ATTR
1120  * is consumed.  */
1121 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1122     struct tlv *vattr;
1123
1124     vattr = makevendortlv(vendor, attr);
1125     if (!vattr) {
1126         freetlv(attr);
1127         return 0;
1128     }
1129     if (!radmsg_add(msg, vattr)) {
1130         freetlv(vattr);
1131         return 0;
1132     }
1133     return 1;
1134 }
1135
1136 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1137     uint8_t ttl[4];
1138     struct tlv *attr;
1139
1140     memset(ttl, 0, 4);
1141     ttl[3] = addttl;
1142
1143     if (attrtype[1] == 256) { /* not vendor */
1144         attr = maketlv(attrtype[0], 4, ttl);
1145         if (attr && !radmsg_add(msg, attr))
1146             freetlv(attr);
1147     } else {
1148         attr = maketlv(attrtype[1], 4, ttl);
1149         if (attr)
1150             addvendorattr(msg, attrtype[0], attr);
1151     }
1152 }
1153
1154 int decttl(uint8_t l, uint8_t *v) {
1155     int i;
1156
1157     i = l - 1;
1158     if (v[i]) {
1159         if (--v[i--])
1160             return 1;
1161         while (i >= 0 && !v[i])
1162             i--;
1163         return i >= 0;
1164     }
1165     for (i--; i >= 0 && !v[i]; i--);
1166     if (i < 0)
1167         return 0;
1168     v[i]--;
1169     while (++i < l)
1170         v[i] = 255;
1171     return 1;
1172 }
1173
1174 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1175 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1176     uint8_t alen, *subattrs;
1177     struct tlv *attr;
1178     struct list_node *node;
1179     uint32_t vendor;
1180     int sublen;
1181
1182     if (attrtype[1] == 256) { /* not vendor */
1183         attr = radmsg_gettype(msg, attrtype[0]);
1184         if (attr)
1185             return decttl(attr->l, attr->v);
1186     } else
1187         for (node = list_first(msg->attrs); node; node = list_next(node)) {
1188             attr = (struct tlv *)node->data;
1189             if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1190                 continue;
1191             memcpy(&vendor, attr->v, 4);
1192             if (ntohl(vendor) != attrtype[0])
1193                 continue;
1194             sublen = attr->l - 4;
1195             subattrs = attr->v + 4;
1196             if (!attrvalidate(subattrs, sublen))
1197                 continue;
1198             while (sublen > 1) {
1199                 if (ATTRTYPE(subattrs) == attrtype[1])
1200                     return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1201                 alen = ATTRLEN(subattrs);
1202                 sublen -= alen;
1203                 subattrs += alen;
1204             }
1205         }
1206     return -1;
1207 }
1208
1209 const char *radmsgtype2string(uint8_t code) {
1210     static const char *rad_msg_names[] = {
1211         "", "Access-Request", "Access-Accept", "Access-Reject",
1212         "Accounting-Request", "Accounting-Response", "", "",
1213         "", "", "", "Access-Challenge",
1214         "Status-Server", "Status-Client"
1215     };
1216     return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1217 }
1218
1219 void char2hex(char *h, unsigned char c) {
1220     static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1221                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1222     h[0] = hexdigits[c / 16];
1223     h[1] = hexdigits[c % 16];
1224     return;
1225 }
1226
1227 uint8_t *radattr2ascii(struct tlv *attr) {
1228     int i, l;
1229     uint8_t *a, *d;
1230
1231     if (!attr)
1232         return NULL;
1233
1234     l = attr->l;
1235     for (i = 0; i < attr->l; i++)
1236         if (attr->v[i] < 32 || attr->v[i] > 126)
1237             l += 2;
1238     if (l == attr->l)
1239         return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1240
1241     a = malloc(l + 1);
1242     if (!a)
1243         return NULL;
1244
1245     d = a;
1246     for (i = 0; i < attr->l; i++)
1247         if (attr->v[i] < 32 || attr->v[i] > 126) {
1248             *d++ = '%';
1249             char2hex((char *)d, attr->v[i]);
1250             d += 2;
1251         } else
1252             *d++ = attr->v[i];
1253     *d = '\0';
1254     return a;
1255 }
1256
1257 void acclog(struct radmsg *msg, struct client *from) {
1258     struct tlv *attr;
1259     uint8_t *username;
1260
1261     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1262     if (!attr) {
1263         debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1264         return;
1265     }
1266     username = radattr2ascii(attr);
1267     if (username) {
1268         debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1269
1270         free(username);
1271     }
1272 }
1273
1274 void respond(struct request *rq, uint8_t code, char *message) {
1275     struct radmsg *msg;
1276     struct tlv *attr;
1277
1278     msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1279     if (!msg) {
1280         debug(DBG_ERR, "respond: malloc failed");
1281         return;
1282     }
1283     if (message && *message) {
1284         attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1285         if (!attr || !radmsg_add(msg, attr)) {
1286             freetlv(attr);
1287             radmsg_free(msg);
1288             debug(DBG_ERR, "respond: malloc failed");
1289             return;
1290         }
1291     }
1292
1293     radmsg_free(rq->msg);
1294     rq->msg = msg;
1295     debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1296     sendreply(newrqref(rq));
1297 }
1298
1299 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1300     struct list_node *entry;
1301     struct clsrvconf *server, *best = NULL, *first = NULL;
1302
1303     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1304         server = (struct clsrvconf *)entry->data;
1305         if (!server->servers)
1306             return server;
1307         if (!first)
1308             first = server;
1309         if (!server->servers->connectionok && !server->servers->dynstartup)
1310             continue;
1311         if (!server->servers->lostrqs)
1312             return server;
1313         if (!best) {
1314             best = server;
1315             continue;
1316         }
1317         if (server->servers->lostrqs < best->servers->lostrqs)
1318             best = server;
1319     }
1320     return best ? best : first;
1321 }
1322
1323 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1324 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1325     struct clsrvconf *srvconf;
1326     struct realm *subrealm;
1327     struct server *server = NULL;
1328     char *id = (char *)tlv2str(username);
1329
1330     if (!id)
1331         return NULL;
1332     /* returns with lock on realm */
1333     *realm = id2realm(realms, id);
1334     if (!*realm)
1335         goto exit;
1336     debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1337     srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1338     if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1339         subrealm = adddynamicrealmserver(*realm, id);
1340         if (subrealm) {
1341             pthread_mutex_lock(&subrealm->mutex);
1342             pthread_mutex_unlock(&(*realm)->mutex);
1343             freerealm(*realm);
1344             *realm = subrealm;
1345             srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1346         }
1347     }
1348     if (srvconf)
1349         server = srvconf->servers;
1350
1351 exit:
1352     free(id);
1353     return server;
1354 }
1355
1356
1357 struct request *newrequest() {
1358     struct request *rq;
1359
1360     rq = malloc(sizeof(struct request));
1361     if (!rq) {
1362         debug(DBG_ERR, "newrequest: malloc failed");
1363         return NULL;
1364     }
1365     memset(rq, 0, sizeof(struct request));
1366     rq->refcount = 1;
1367     gettimeofday(&rq->created, NULL);
1368     return rq;
1369 }
1370
1371 int addclientrq(struct request *rq) {
1372     struct request *r;
1373     struct timeval now;
1374
1375     r = rq->from->rqs[rq->rqid];
1376     if (r) {
1377         if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1378             gettimeofday(&now, NULL);
1379             if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1380                 if (r->replybuf) {
1381                     debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1382                     sendreply(newrqref(r));
1383                 } else
1384                     debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1385                 return 0;
1386             }
1387         }
1388         freerq(r);
1389     }
1390     rq->from->rqs[rq->rqid] = newrqref(rq);
1391     return 1;
1392 }
1393
1394 void rmclientrq(struct request *rq, uint8_t id) {
1395     struct request *r;
1396
1397     r = rq->from->rqs[id];
1398     if (r) {
1399         freerq(r);
1400         rq->from->rqs[id] = NULL;
1401     }
1402 }
1403
1404 /* returns 0 if validation/authentication fails, else 1 */
1405 int radsrv(struct request *rq) {
1406     struct radmsg *msg = NULL;
1407     struct tlv *attr;
1408     uint8_t *userascii = NULL;
1409     struct realm *realm = NULL;
1410     struct server *to = NULL;
1411     struct client *from = rq->from;
1412     int ttlres;
1413
1414     msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1415     free(rq->buf);
1416     rq->buf = NULL;
1417
1418     if (!msg) {
1419         debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1420         freerq(rq);
1421         return 0;
1422     }
1423
1424     rq->msg = msg;
1425     rq->rqid = msg->id;
1426     memcpy(rq->rqauth, msg->auth, 16);
1427
1428     debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1429     if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1430         debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1431         goto exit;
1432     }
1433
1434     if (!addclientrq(rq))
1435         goto exit;
1436
1437     if (msg->code == RAD_Status_Server) {
1438         respond(rq, RAD_Access_Accept, NULL);
1439         goto exit;
1440     }
1441
1442     /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1443
1444     if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1445         goto rmclrqexit;
1446
1447     ttlres = checkttl(msg, options.ttlattrtype);
1448     if (!ttlres) {
1449         debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1450         goto exit;
1451     }
1452
1453     attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1454     if (!attr) {
1455         if (msg->code == RAD_Accounting_Request) {
1456             acclog(msg, from);
1457             respond(rq, RAD_Accounting_Response, NULL);
1458         } else
1459             debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1460         goto exit;
1461     }
1462
1463     if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1464         debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1465         goto rmclrqexit;
1466     }
1467
1468     userascii = radattr2ascii(attr);
1469     if (!userascii)
1470         goto rmclrqexit;
1471     debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1472
1473     /* will return with lock on the realm */
1474     to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1475     if (!realm) {
1476         debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1477         goto exit;
1478     }
1479
1480     if (!to) {
1481         if (realm->message && msg->code == RAD_Access_Request) {
1482             debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1483             respond(rq, RAD_Access_Reject, realm->message);
1484         } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1485             acclog(msg, from);
1486             respond(rq, RAD_Accounting_Response, NULL);
1487         }
1488         goto exit;
1489     }
1490
1491     if ((to->conf->loopprevention == 1
1492          || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1493         && !strcmp(from->conf->name, to->conf->name)) {
1494         debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1495               from->conf->name, addr2string(from->addr), to->conf->name);
1496         goto exit;
1497     }
1498
1499     if (msg->code == RAD_Accounting_Request)
1500         memset(msg->auth, 0, 16);
1501     else if (!RAND_bytes(msg->auth, 16)) {
1502         debug(DBG_WARN, "radsrv: failed to generate random auth");
1503         goto rmclrqexit;
1504     }
1505
1506 #ifdef DEBUG
1507     printfchars(NULL, "auth", "%02x ", auth, 16);
1508 #endif
1509
1510     attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1511     if (attr) {
1512         debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1513         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1514             goto rmclrqexit;
1515     }
1516
1517     attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1518     if (attr) {
1519         debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1520         if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1521             goto rmclrqexit;
1522     }
1523
1524     if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1525         goto rmclrqexit;
1526
1527     if (ttlres == -1 && (options.addttl || to->conf->addttl))
1528         addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1529
1530     free(userascii);
1531     rq->to = to;
1532     sendrq(rq);
1533     pthread_mutex_unlock(&realm->mutex);
1534     freerealm(realm);
1535     return 1;
1536
1537 rmclrqexit:
1538     rmclientrq(rq, msg->id);
1539 exit:
1540     freerq(rq);
1541     free(userascii);
1542     if (realm) {
1543         pthread_mutex_unlock(&realm->mutex);
1544         freerealm(realm);
1545     }
1546     return 1;
1547 }
1548
1549 void replyh(struct server *server, unsigned char *buf) {
1550     struct client *from;
1551     struct rqout *rqout;
1552     int sublen, ttlres;
1553     unsigned char *subattrs;
1554     uint8_t *username, *stationid, *replymsg;
1555     struct radmsg *msg = NULL;
1556     struct tlv *attr;
1557     struct list_node *node;
1558
1559     server->connectionok = 1;
1560     server->lostrqs = 0;
1561
1562     rqout = server->requests + buf[1];
1563     pthread_mutex_lock(rqout->lock);
1564     if (!rqout->tries) {
1565         free(buf);
1566         buf = NULL;
1567         debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1568         goto errunlock;
1569     }
1570
1571     msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1572     free(buf);
1573     buf = NULL;
1574     if (!msg) {
1575         debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1576         goto errunlock;
1577     }
1578     if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1579         && msg->code != RAD_Accounting_Response) {
1580         debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1581         goto errunlock;
1582     }
1583     debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1584
1585     gettimeofday(&server->lastrcv, NULL);
1586
1587     if (rqout->rq->msg->code == RAD_Status_Server) {
1588         freerqoutdata(rqout);
1589         debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1590         goto errunlock;
1591     }
1592
1593     gettimeofday(&server->lastreply, NULL);
1594     from = rqout->rq->from;
1595
1596     if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1597         debug(DBG_INFO, "replyh: rewritein failed");
1598         goto errunlock;
1599     }
1600
1601     ttlres = checkttl(msg, options.ttlattrtype);
1602     if (!ttlres) {
1603         debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1604         goto errunlock;
1605     }
1606
1607     /* MS MPPE */
1608     for (node = list_first(msg->attrs); node; node = list_next(node)) {
1609         attr = (struct tlv *)node->data;
1610         if (attr->t != RAD_Attr_Vendor_Specific)
1611             continue;
1612         if (attr->l <= 4)
1613             break;
1614         if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55)  /* 311 == MS */
1615             continue;
1616
1617         sublen = attr->l - 4;
1618         subattrs = attr->v + 4;
1619         if (!attrvalidate(subattrs, sublen) ||
1620             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1621                     rqout->rq, server->conf->secret, from->conf->secret) ||
1622             !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1623                     rqout->rq, server->conf->secret, from->conf->secret))
1624             break;
1625     }
1626     if (node) {
1627         debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1628         goto errunlock;
1629     }
1630
1631     if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1632         username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1633         if (username) {
1634             stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1635             replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1636             if (stationid) {
1637                 if (replymsg) {
1638                     debug(DBG_NOTICE,
1639                           "%s for user %s stationid %s from %s (%s) to %s (%s)",
1640                           radmsgtype2string(msg->code), username, stationid,
1641                           server->conf->name, replymsg, from->conf->name,
1642                           addr2string(from->addr));
1643                     free(replymsg);
1644                 } else
1645                     debug(DBG_NOTICE,
1646                           "%s for user %s stationid %s from %s to %s (%s)",
1647                           radmsgtype2string(msg->code), username, stationid,
1648                           server->conf->name, from->conf->name,
1649                           addr2string(from->addr));
1650                 free(stationid);
1651             } else {
1652                 if (replymsg) {
1653                     debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1654                           radmsgtype2string(msg->code), username,
1655                           server->conf->name, replymsg, from->conf->name,
1656                           addr2string(from->addr));
1657                     free(replymsg);
1658                 } else
1659                     debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1660                           radmsgtype2string(msg->code), username,
1661                           server->conf->name, from->conf->name,
1662                           addr2string(from->addr));
1663             }
1664             free(username);
1665         }
1666     }
1667
1668     if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject)
1669         if (options.fticks_reporting && from->conf->fticks_viscountry != NULL)
1670             fticks_log(&options, from, msg, rqout);
1671
1672     msg->id = (char)rqout->rq->rqid;
1673     memcpy(msg->auth, rqout->rq->rqauth, 16);
1674
1675 #ifdef DEBUG
1676     printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1677 #endif
1678
1679     if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1680         if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1681             debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1682             goto errunlock;
1683         }
1684         memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1685     }
1686
1687     if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1688         debug(DBG_WARN, "replyh: rewriteout failed");
1689         goto errunlock;
1690     }
1691
1692     if (ttlres == -1 && (options.addttl || from->conf->addttl))
1693         addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1694
1695     debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1696           "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
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, "Server", CONF_CBK, confserver_cb,
2263                           (void *) conf, NULL);
2264     freegconf(&cf);
2265
2266     if (waitpid(pid, &status, 0) < 0) {
2267         debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2268         goto errexit;
2269     }
2270
2271     if (status) {
2272         debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2273         goto errexit;
2274     }
2275
2276     if (ok)
2277         return 1;
2278
2279 errexit:
2280     debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2281     return 0;
2282 }
2283
2284 /* should accept both names and numeric values, only numeric right now */
2285 uint8_t attrname2val(char *attrname) {
2286     int val = 0;
2287
2288     val = atoi(attrname);
2289     return val > 0 && val < 256 ? val : 0;
2290 }
2291
2292 /* ATTRNAME is on the form vendor[:type].
2293    If only vendor is found, TYPE is set to 256 and 1 is returned.
2294    If type is >= 256, 1 is returned.
2295    Otherwise, 0 is returned.
2296 */
2297 /* should accept both names and numeric values, only numeric right now */
2298 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2299     char *s;
2300
2301     *vendor = atoi(attrname);
2302     s = strchr(attrname, ':');
2303     if (!s) {                   /* Only vendor was found.  */
2304         *type = 256;
2305         return 1;
2306     }
2307     *type = atoi(s + 1);
2308     return *type < 256;
2309 }
2310
2311 /** Extract attributes from string NAMEVAL, create a struct tlv and
2312  * return the tlv.  If VENDOR_FLAG, NAMEVAL is on the form
2313  * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>".  Return
2314  * NULL if fields are missing or if conversion fails.
2315  *
2316  * FIXME: Should accept both names and numeric values, only numeric
2317  * right now */
2318 struct tlv *extractattr(char *nameval, char vendor_flag) {
2319     int len, name = 0;
2320     int vendor = 0;         /* Vendor 0 is reserved, see RFC 1700.  */
2321     char *s, *s2;
2322     struct tlv *a;
2323
2324     s = strchr(nameval, ':');
2325     if (!s)
2326         return NULL;
2327     name = atoi(nameval);
2328
2329     if (vendor_flag) {
2330         s2 = strchr(s + 1, ':');
2331         if (!s2)
2332             return NULL;
2333         vendor = name;
2334         name = atoi(s + 1);
2335         s = s2;
2336     }
2337     len = strlen(s + 1);
2338     if (len > 253)
2339         return NULL;
2340
2341     if (name < 1 || name > 255)
2342         return NULL;
2343     a = malloc(sizeof(struct tlv));
2344     if (!a)
2345         return NULL;
2346
2347     a->v = (uint8_t *)stringcopy(s + 1, 0);
2348     if (!a->v) {
2349         free(a);
2350         return NULL;
2351     }
2352     a->t = name;
2353     a->l = len;
2354
2355     if (vendor_flag)
2356         a = makevendortlv(vendor, a);
2357
2358     return a;
2359 }
2360
2361 /* should accept both names and numeric values, only numeric right now */
2362 struct modattr *extractmodattr(char *nameval) {
2363     int name = 0;
2364     char *s, *t;
2365     struct modattr *m;
2366
2367     if (!strncasecmp(nameval, "User-Name:/", 11)) {
2368         s = nameval + 11;
2369         name = 1;
2370     } else {
2371         s = strchr(nameval, ':');
2372         name = atoi(nameval);
2373         if (!s || name < 1 || name > 255 || s[1] != '/')
2374             return NULL;
2375         s += 2;
2376     }
2377     /* regexp, remove optional trailing / if present */
2378     if (s[strlen(s) - 1] == '/')
2379         s[strlen(s) - 1] = '\0';
2380
2381     t = strchr(s, '/');
2382     if (!t)
2383         return NULL;
2384     *t = '\0';
2385     t++;
2386
2387     m = malloc(sizeof(struct modattr));
2388     if (!m) {
2389         debug(DBG_ERR, "malloc failed");
2390         return NULL;
2391     }
2392     m->t = name;
2393
2394     m->replacement = stringcopy(t, 0);
2395     if (!m->replacement) {
2396         free(m);
2397         debug(DBG_ERR, "malloc failed");
2398         return NULL;
2399     }
2400
2401     m->regex = malloc(sizeof(regex_t));
2402     if (!m->regex) {
2403         free(m->replacement);
2404         free(m);
2405         debug(DBG_ERR, "malloc failed");
2406         return NULL;
2407     }
2408
2409     if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2410         free(m->regex);
2411         free(m->replacement);
2412         free(m);
2413         debug(DBG_ERR, "failed to compile regular expression %s", s);
2414         return NULL;
2415     }
2416
2417     return m;
2418 }
2419
2420 struct rewrite *getrewrite(char *alt1, char *alt2) {
2421     struct rewrite *r;
2422
2423     if (alt1)
2424         if ((r = hash_read(rewriteconfs,  alt1, strlen(alt1))))
2425             return r;
2426     if (alt2)
2427         if ((r = hash_read(rewriteconfs,  alt2, strlen(alt2))))
2428             return r;
2429     return NULL;
2430 }
2431
2432 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2433 {
2434     struct rewrite *rewrite = NULL;
2435     int i, n;
2436     uint8_t *rma = NULL;
2437     uint32_t *p, *rmva = NULL;
2438     struct list *adda = NULL, *moda = NULL;
2439     struct tlv *a;
2440     struct modattr *m;
2441
2442     if (rmattrs) {
2443         for (n = 0; rmattrs[n]; n++);
2444         rma = calloc(n + 1, sizeof(uint8_t));
2445         if (!rma)
2446             debugx(1, DBG_ERR, "malloc failed");
2447
2448         for (i = 0; i < n; i++)
2449             if (!(rma[i] = attrname2val(rmattrs[i])))
2450                 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2451         freegconfmstr(rmattrs);
2452         rma[i] = 0;
2453     }
2454
2455     if (rmvattrs) {
2456         for (n = 0; rmvattrs[n]; n++);
2457         rmva = calloc(2 * n + 1, sizeof(uint32_t));
2458         if (!rmva)
2459             debugx(1, DBG_ERR, "malloc failed");
2460
2461         for (p = rmva, i = 0; i < n; i++, p += 2)
2462             if (!vattrname2val(rmvattrs[i], p, p + 1))
2463                 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2464         freegconfmstr(rmvattrs);
2465         *p = 0;
2466     }
2467
2468     if (addattrs) {
2469         adda = list_create();
2470         if (!adda)
2471             debugx(1, DBG_ERR, "malloc failed");
2472         for (i = 0; addattrs[i]; i++) {
2473             a = extractattr(addattrs[i], 0);
2474             if (!a)
2475                 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2476             if (!list_push(adda, a))
2477                 debugx(1, DBG_ERR, "malloc failed");
2478         }
2479         freegconfmstr(addattrs);
2480     }
2481
2482     if (addvattrs) {
2483         if (!adda)
2484             adda = list_create();
2485         if (!adda)
2486             debugx(1, DBG_ERR, "malloc failed");
2487         for (i = 0; addvattrs[i]; i++) {
2488             a = extractattr(addvattrs[i], 1);
2489             if (!a)
2490                 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2491             if (!list_push(adda, a))
2492                 debugx(1, DBG_ERR, "malloc failed");
2493         }
2494         freegconfmstr(addvattrs);
2495     }
2496
2497     if (modattrs) {
2498         moda = list_create();
2499         if (!moda)
2500             debugx(1, DBG_ERR, "malloc failed");
2501         for (i = 0; modattrs[i]; i++) {
2502             m = extractmodattr(modattrs[i]);
2503             if (!m)
2504                 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2505             if (!list_push(moda, m))
2506                 debugx(1, DBG_ERR, "malloc failed");
2507         }
2508         freegconfmstr(modattrs);
2509     }
2510
2511     if (rma || rmva || adda || moda) {
2512         rewrite = malloc(sizeof(struct rewrite));
2513         if (!rewrite)
2514             debugx(1, DBG_ERR, "malloc failed");
2515         rewrite->removeattrs = rma;
2516         rewrite->removevendorattrs = rmva;
2517         rewrite->addattrs = adda;
2518         rewrite->modattrs = moda;
2519     }
2520
2521     if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2522         debugx(1, DBG_ERR, "malloc failed");
2523     debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2524 }
2525
2526 int setttlattr(struct options *opts, char *defaultattr) {
2527     char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2528
2529     if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2530         (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2531         return 1;
2532     debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2533     return 0;
2534 }
2535
2536 void freeclsrvconf(struct clsrvconf *conf) {
2537     free(conf->name);
2538     if (conf->hostsrc)
2539         freegconfmstr(conf->hostsrc);
2540     free(conf->portsrc);
2541     free(conf->secret);
2542     free(conf->tls);
2543     free(conf->matchcertattr);
2544     if (conf->certcnregex)
2545         regfree(conf->certcnregex);
2546     if (conf->certuriregex)
2547         regfree(conf->certuriregex);
2548     free(conf->confrewritein);
2549     free(conf->confrewriteout);
2550     if (conf->rewriteusername) {
2551         if (conf->rewriteusername->regex)
2552             regfree(conf->rewriteusername->regex);
2553         free(conf->rewriteusername->replacement);
2554         free(conf->rewriteusername);
2555     }
2556     free(conf->dynamiclookupcommand);
2557     free(conf->rewritein);
2558     free(conf->rewriteout);
2559     if (conf->hostports)
2560         freehostports(conf->hostports);
2561     if (conf->lock) {
2562         pthread_mutex_destroy(conf->lock);
2563         free(conf->lock);
2564     }
2565     /* not touching ssl_ctx, clients and servers */
2566     free(conf);
2567 }
2568
2569 int mergeconfstring(char **dst, char **src) {
2570     char *t;
2571
2572     if (*src) {
2573         *dst = *src;
2574         *src = NULL;
2575         return 1;
2576     }
2577     if (*dst) {
2578         t = stringcopy(*dst, 0);
2579         if (!t) {
2580             debug(DBG_ERR, "malloc failed");
2581             return 0;
2582         }
2583         *dst = t;
2584     }
2585     return 1;
2586 }
2587
2588 char **mstringcopy(char **in) {
2589     char **out;
2590     int n;
2591
2592     if (!in)
2593         return NULL;
2594
2595     for (n = 0; in[n]; n++);
2596     out = malloc((n + 1) * sizeof(char *));
2597     if (!out)
2598         return NULL;
2599     for (n = 0; in[n]; n++) {
2600         out[n] = stringcopy(in[n], 0);
2601         if (!out[n]) {
2602             freegconfmstr(out);
2603             return NULL;
2604         }
2605     }
2606     out[n] = NULL;
2607     return out;
2608 }
2609
2610 int mergeconfmstring(char ***dst, char ***src) {
2611     char **t;
2612
2613     if (*src) {
2614         *dst = *src;
2615         *src = NULL;
2616         return 1;
2617     }
2618     if (*dst) {
2619         t = mstringcopy(*dst);
2620         if (!t) {
2621             debug(DBG_ERR, "malloc failed");
2622             return 0;
2623         }
2624         *dst = t;
2625     }
2626     return 1;
2627 }
2628
2629 /* assumes dst is a shallow copy */
2630 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2631     if (!mergeconfstring(&dst->name, &src->name) ||
2632         !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2633         !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2634         !mergeconfstring(&dst->secret, &src->secret) ||
2635         !mergeconfstring(&dst->tls, &src->tls) ||
2636         !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2637         !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2638         !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2639         !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2640         return 0;
2641     if (src->pdef)
2642         dst->pdef = src->pdef;
2643     dst->statusserver = src->statusserver;
2644     dst->certnamecheck = src->certnamecheck;
2645     if (src->retryinterval != 255)
2646         dst->retryinterval = src->retryinterval;
2647     if (src->retrycount != 255)
2648         dst->retrycount = src->retrycount;
2649     return 1;
2650 }
2651
2652 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2653     struct clsrvconf *conf;
2654     char *conftype = NULL, *rewriteinalias = NULL;
2655     long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2656
2657     debug(DBG_DBG, "confclient_cb called for %s", block);
2658
2659     conf = malloc(sizeof(struct clsrvconf));
2660     if (!conf)
2661         debugx(1, DBG_ERR, "malloc failed");
2662     memset(conf, 0, sizeof(struct clsrvconf));
2663     conf->certnamecheck = 1;
2664
2665     if (!getgenericconfig(
2666             cf, block,
2667             "type", CONF_STR, &conftype,
2668             "host", CONF_MSTR, &conf->hostsrc,
2669             "secret", CONF_STR, &conf->secret,
2670 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2671             "tls", CONF_STR, &conf->tls,
2672             "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2673             "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2674 #endif
2675             "DuplicateInterval", CONF_LINT, &dupinterval,
2676             "addTTL", CONF_LINT, &addttl,
2677             "rewrite", CONF_STR, &rewriteinalias,
2678             "rewriteIn", CONF_STR, &conf->confrewritein,
2679             "rewriteOut", CONF_STR, &conf->confrewriteout,
2680             "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2681             "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2682             NULL
2683             ))
2684         debugx(1, DBG_ERR, "configuration error");
2685
2686     conf->name = stringcopy(val, 0);
2687     if (conf->name && !conf->hostsrc) {
2688         conf->hostsrc = malloc(2 * sizeof(char *));
2689         if (conf->hostsrc) {
2690             conf->hostsrc[0] = stringcopy(val, 0);
2691             conf->hostsrc[1] = NULL;
2692         }
2693     }
2694     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2695         debugx(1, DBG_ERR, "malloc failed");
2696
2697     if (!conftype)
2698         debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2699     conf->type = protoname2int(conftype);
2700     if (conf->type == 255)
2701         debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2702     free(conftype);
2703     conf->pdef = protodefs[conf->type];
2704
2705 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2706     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2707         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2708         if (!conf->tlsconf)
2709             debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2710         if (conf->matchcertattr && !addmatchcertattr(conf))
2711             debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2712     }
2713 #endif
2714
2715     if (dupinterval != LONG_MIN) {
2716         if (dupinterval < 0 || dupinterval > 255)
2717             debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2718         conf->dupinterval = (uint8_t)dupinterval;
2719     } else
2720         conf->dupinterval = conf->pdef->duplicateintervaldefault;
2721
2722     if (addttl != LONG_MIN) {
2723         if (addttl < 1 || addttl > 255)
2724             debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2725         conf->addttl = (uint8_t)addttl;
2726     }
2727
2728     if (!conf->confrewritein)
2729         conf->confrewritein = rewriteinalias;
2730     else
2731         free(rewriteinalias);
2732     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2733     if (conf->confrewriteout)
2734         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2735
2736     if (conf->confrewriteusername) {
2737         conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2738         if (!conf->rewriteusername)
2739             debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2740     }
2741
2742     if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2743         !resolvehostports(conf->hostports, conf->pdef->socktype))
2744         debugx(1, DBG_ERR, "resolve failed, exiting");
2745
2746     if (!conf->secret) {
2747         if (!conf->pdef->secretdefault)
2748             debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2749         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2750         if (!conf->secret)
2751             debugx(1, DBG_ERR, "malloc failed");
2752     }
2753
2754     conf->lock = malloc(sizeof(pthread_mutex_t));
2755     if (!conf->lock)
2756         debugx(1, DBG_ERR, "malloc failed");
2757
2758     pthread_mutex_init(conf->lock, NULL);
2759     if (!list_push(clconfs, conf))
2760         debugx(1, DBG_ERR, "malloc failed");
2761     return 1;
2762 }
2763
2764 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2765 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2766     if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2767         conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2768         if (!conf->tlsconf) {
2769             debug(DBG_ERR, "error in block %s, no tls context defined", block);
2770             return 0;
2771         }
2772         if (conf->matchcertattr && !addmatchcertattr(conf)) {
2773             debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2774             return 0;
2775         }
2776     }
2777 #endif
2778
2779     if (!conf->portsrc) {
2780         conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2781         if (!conf->portsrc) {
2782             debug(DBG_ERR, "malloc failed");
2783             return 0;
2784         }
2785     }
2786
2787     if (conf->retryinterval == 255)
2788         conf->retryinterval = conf->pdef->retryintervaldefault;
2789     if (conf->retrycount == 255)
2790         conf->retrycount = conf->pdef->retrycountdefault;
2791
2792     conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2793     if (conf->confrewriteout)
2794         conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2795
2796     if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2797         debug(DBG_ERR, "error in block %s, failed to parse %s", block, *conf->hostsrc);
2798         return 0;
2799     }
2800
2801     if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2802         debug(DBG_ERR, "resolve failed, exiting");
2803         return 0;
2804     }
2805     return 1;
2806 }
2807
2808 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2809     struct clsrvconf *conf, *resconf;
2810     char *conftype = NULL, *rewriteinalias = NULL;
2811     long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2812
2813     debug(DBG_DBG, "confserver_cb called for %s", block);
2814
2815     conf = malloc(sizeof(struct clsrvconf));
2816     if (!conf) {
2817         debug(DBG_ERR, "malloc failed");
2818         return 0;
2819     }
2820     memset(conf, 0, sizeof(struct clsrvconf));
2821     conf->loopprevention = UCHAR_MAX; /* Uninitialized.  */
2822     resconf = (struct clsrvconf *)arg;
2823     if (resconf) {
2824         conf->statusserver = resconf->statusserver;
2825         conf->certnamecheck = resconf->certnamecheck;
2826     } else
2827         conf->certnamecheck = 1;
2828
2829     if (!getgenericconfig(cf, block,
2830                           "type", CONF_STR, &conftype,
2831                           "host", CONF_MSTR, &conf->hostsrc,
2832                           "port", CONF_STR, &conf->portsrc,
2833                           "secret", CONF_STR, &conf->secret,
2834 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2835                           "tls", CONF_STR, &conf->tls,
2836                           "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2837                           "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2838 #endif
2839                           "addTTL", CONF_LINT, &addttl,
2840                           "rewrite", CONF_STR, &rewriteinalias,
2841                           "rewriteIn", CONF_STR, &conf->confrewritein,
2842                           "rewriteOut", CONF_STR, &conf->confrewriteout,
2843                           "StatusServer", CONF_BLN, &conf->statusserver,
2844                           "RetryInterval", CONF_LINT, &retryinterval,
2845                           "RetryCount", CONF_LINT, &retrycount,
2846                           "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2847                           "LoopPrevention", CONF_BLN, &conf->loopprevention,
2848                           NULL
2849             )) {
2850         debug(DBG_ERR, "configuration error");
2851         goto errexit;
2852     }
2853
2854     conf->name = stringcopy(val, 0);
2855     if (conf->name && !conf->hostsrc) {
2856         conf->hostsrc = malloc(2 * sizeof(char *));
2857         if (conf->hostsrc) {
2858             conf->hostsrc[0] = stringcopy(val, 0);
2859             conf->hostsrc[1] = NULL;
2860         }
2861     }
2862     if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2863         debug(DBG_ERR, "malloc failed");
2864         goto errexit;
2865     }
2866
2867     if (!conftype) {
2868         debug(DBG_ERR, "error in block %s, option type missing", block);
2869         goto errexit;
2870     }
2871     conf->type = protoname2int(conftype);
2872     if (conf->type == 255) {
2873         debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2874         goto errexit;
2875     }
2876     free(conftype);
2877     conftype = NULL;
2878
2879     conf->pdef = protodefs[conf->type];
2880
2881     if (!conf->confrewritein)
2882         conf->confrewritein = rewriteinalias;
2883     else
2884         free(rewriteinalias);
2885     rewriteinalias = NULL;
2886
2887     if (retryinterval != LONG_MIN) {
2888         if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2889             debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2890             goto errexit;
2891         }
2892         conf->retryinterval = (uint8_t)retryinterval;
2893     } else
2894         conf->retryinterval = 255;
2895
2896     if (retrycount != LONG_MIN) {
2897         if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2898             debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2899             goto errexit;
2900         }
2901         conf->retrycount = (uint8_t)retrycount;
2902     } else
2903         conf->retrycount = 255;
2904
2905     if (addttl != LONG_MIN) {
2906         if (addttl < 1 || addttl > 255) {
2907             debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2908             goto errexit;
2909         }
2910         conf->addttl = (uint8_t)addttl;
2911     }
2912
2913     if (resconf) {
2914         if (!mergesrvconf(resconf, conf))
2915             goto errexit;
2916         free(conf);
2917         conf = resconf;
2918         if (conf->dynamiclookupcommand) {
2919             free(conf->dynamiclookupcommand);
2920             conf->dynamiclookupcommand = NULL;
2921         }
2922     }
2923
2924     if (resconf || !conf->dynamiclookupcommand) {
2925         if (!compileserverconfig(conf, block))
2926             goto errexit;
2927     }
2928
2929     if (!conf->secret) {
2930         if (!conf->pdef->secretdefault) {
2931             debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2932             return 0;
2933         }
2934         conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2935         if (!conf->secret) {
2936             debug(DBG_ERR, "malloc failed");
2937             return 0;
2938         }
2939     }
2940
2941     if (resconf)
2942         return 1;
2943
2944     if (!list_push(srvconfs, conf)) {
2945         debug(DBG_ERR, "malloc failed");
2946         goto errexit;
2947     }
2948     return 1;
2949
2950 errexit:
2951     free(conftype);
2952     free(rewriteinalias);
2953     freeclsrvconf(conf);
2954     return 0;
2955 }
2956
2957 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2958     char **servers = NULL, **accservers = NULL, *msg = NULL;
2959     uint8_t accresp = 0;
2960
2961     debug(DBG_DBG, "confrealm_cb called for %s", block);
2962
2963     if (!getgenericconfig(cf, block,
2964                           "server", CONF_MSTR, &servers,
2965                           "accountingServer", CONF_MSTR, &accservers,
2966                           "ReplyMessage", CONF_STR, &msg,
2967                           "AccountingResponse", CONF_BLN, &accresp,
2968                           NULL
2969             ))
2970         debugx(1, DBG_ERR, "configuration error");
2971
2972     addrealm(realms, val, servers, accservers, msg, accresp);
2973     return 1;
2974 }
2975
2976 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2977     char **rmattrs = NULL, **rmvattrs = NULL;
2978     char **addattrs = NULL, **addvattrs = NULL;
2979     char **modattrs = NULL;
2980
2981     debug(DBG_DBG, "confrewrite_cb called for %s", block);
2982
2983     if (!getgenericconfig(cf, block,
2984                           "removeAttribute", CONF_MSTR, &rmattrs,
2985                           "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2986                           "addAttribute", CONF_MSTR, &addattrs,
2987                           "addVendorAttribute", CONF_MSTR, &addvattrs,
2988                           "modifyAttribute", CONF_MSTR, &modattrs,
2989                           NULL
2990             ))
2991         debugx(1, DBG_ERR, "configuration error");
2992     addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2993     return 1;
2994 }
2995
2996 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2997     struct commonprotoopts *protoopts;
2998
2999     protoopts = malloc(sizeof(struct commonprotoopts));
3000     if (!protoopts)
3001         return 0;
3002     memset(protoopts, 0, sizeof(struct commonprotoopts));
3003     protoopts->listenargs = listenargs;
3004     protoopts->sourcearg = sourcearg;
3005     protodefs[type]->setprotoopts(protoopts);
3006     return 1;
3007 }
3008
3009 void getmainconfig(const char *configfile) {
3010     long int addttl = LONG_MIN, loglevel = LONG_MIN;
3011     struct gconffile *cfs;
3012     char **listenargs[RAD_PROTOCOUNT];
3013     char *sourcearg[RAD_PROTOCOUNT];
3014     uint8_t *fticks_reporting_str = NULL;
3015     uint8_t *fticks_mac_str = NULL;
3016     uint8_t *fticks_key_str = NULL;
3017     int i;
3018
3019     cfs = openconfigfile(configfile);
3020     memset(&options, 0, sizeof(options));
3021     memset(&listenargs, 0, sizeof(listenargs));
3022     memset(&sourcearg, 0, sizeof(sourcearg));
3023
3024     clconfs = list_create();
3025     if (!clconfs)
3026         debugx(1, DBG_ERR, "malloc failed");
3027
3028     srvconfs = list_create();
3029     if (!srvconfs)
3030         debugx(1, DBG_ERR, "malloc failed");
3031
3032     realms = list_create();
3033     if (!realms)
3034         debugx(1, DBG_ERR, "malloc failed");
3035
3036     rewriteconfs = hash_create();
3037     if (!rewriteconfs)
3038         debugx(1, DBG_ERR, "malloc failed");
3039
3040     if (!getgenericconfig(
3041             &cfs, NULL,
3042 #ifdef RADPROT_UDP
3043             "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3044             "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3045 #endif
3046 #ifdef RADPROT_TCP
3047             "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3048             "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3049 #endif
3050 #ifdef RADPROT_TLS
3051             "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3052             "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3053 #endif
3054 #ifdef RADPROT_DTLS
3055             "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3056             "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3057 #endif
3058             "TTLAttribute", CONF_STR, &options.ttlattr,
3059             "addTTL", CONF_LINT, &addttl,
3060             "LogLevel", CONF_LINT, &loglevel,
3061             "LogDestination", CONF_STR, &options.logdestination,
3062             "LoopPrevention", CONF_BLN, &options.loopprevention,
3063             "Client", CONF_CBK, confclient_cb, NULL,
3064             "Server", CONF_CBK, confserver_cb, NULL,
3065             "Realm", CONF_CBK, confrealm_cb, NULL,
3066 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3067             "TLS", CONF_CBK, conftls_cb, NULL,
3068 #endif
3069             "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3070             "FTicksReporting", CONF_STR, &fticks_reporting_str,
3071             "FTicksMAC", CONF_STR, &fticks_mac_str,
3072             "FTicksKey", CONF_STR, &fticks_key_str,
3073             NULL
3074             ))
3075         debugx(1, DBG_ERR, "configuration error");
3076
3077     if (loglevel != LONG_MIN) {
3078         if (loglevel < 1 || loglevel > 5)
3079             debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3080         options.loglevel = (uint8_t)loglevel;
3081     }
3082     if (addttl != LONG_MIN) {
3083         if (addttl < 1 || addttl > 255)
3084             debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3085         options.addttl = (uint8_t)addttl;
3086     }
3087     if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3088         debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3089
3090     fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3091                      &fticks_key_str);
3092
3093     for (i = 0; i < RAD_PROTOCOUNT; i++)
3094         if (listenargs[i] || sourcearg[i])
3095             setprotoopts(i, listenargs[i], sourcearg[i]);
3096 }
3097
3098 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3099     int c;
3100
3101     while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3102         switch (c) {
3103         case 'c':
3104             *configfile = optarg;
3105             break;
3106         case 'd':
3107             if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3108                 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3109             *loglevel = *optarg - '0';
3110             break;
3111         case 'f':
3112             *foreground = 1;
3113             break;
3114         case 'i':
3115             *pidfile = optarg;
3116             break;
3117         case 'p':
3118             *pretend = 1;
3119             break;
3120         case 'v':
3121             debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3122             debug(DBG_ERR, "This binary was built with support for the following transports:");
3123 #ifdef RADPROT_UDP
3124             debug(DBG_ERR, "  UDP");
3125 #endif
3126 #ifdef RADPROT_TCP
3127             debug(DBG_ERR, "  TCP");
3128 #endif
3129 #ifdef RADPROT_TLS
3130             debug(DBG_ERR, "  TLS");
3131 #endif
3132 #ifdef RADPROT_DTLS
3133             debug(DBG_ERR, "  DTLS");
3134 #endif
3135             exit(0);
3136         default:
3137             goto usage;
3138         }
3139     }
3140     if (!(argc - optind))
3141         return;
3142
3143 usage:
3144     debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3145 }
3146
3147 #ifdef SYS_SOLARIS9
3148 int daemon(int a, int b) {
3149     int i;
3150
3151     if (fork())
3152         exit(0);
3153
3154     setsid();
3155
3156     for (i = 0; i < 3; i++) {
3157         close(i);
3158         open("/dev/null", O_RDWR);
3159     }
3160     return 1;
3161 }
3162 #endif
3163
3164 void *sighandler(void *arg) {
3165     sigset_t sigset;
3166     int sig;
3167
3168     for(;;) {
3169         sigemptyset(&sigset);
3170         sigaddset(&sigset, SIGHUP);
3171         sigaddset(&sigset, SIGPIPE);
3172         sigwait(&sigset, &sig);
3173         switch (sig) {
3174         case 0:
3175             /* completely ignoring this */
3176             break;
3177         case SIGHUP:
3178             debug(DBG_INFO, "sighandler: got SIGHUP");
3179             debug_reopen_log();
3180             break;
3181         case SIGPIPE:
3182             debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3183             break;
3184         default:
3185             debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3186         }
3187     }
3188 }
3189
3190 int createpidfile(const char *pidfile) {
3191     int r = 0;
3192     FILE *f = fopen(pidfile, "w");
3193     if (f)
3194         r = fprintf(f, "%ld\n", (long) getpid());
3195     return f && !fclose(f) && r >= 0;
3196 }
3197
3198 int radsecproxy_main(int argc, char **argv) {
3199     pthread_t sigth;
3200     sigset_t sigset;
3201     struct list_node *entry;
3202     uint8_t foreground = 0, pretend = 0, loglevel = 0;
3203     char *configfile = NULL, *pidfile = NULL;
3204     struct clsrvconf *srvconf;
3205     int i;
3206
3207     debug_init("radsecproxy");
3208     debug_set_level(DEBUG_LEVEL);
3209
3210     for (i = 0; i < RAD_PROTOCOUNT; i++)
3211         protodefs[i] = protoinits[i](i);
3212
3213     /* needed even if no TLS/DTLS transport */
3214     sslinit();
3215
3216     getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3217     if (loglevel)
3218         debug_set_level(loglevel);
3219     getmainconfig(configfile ? configfile : CONFIG_MAIN);
3220     if (loglevel)
3221         options.loglevel = loglevel;
3222     else if (options.loglevel)
3223         debug_set_level(options.loglevel);
3224     if (!foreground)
3225         debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3226     free(options.logdestination);
3227
3228     if (!list_first(clconfs))
3229         debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3230     if (!list_first(realms))
3231         debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3232
3233     if (pretend)
3234         debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3235
3236     if (!foreground && (daemon(0, 0) < 0))
3237         debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3238
3239     debug_timestamp_on();
3240     debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3241     if (pidfile && !createpidfile(pidfile))
3242         debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3243
3244     sigemptyset(&sigset);
3245     /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3246     sigaddset(&sigset, SIGHUP);
3247     sigaddset(&sigset, SIGPIPE);
3248     pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3249     pthread_create(&sigth, NULL, sighandler, NULL);
3250
3251     for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3252         srvconf = (struct clsrvconf *)entry->data;
3253         if (srvconf->dynamiclookupcommand)
3254             continue;
3255         if (!addserver(srvconf))
3256             debugx(1, DBG_ERR, "failed to add server");
3257         if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3258                            (void *)(srvconf->servers)))
3259             debugx(1, DBG_ERR, "pthread_create failed");
3260     }
3261
3262     for (i = 0; i < RAD_PROTOCOUNT; i++) {
3263         if (!protodefs[i])
3264             continue;
3265         if (protodefs[i]->initextra)
3266             protodefs[i]->initextra();
3267         if (find_clconf_type(i, NULL))
3268             createlisteners(i);
3269     }
3270
3271     /* just hang around doing nothing, anything to do here? */
3272     for (;;)
3273         sleep(1000);
3274 }
3275
3276 /* Local Variables: */
3277 /* c-file-style: "stroustrup" */
3278 /* End: */