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