1 /* Copyright (c) 2006-2010, UNINETT AS
2 * Copyright (c) 2010-2012, NORDUnet A/S */
3 /* See LICENSE for licensing information. */
5 /* Code contributions from:
7 * Arne Schwabe <schwabe at uni-paderborn.de>
8 * Maja Wolniewicz <mgw@umk.pl>
9 * Simon Leinen <simon.leinen@switch.ch>
10 * Stefan Winter <stefan.winter@restena.lu>
13 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
14 * rd is responsible for init and launching wr
15 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
16 * each tlsserverrd launches tlsserverwr
17 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
18 * for init and launching rd
20 * serverrd will receive a request, processes it and puts it in the requestq of
21 * the appropriate clientwr
22 * clientwr monitors its requestq and sends requests
23 * clientrd looks for responses, processes them and puts them in the replyq of
24 * the peer the request came from
25 * serverwr monitors its reply and sends replies
27 * In addition to the main thread, we have:
28 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
29 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
30 * For each TLS peer connecting to us there will be 2 more TLS threads
31 * This is only for connected peers
32 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
33 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
37 * May segfault when dtls connections go down? More testing needed
38 * Remove expired stuff from clients request list?
39 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
40 * Useful for TCP accounting? Now we require separate server config for alt port
44 #include <sys/socket.h>
45 #include <netinet/in.h>
54 #include <sys/types.h>
57 #include <arpa/inet.h>
63 #include <openssl/ssl.h>
64 #include <openssl/rand.h>
65 #include <openssl/err.h>
66 #include <openssl/md5.h>
71 #include "radsecproxy.h"
76 #if defined(WANT_FTICKS)
80 static struct options options;
81 static struct list *clconfs, *srvconfs;
82 static struct list *realms;
83 static struct hash *rewriteconfs;
85 static pthread_mutex_t *ssl_locks = NULL;
86 static long *ssl_lock_count;
89 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
91 /* minimum required declarations to avoid reordering code */
92 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
93 int dynamicconfig(struct server *server);
94 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
95 void freerealm(struct realm *realm);
96 void freeclsrvconf(struct clsrvconf *conf);
97 void freerq(struct request *rq);
98 void freerqoutdata(struct rqout *rqout);
99 void rmclientrq(struct request *rq, uint8_t id);
101 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
103 uint8_t protoname2int(const char *name) {
106 for (i = 0; i < RAD_PROTOCOUNT; i++)
107 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
112 /* callbacks for making OpenSSL thread safe */
113 unsigned long ssl_thread_id() {
114 return (unsigned long)pthread_self();
117 void ssl_locking_callback(int mode, int type, const char *file, int line) {
118 if (mode & CRYPTO_LOCK) {
119 pthread_mutex_lock(&ssl_locks[type]);
120 ssl_lock_count[type]++;
122 pthread_mutex_unlock(&ssl_locks[type]);
125 /* returns 1 if the len first bits are equal, else 0 */
126 int prefixmatch(void *a1, void *a2, uint8_t len) {
127 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
128 uint8_t r, l = len / 8;
129 if (l && memcmp(a1, a2, l))
134 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
137 /* returns next config with matching address, or NULL */
138 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
139 struct list_node *entry;
140 struct clsrvconf *conf;
142 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
143 conf = (struct clsrvconf *)entry->data;
144 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
153 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
154 return find_conf(type, addr, clconfs, cur, 0);
157 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
158 return find_conf(type, addr, srvconfs, cur, 1);
161 /* returns next config of given type, or NULL */
162 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
163 struct list_node *entry;
164 struct clsrvconf *conf;
166 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
167 conf = (struct clsrvconf *)entry->data;
168 if (conf->type == type) {
177 struct gqueue *newqueue() {
180 q = malloc(sizeof(struct gqueue));
182 debugx(1, DBG_ERR, "malloc failed");
183 q->entries = list_create();
185 debugx(1, DBG_ERR, "malloc failed");
186 pthread_mutex_init(&q->mutex, NULL);
187 pthread_cond_init(&q->cond, NULL);
191 void removequeue(struct gqueue *q) {
192 struct list_node *entry;
196 pthread_mutex_lock(&q->mutex);
197 for (entry = list_first(q->entries); entry; entry = list_next(entry))
198 freerq((struct request *)entry);
199 list_destroy(q->entries);
200 pthread_cond_destroy(&q->cond);
201 pthread_mutex_unlock(&q->mutex);
202 pthread_mutex_destroy(&q->mutex);
206 void freebios(struct gqueue *q) {
209 pthread_mutex_lock(&q->mutex);
210 while ((bio = (BIO *)list_shift(q->entries)))
212 pthread_mutex_unlock(&q->mutex);
216 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
217 struct client *new = malloc(sizeof(struct client));
220 debug(DBG_ERR, "malloc failed");
225 pthread_mutex_lock(conf->lock);
226 if (!conf->clients) {
227 conf->clients = list_create();
228 if (!conf->clients) {
230 pthread_mutex_unlock(conf->lock);
231 debug(DBG_ERR, "malloc failed");
236 memset(new, 0, sizeof(struct client));
238 if (conf->pdef->addclient)
239 conf->pdef->addclient(new);
241 new->replyq = newqueue();
242 list_push(conf->clients, new);
244 pthread_mutex_unlock(conf->lock);
248 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
249 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
252 pthread_mutex_lock(&lock);
254 pthread_mutex_unlock(&lock);
257 void removeclientrqs(struct client *client) {
262 removeclientrqs_sendrq_freeserver_lock(1);
263 for (i = 0; i < MAX_REQUESTS; i++) {
268 rqout = rq->to->requests + rq->newid;
269 pthread_mutex_lock(rqout->lock);
270 if (rqout->rq == rq) /* still pointing to our request */
271 freerqoutdata(rqout);
272 pthread_mutex_unlock(rqout->lock);
276 removeclientrqs_sendrq_freeserver_lock(0);
279 void removelockedclient(struct client *client) {
280 struct clsrvconf *conf;
284 removeclientrqs(client);
285 removequeue(client->replyq);
286 list_removedata(conf->clients, client);
292 void removeclient(struct client *client) {
293 struct clsrvconf *conf;
299 pthread_mutex_lock(conf->lock);
300 removelockedclient(client);
301 pthread_mutex_unlock(conf->lock);
304 void freeserver(struct server *server, uint8_t destroymutex) {
305 struct rqout *rqout, *end;
310 removeclientrqs_sendrq_freeserver_lock(1);
311 if (server->requests) {
312 rqout = server->requests;
313 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
315 rqout->rq->to = NULL;
316 freerqoutdata(rqout);
317 pthread_mutex_destroy(rqout->lock);
320 free(server->requests);
323 freebios(server->rbios);
324 free(server->dynamiclookuparg);
326 #if defined ENABLE_EXPERIMENTAL_DYNDISC
327 if (server->sock >= 0)
330 SSL_free(server->ssl);
333 pthread_mutex_destroy(&server->lock);
334 pthread_cond_destroy(&server->newrq_cond);
335 pthread_mutex_destroy(&server->newrq_mutex);
337 removeclientrqs_sendrq_freeserver_lock(0);
341 int addserver(struct clsrvconf *conf) {
345 debug(DBG_ERR, "addserver: currently works with just one server per conf");
348 conf->servers = malloc(sizeof(struct server));
349 if (!conf->servers) {
350 debug(DBG_ERR, "malloc failed");
353 memset(conf->servers, 0, sizeof(struct server));
354 conf->servers->conf = conf;
357 if (conf->type == RAD_DTLS)
358 conf->servers->rbios = newqueue();
360 conf->pdef->setsrcres();
362 conf->servers->sock = -1;
363 if (conf->pdef->addserverextra)
364 conf->pdef->addserverextra(conf);
366 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
367 if (!conf->servers->requests) {
368 debug(DBG_ERR, "malloc failed");
371 for (i = 0; i < MAX_REQUESTS; i++) {
372 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
373 if (!conf->servers->requests[i].lock) {
374 debug(DBG_ERR, "malloc failed");
377 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
378 debugerrno(errno, DBG_ERR, "mutex init failed");
379 free(conf->servers->requests[i].lock);
380 conf->servers->requests[i].lock = NULL;
384 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
385 debugerrno(errno, DBG_ERR, "mutex init failed");
388 conf->servers->newrq = 0;
389 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
390 debugerrno(errno, DBG_ERR, "mutex init failed");
391 pthread_mutex_destroy(&conf->servers->lock);
394 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
395 debugerrno(errno, DBG_ERR, "mutex init failed");
396 pthread_mutex_destroy(&conf->servers->newrq_mutex);
397 pthread_mutex_destroy(&conf->servers->lock);
404 freeserver(conf->servers, 0);
405 conf->servers = NULL;
409 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
411 if (ATTRTYPE(attrs) == type)
413 length -= ATTRLEN(attrs);
414 attrs += ATTRLEN(attrs);
419 struct request *newrqref(struct request *rq) {
425 void freerq(struct request *rq) {
428 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
431 if (rq->origusername)
432 free(rq->origusername);
438 radmsg_free(rq->msg);
442 void freerqoutdata(struct rqout *rqout) {
446 if (rqout->rq->buf) {
447 free(rqout->rq->buf);
448 rqout->rq->buf = NULL;
454 memset(&rqout->expiry, 0, sizeof(struct timeval));
457 void sendrq(struct request *rq) {
461 removeclientrqs_sendrq_freeserver_lock(1);
466 start = to->conf->statusserver ? 1 : 0;
467 pthread_mutex_lock(&to->newrq_mutex);
468 if (start && rq->msg->code == RAD_Status_Server) {
469 pthread_mutex_lock(to->requests[0].lock);
470 if (to->requests[0].rq) {
471 pthread_mutex_unlock(to->requests[0].lock);
472 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
479 /* might simplify if only try nextid, might be ok */
480 for (i = to->nextid; i < MAX_REQUESTS; i++) {
481 if (!to->requests[i].rq) {
482 pthread_mutex_lock(to->requests[i].lock);
483 if (!to->requests[i].rq)
485 pthread_mutex_unlock(to->requests[i].lock);
488 if (i == MAX_REQUESTS) {
489 for (i = start; i < to->nextid; i++) {
490 if (!to->requests[i].rq) {
491 pthread_mutex_lock(to->requests[i].lock);
492 if (!to->requests[i].rq)
494 pthread_mutex_unlock(to->requests[i].lock);
497 if (i == to->nextid) {
498 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
503 rq->newid = (uint8_t)i;
504 rq->msg->id = (uint8_t)i;
505 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
507 pthread_mutex_unlock(to->requests[i].lock);
508 debug(DBG_ERR, "sendrq: radmsg2buf failed");
512 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
513 to->requests[i].rq = rq;
514 pthread_mutex_unlock(to->requests[i].lock);
515 if (i >= start) /* i is not reserved for statusserver */
520 debug(DBG_DBG, "sendrq: signalling client writer");
521 pthread_cond_signal(&to->newrq_cond);
524 pthread_mutex_unlock(&to->newrq_mutex);
525 removeclientrqs_sendrq_freeserver_lock(0);
530 rmclientrq(rq, rq->msg->id);
532 pthread_mutex_unlock(&to->newrq_mutex);
533 removeclientrqs_sendrq_freeserver_lock(0);
536 void sendreply(struct request *rq) {
538 struct client *to = rq->from;
541 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
542 radmsg_free(rq->msg);
546 debug(DBG_ERR, "sendreply: radmsg2buf failed");
550 pthread_mutex_lock(&to->replyq->mutex);
551 first = list_first(to->replyq->entries) == NULL;
553 if (!list_push(to->replyq->entries, rq)) {
554 pthread_mutex_unlock(&to->replyq->mutex);
556 debug(DBG_ERR, "sendreply: malloc failed");
561 debug(DBG_DBG, "signalling server writer");
562 pthread_cond_signal(&to->replyq->cond);
564 pthread_mutex_unlock(&to->replyq->mutex);
567 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
568 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
569 static unsigned char first = 1;
570 static EVP_MD_CTX mdctx;
571 unsigned char hash[EVP_MAX_MD_SIZE], *input;
573 uint8_t i, offset = 0, out[128];
575 pthread_mutex_lock(&lock);
577 EVP_MD_CTX_init(&mdctx);
583 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
584 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
585 !EVP_DigestUpdate(&mdctx, input, 16) ||
586 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
588 pthread_mutex_unlock(&lock);
591 for (i = 0; i < 16; i++)
592 out[offset + i] = hash[i] ^ in[offset + i];
594 input = out + offset;
601 memcpy(in, out, len);
602 pthread_mutex_unlock(&lock);
606 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
607 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
608 static unsigned char first = 1;
609 static EVP_MD_CTX mdctx;
610 unsigned char hash[EVP_MAX_MD_SIZE];
614 pthread_mutex_lock(&lock);
616 EVP_MD_CTX_init(&mdctx);
621 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
622 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
623 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
626 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
627 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
628 !EVP_DigestUpdate(&mdctx, auth, 16) ||
629 !EVP_DigestUpdate(&mdctx, salt, 2) ||
630 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
631 pthread_mutex_unlock(&lock);
636 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
639 for (i = 0; i < 16; i++)
642 for (offset = 16; offset < len; offset += 16) {
644 printf("text + offset - 16 c(%d): ", offset / 16);
645 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
647 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
648 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
649 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
650 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
652 pthread_mutex_unlock(&lock);
656 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
659 for (i = 0; i < 16; i++)
660 text[offset + i] ^= hash[i];
664 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
667 pthread_mutex_unlock(&lock);
671 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
672 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
673 static unsigned char first = 1;
674 static EVP_MD_CTX mdctx;
675 unsigned char hash[EVP_MAX_MD_SIZE];
680 pthread_mutex_lock(&lock);
682 EVP_MD_CTX_init(&mdctx);
687 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
688 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
689 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
692 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
693 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
694 !EVP_DigestUpdate(&mdctx, auth, 16) ||
695 !EVP_DigestUpdate(&mdctx, salt, 2) ||
696 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
697 pthread_mutex_unlock(&lock);
702 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
705 for (i = 0; i < 16; i++)
706 plain[i] = text[i] ^ hash[i];
708 for (offset = 16; offset < len; offset += 16) {
710 printf("text + offset - 16 c(%d): ", offset / 16);
711 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
713 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
714 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
715 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
716 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
718 pthread_mutex_unlock(&lock);
722 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
725 for (i = 0; i < 16; i++)
726 plain[offset + i] = text[offset + i] ^ hash[i];
729 memcpy(text, plain, len);
731 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
734 pthread_mutex_unlock(&lock);
738 struct realm *newrealmref(struct realm *r) {
744 /* returns with lock on realm */
745 struct realm *id2realm(struct list *realmlist, char *id) {
746 struct list_node *entry;
747 struct realm *realm, *subrealm;
749 /* need to do locking for subrealms and check subrealm timers */
750 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
751 realm = (struct realm *)entry->data;
752 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
753 pthread_mutex_lock(&realm->mutex);
754 if (realm->subrealms) {
755 subrealm = id2realm(realm->subrealms, id);
757 pthread_mutex_unlock(&realm->mutex);
761 return newrealmref(realm);
767 int hasdynamicserver(struct list *srvconfs) {
768 struct list_node *entry;
770 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
771 #if defined ENABLE_EXPERIMENTAL_DYNDISC
772 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand
773 || ((struct clsrvconf *)entry->data)->servers->in_use)
775 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
781 /* helper function, only used by removeserversubrealms() */
782 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
783 struct list_node *entry, *entry2;
786 for (entry = list_first(realmlist); entry;) {
787 realm = newrealmref((struct realm *)entry->data);
788 pthread_mutex_lock(&realm->mutex);
789 entry = list_next(entry);
791 if (realm->srvconfs) {
792 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
793 if (entry2->data == srv)
795 list_removedata(realm->srvconfs, srv);
797 if (realm->accsrvconfs) {
798 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
799 if (entry2->data == srv)
801 list_removedata(realm->accsrvconfs, srv);
804 /* remove subrealm if no dynamic servers left */
805 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
806 while (list_shift(realm->srvconfs))
808 list_destroy(realm->srvconfs);
809 realm->srvconfs = NULL;
810 while (list_shift(realm->accsrvconfs))
812 list_destroy(realm->accsrvconfs);
813 realm->accsrvconfs = NULL;
814 list_removedata(realmlist, realm);
816 pthread_mutex_unlock(&realm->mutex);
821 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
822 struct list_node *entry;
825 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
826 realm = (struct realm *)entry->data;
827 pthread_mutex_lock(&realm->mutex);
828 if (realm->subrealms) {
829 _internal_removeserversubrealms(realm->subrealms, srv);
830 if (!list_first(realm->subrealms)) {
831 list_destroy(realm->subrealms);
832 realm->subrealms = NULL;
835 pthread_mutex_unlock(&realm->mutex);
839 int attrvalidate(unsigned char *attrs, int length) {
841 if (ATTRLEN(attrs) < 2) {
842 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
845 length -= ATTRLEN(attrs);
847 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
850 attrs += ATTRLEN(attrs);
853 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
857 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
858 if (len < 16 || len > 128 || len % 16) {
859 debug(DBG_WARN, "pwdrecrypt: invalid password length");
863 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
864 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
868 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
870 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
871 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
877 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
880 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
881 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
884 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
885 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
891 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
892 char *oldsecret, char *newsecret) {
895 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
896 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
897 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
903 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
907 for (; attrs[0]; attrs += 2)
908 if (attrs[0] == vendor && attrs[1] == subattr)
913 /* returns 1 if entire element is to be removed, else 0 */
914 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
915 uint8_t alen, sublen;
919 if (!removevendorattrs)
922 memcpy(&vendor, attr->v, 4);
923 vendor = ntohl(vendor);
924 while (*removevendorattrs && *removevendorattrs != vendor)
925 removevendorattrs += 2;
926 if (!*removevendorattrs)
929 if (findvendorsubattr(removevendorattrs, vendor, 256))
930 return 1; /* remove entire vendor attribute */
932 sublen = attr->l - 4;
933 subattrs = attr->v + 4;
935 if (!attrvalidate(subattrs, sublen)) {
936 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
941 alen = ATTRLEN(subattrs);
943 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
944 memmove(subattrs, subattrs + alen, sublen);
952 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
953 struct list_node *n, *p;
957 n = list_first(msg->attrs);
959 attr = (struct tlv *)n->data;
960 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
961 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
962 list_removedata(msg->attrs, attr);
964 n = p ? list_next(p) : list_first(msg->attrs);
972 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
976 for (n = list_first(addattrs); n; n = list_next(n)) {
977 a = copytlv((struct tlv *)n->data);
980 if (!radmsg_add(msg, a)) {
988 int resizeattr(struct tlv *attr, uint8_t newlen) {
991 if (newlen != attr->l) {
992 newv = realloc(attr->v, newlen);
1001 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1002 size_t nmatch = 10, reslen = 0, start = 0;
1003 regmatch_t pmatch[10], *pfield;
1007 in = stringcopy((char *)attr->v, attr->l);
1011 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1016 out = modattr->replacement;
1018 for (i = start; out[i]; i++) {
1019 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1020 pfield = &pmatch[out[i + 1] - '0'];
1021 if (pfield->rm_so >= 0) {
1022 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1028 reslen += i - start;
1030 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1035 if (!resizeattr(attr, reslen)) {
1042 for (i = start; out[i]; i++) {
1043 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1044 pfield = &pmatch[out[i + 1] - '0'];
1045 if (pfield->rm_so >= 0) {
1046 memcpy(attr->v + reslen, out + start, i - start);
1047 reslen += i - start;
1048 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1049 reslen += pfield->rm_eo - pfield->rm_so;
1056 memcpy(attr->v + reslen, out + start, i - start);
1060 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1061 struct list_node *n, *m;
1063 for (n = list_first(msg->attrs); n; n = list_next(n))
1064 for (m = list_first(modattrs); m; m = list_next(m))
1065 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1066 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1071 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1072 int rv = 1; /* Success. */
1075 if (rewrite->removeattrs || rewrite->removevendorattrs)
1076 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1077 if (rewrite->modattrs)
1078 if (!dorewritemod(msg, rewrite->modattrs))
1080 if (rewrite->addattrs)
1081 if (!dorewriteadd(msg, rewrite->addattrs))
1087 int rewriteusername(struct request *rq, struct tlv *attr) {
1088 char *orig = (char *)tlv2str(attr);
1089 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1093 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1094 rq->origusername = (char *)orig;
1100 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1101 * all is well with the new tlv, i.e. if the function returns
1104 makevendortlv(uint32_t vendor, struct tlv *attr)
1106 struct tlv *newtlv = NULL;
1114 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1115 memcpy(v, &vendor, 4);
1116 tlv2buf(v + 4, attr);
1117 v[5] += 2; /* Vendor length increased for type and length fields. */
1118 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1127 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1129 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1132 vattr = makevendortlv(vendor, attr);
1137 if (!radmsg_add(msg, vattr)) {
1144 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1151 if (attrtype[1] == 256) { /* not vendor */
1152 attr = maketlv(attrtype[0], 4, ttl);
1153 if (attr && !radmsg_add(msg, attr))
1156 attr = maketlv(attrtype[1], 4, ttl);
1158 addvendorattr(msg, attrtype[0], attr);
1162 int decttl(uint8_t l, uint8_t *v) {
1169 while (i >= 0 && !v[i])
1173 for (i--; i >= 0 && !v[i]; i--);
1182 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1183 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1184 uint8_t alen, *subattrs;
1186 struct list_node *node;
1190 if (attrtype[1] == 256) { /* not vendor */
1191 attr = radmsg_gettype(msg, attrtype[0]);
1193 return decttl(attr->l, attr->v);
1195 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1196 attr = (struct tlv *)node->data;
1197 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1199 memcpy(&vendor, attr->v, 4);
1200 if (ntohl(vendor) != attrtype[0])
1202 sublen = attr->l - 4;
1203 subattrs = attr->v + 4;
1204 if (!attrvalidate(subattrs, sublen))
1206 while (sublen > 1) {
1207 if (ATTRTYPE(subattrs) == attrtype[1])
1208 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1209 alen = ATTRLEN(subattrs);
1217 const char *radmsgtype2string(uint8_t code) {
1218 static const char *rad_msg_names[] = {
1219 "", "Access-Request", "Access-Accept", "Access-Reject",
1220 "Accounting-Request", "Accounting-Response", "", "",
1221 "", "", "", "Access-Challenge",
1222 "Status-Server", "Status-Client"
1224 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1227 void char2hex(char *h, unsigned char c) {
1228 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1229 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1230 h[0] = hexdigits[c / 16];
1231 h[1] = hexdigits[c % 16];
1235 uint8_t *radattr2ascii(struct tlv *attr) {
1243 for (i = 0; i < attr->l; i++)
1244 if (attr->v[i] < 32 || attr->v[i] > 126)
1247 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1254 for (i = 0; i < attr->l; i++)
1255 if (attr->v[i] < 32 || attr->v[i] > 126) {
1257 char2hex((char *)d, attr->v[i]);
1265 void acclog(struct radmsg *msg, struct client *from) {
1269 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1271 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1274 username = radattr2ascii(attr);
1276 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1282 void respond(struct request *rq, uint8_t code, char *message) {
1286 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1288 debug(DBG_ERR, "respond: malloc failed");
1291 if (message && *message) {
1292 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1293 if (!attr || !radmsg_add(msg, attr)) {
1296 debug(DBG_ERR, "respond: malloc failed");
1301 radmsg_free(rq->msg);
1303 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1304 sendreply(newrqref(rq));
1307 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1308 struct list_node *entry;
1309 struct clsrvconf *server, *best = NULL, *first = NULL;
1311 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1312 server = (struct clsrvconf *)entry->data;
1313 if (!server->servers)
1315 if (server->servers->dynfailing)
1319 if (!server->servers->connectionok && !server->servers->dynstartup)
1321 if (!server->servers->lostrqs)
1327 if (server->servers->lostrqs < best->servers->lostrqs)
1330 return best ? best : first;
1333 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1334 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1335 struct clsrvconf *srvconf;
1336 struct realm *subrealm;
1337 struct server *server = NULL;
1338 char *id = (char *)tlv2str(username);
1342 /* returns with lock on realm */
1343 *realm = id2realm(realms, id);
1346 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1347 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1348 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1349 subrealm = adddynamicrealmserver(*realm, id);
1351 pthread_mutex_lock(&subrealm->mutex);
1352 pthread_mutex_unlock(&(*realm)->mutex);
1355 debug(DBG_DBG, "added realm: %s", (*realm)->name);
1356 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1357 debug(DBG_DBG, "found conf for new realm: %s", srvconf->name);
1361 debug(DBG_DBG, "found matching conf: %s", srvconf->name);
1362 server = srvconf->servers;
1371 struct request *newrequest() {
1374 rq = malloc(sizeof(struct request));
1376 debug(DBG_ERR, "newrequest: malloc failed");
1379 memset(rq, 0, sizeof(struct request));
1381 gettimeofday(&rq->created, NULL);
1385 int addclientrq(struct request *rq) {
1389 r = rq->from->rqs[rq->rqid];
1391 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1392 gettimeofday(&now, NULL);
1393 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1395 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1396 sendreply(newrqref(r));
1398 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1404 rq->from->rqs[rq->rqid] = newrqref(rq);
1408 void rmclientrq(struct request *rq, uint8_t id) {
1411 r = rq->from->rqs[id];
1414 rq->from->rqs[id] = NULL;
1418 /* returns 0 if validation/authentication fails, else 1 */
1419 int radsrv(struct request *rq) {
1420 struct radmsg *msg = NULL;
1422 uint8_t *userascii = NULL;
1423 struct realm *realm = NULL;
1424 struct server *to = NULL;
1425 struct client *from = rq->from;
1428 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1433 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1440 memcpy(rq->rqauth, msg->auth, 16);
1442 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1443 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1444 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1448 if (!addclientrq(rq))
1451 if (msg->code == RAD_Status_Server) {
1452 respond(rq, RAD_Access_Accept, NULL);
1456 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1458 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1461 ttlres = checkttl(msg, options.ttlattrtype);
1463 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1467 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1469 if (msg->code == RAD_Accounting_Request) {
1471 respond(rq, RAD_Accounting_Response, NULL);
1473 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1477 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1478 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1482 userascii = radattr2ascii(attr);
1485 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1487 /* will return with lock on the realm */
1488 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1490 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1495 if (realm->message && msg->code == RAD_Access_Request) {
1496 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1497 respond(rq, RAD_Access_Reject, realm->message);
1498 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1500 respond(rq, RAD_Accounting_Response, NULL);
1505 if ((to->conf->loopprevention == 1
1506 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1507 && !strcmp(from->conf->name, to->conf->name)) {
1508 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1509 from->conf->name, addr2string(from->addr), to->conf->name);
1513 if (msg->code == RAD_Accounting_Request)
1514 memset(msg->auth, 0, 16);
1515 else if (!RAND_bytes(msg->auth, 16)) {
1516 debug(DBG_WARN, "radsrv: failed to generate random auth");
1521 printfchars(NULL, "auth", "%02x ", auth, 16);
1524 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1526 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1527 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1531 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1533 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1534 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1538 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1541 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1542 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1547 pthread_mutex_unlock(&realm->mutex);
1552 rmclientrq(rq, msg->id);
1557 pthread_mutex_unlock(&realm->mutex);
1563 void replyh(struct server *server, unsigned char *buf) {
1564 struct client *from;
1565 struct rqout *rqout;
1567 unsigned char *subattrs;
1568 uint8_t *username, *stationid, *replymsg;
1569 struct radmsg *msg = NULL;
1571 struct list_node *node;
1573 server->connectionok = 1;
1574 server->lostrqs = 0;
1576 rqout = server->requests + buf[1];
1577 pthread_mutex_lock(rqout->lock);
1578 if (!rqout->tries) {
1581 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1585 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1589 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1592 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1593 && msg->code != RAD_Accounting_Response) {
1594 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1597 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1599 gettimeofday(&server->lastrcv, NULL);
1601 if (rqout->rq->msg->code == RAD_Status_Server) {
1602 freerqoutdata(rqout);
1603 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1607 gettimeofday(&server->lastreply, NULL);
1608 from = rqout->rq->from;
1610 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1611 debug(DBG_INFO, "replyh: rewritein failed");
1615 ttlres = checkttl(msg, options.ttlattrtype);
1617 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1622 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1623 attr = (struct tlv *)node->data;
1624 if (attr->t != RAD_Attr_Vendor_Specific)
1628 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1631 sublen = attr->l - 4;
1632 subattrs = attr->v + 4;
1633 if (!attrvalidate(subattrs, sublen) ||
1634 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1635 rqout->rq, server->conf->secret, from->conf->secret) ||
1636 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1637 rqout->rq, server->conf->secret, from->conf->secret))
1641 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1645 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1646 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1648 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1649 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1653 "%s for user %s stationid %s from %s (%s) to %s (%s)",
1654 radmsgtype2string(msg->code), username, stationid,
1655 server->conf->name, replymsg, from->conf->name,
1656 addr2string(from->addr));
1660 "%s for user %s stationid %s from %s to %s (%s)",
1661 radmsgtype2string(msg->code), username, stationid,
1662 server->conf->name, from->conf->name,
1663 addr2string(from->addr));
1667 debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1668 radmsgtype2string(msg->code), username,
1669 server->conf->name, replymsg, from->conf->name,
1670 addr2string(from->addr));
1673 debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1674 radmsgtype2string(msg->code), username,
1675 server->conf->name, from->conf->name,
1676 addr2string(from->addr));
1682 #if defined(WANT_FTICKS)
1683 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject)
1684 if (options.fticks_reporting && from->conf->fticks_viscountry != NULL)
1685 fticks_log(&options, from, msg, rqout);
1688 msg->id = (char)rqout->rq->rqid;
1689 memcpy(msg->auth, rqout->rq->rqauth, 16);
1692 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1695 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1696 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1697 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1700 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1703 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1704 debug(DBG_WARN, "replyh: rewriteout failed");
1708 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1709 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1711 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1712 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1714 radmsg_free(rqout->rq->msg);
1715 rqout->rq->msg = msg;
1716 sendreply(newrqref(rqout->rq));
1717 freerqoutdata(rqout);
1718 pthread_mutex_unlock(rqout->lock);
1723 pthread_mutex_unlock(rqout->lock);
1727 struct request *createstatsrvrq() {
1734 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1737 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1740 if (!radmsg_add(rq->msg, attr)) {
1751 /* code for removing state not finished */
1752 void *clientwr(void *arg) {
1753 struct server *server = (struct server *)arg;
1754 struct rqout *rqout = NULL;
1755 pthread_t clientrdth;
1756 int i, dynconffail = 0;
1759 struct timeval now, laststatsrv;
1760 struct timespec timeout;
1761 struct request *statsrvrq;
1762 struct clsrvconf *conf;
1764 conf = server->conf;
1768 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1770 server->dynstartup = 0;
1771 server->dynfailing = 1;
1772 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1773 pthread_mutex_unlock(&server->lock);
1775 debug(DBG_WARN, "%s: dynamicconfig(%s) failed, sleeping %ds",
1776 __func__, server->conf->name, ZZZ);
1780 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1781 pthread_mutex_unlock(&server->lock);
1783 /* FIXME: Is resolving not always done by compileserverconfig(),
1784 * either as part of static configuration setup or by
1785 * dynamicconfig() above? */
1786 if (!resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype)) {
1787 debug(DBG_WARN, "%s: resolve failed, sleeping %ds", __func__, ZZZ);
1792 memset(&timeout, 0, sizeof(struct timespec));
1794 if (conf->statusserver) {
1795 gettimeofday(&server->lastrcv, NULL);
1796 gettimeofday(&laststatsrv, NULL);
1799 if (conf->pdef->connecter) {
1800 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1801 if (server->dynamiclookuparg) {
1802 server->dynstartup = 0;
1803 server->dynfailing = 1;
1804 debug(DBG_WARN, "%s: connect failed, sleeping %ds",
1810 server->connectionok = 1;
1811 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1814 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1815 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1819 server->connectionok = 1;
1820 server->dynstartup = 0;
1823 pthread_mutex_lock(&server->newrq_mutex);
1824 if (!server->newrq) {
1825 gettimeofday(&now, NULL);
1826 /* random 0-7 seconds */
1827 RAND_bytes(&rnd, 1);
1829 if (conf->statusserver) {
1830 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1831 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1833 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1834 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1836 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1837 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1840 if (timeout.tv_sec > now.tv_sec)
1841 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1843 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1846 if (server->newrq) {
1847 debug(DBG_DBG, "clientwr: got new request");
1852 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1854 pthread_mutex_unlock(&server->newrq_mutex);
1856 for (i = 0; i < MAX_REQUESTS; i++) {
1857 if (server->clientrdgone) {
1858 pthread_join(clientrdth, NULL);
1862 for (; i < MAX_REQUESTS; i++) {
1863 rqout = server->requests + i;
1865 pthread_mutex_lock(rqout->lock);
1868 pthread_mutex_unlock(rqout->lock);
1872 if (i == MAX_REQUESTS)
1875 gettimeofday(&now, NULL);
1876 if (now.tv_sec < rqout->expiry.tv_sec) {
1877 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1878 timeout.tv_sec = rqout->expiry.tv_sec;
1879 pthread_mutex_unlock(rqout->lock);
1883 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1884 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1885 if (conf->statusserver) {
1886 if (*rqout->rq->buf == RAD_Status_Server) {
1887 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1888 if (server->lostrqs < 255)
1892 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1893 if (server->lostrqs < 255)
1896 freerqoutdata(rqout);
1897 pthread_mutex_unlock(rqout->lock);
1901 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1902 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1903 timeout.tv_sec = rqout->expiry.tv_sec;
1905 conf->pdef->clientradput(server, rqout->rq->buf);
1906 pthread_mutex_unlock(rqout->lock);
1908 if (conf->statusserver && server->connectionok) {
1909 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1910 gettimeofday(&now, NULL);
1911 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1913 statsrvrq = createstatsrvrq();
1915 statsrvrq->to = server;
1916 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1923 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1926 conf->servers = NULL;
1927 if (server->dynamiclookuparg) {
1928 removeserversubrealms(realms, conf);
1932 freeclsrvconf(conf);
1934 freeserver(server, 1);
1935 ERR_remove_state(0);
1939 void createlistener(uint8_t type, char *arg) {
1941 struct addrinfo *res;
1942 int s = -1, on = 1, *sp = NULL;
1943 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1945 if (!hp || !resolvehostport(hp, AF_UNSPEC, protodefs[type]->socktype, 1))
1946 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1948 for (res = hp->addrinfo; res; res = res->ai_next) {
1949 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1951 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1954 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1956 disable_DF_bit(s, res);
1959 if (res->ai_family == AF_INET6)
1960 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1962 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1963 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1969 sp = malloc(sizeof(int));
1971 debugx(1, DBG_ERR, "malloc failed");
1973 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1974 debugerrnox(errno, DBG_ERR, "pthread_create failed");
1978 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1980 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1984 void createlisteners(uint8_t type) {
1988 args = protodefs[type]->getlistenerargs();
1990 for (i = 0; args[i]; i++)
1991 createlistener(type, args[i]);
1993 createlistener(type, NULL);
2001 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2002 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2003 for (i = 0; i < CRYPTO_num_locks(); i++) {
2004 ssl_lock_count[i] = 0;
2005 pthread_mutex_init(&ssl_locks[i], NULL);
2007 CRYPTO_set_id_callback(ssl_thread_id);
2008 CRYPTO_set_locking_callback(ssl_locking_callback);
2010 SSL_load_error_strings();
2013 while (!RAND_status()) {
2016 RAND_seed((unsigned char *)&t, sizeof(time_t));
2017 RAND_seed((unsigned char *)&pid, sizeof(pid));
2021 struct list *addsrvconfs(char *value, char **names) {
2022 struct list *conflist;
2024 struct list_node *entry;
2025 struct clsrvconf *conf = NULL;
2027 if (!names || !*names)
2030 conflist = list_create();
2032 debug(DBG_ERR, "malloc failed");
2036 for (n = 0; names[n]; n++) {
2037 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2038 conf = (struct clsrvconf *)entry->data;
2039 if (!strcasecmp(names[n], conf->name))
2043 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2044 list_destroy(conflist);
2047 if (!list_push(conflist, conf)) {
2048 debug(DBG_ERR, "malloc failed");
2049 list_destroy(conflist);
2052 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2057 void freerealm(struct realm *realm) {
2060 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2061 if (--realm->refcount)
2065 free(realm->message);
2066 regfree(&realm->regex);
2067 pthread_mutex_destroy(&realm->mutex);
2068 /* if refcount == 0, all subrealms gone */
2069 list_destroy(realm->subrealms);
2070 /* if refcount == 0, all srvconfs gone */
2071 list_destroy(realm->srvconfs);
2072 /* if refcount == 0, all accsrvconfs gone */
2073 list_destroy(realm->accsrvconfs);
2074 freerealm(realm->parent);
2078 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2080 struct realm *realm;
2081 char *s, *regex = NULL;
2083 if (*value == '/') {
2084 /* regexp, remove optional trailing / if present */
2085 if (value[strlen(value) - 1] == '/')
2086 value[strlen(value) - 1] = '\0';
2088 /* not a regexp, let us make it one */
2089 if (*value == '*' && !value[1])
2090 regex = stringcopy(".*", 0);
2092 for (n = 0, s = value; *s;)
2095 regex = malloc(strlen(value) + n + 3);
2098 for (n = 1, s = value; *s; s++) {
2108 debug(DBG_ERR, "malloc failed");
2112 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2115 realm = malloc(sizeof(struct realm));
2117 debug(DBG_ERR, "malloc failed");
2120 memset(realm, 0, sizeof(struct realm));
2122 if (pthread_mutex_init(&realm->mutex, NULL)) {
2123 debugerrno(errno, DBG_ERR, "mutex init failed");
2129 realm->name = stringcopy(value, 0);
2131 debug(DBG_ERR, "malloc failed");
2134 if (message && strlen(message) > 253) {
2135 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2138 realm->message = message;
2139 realm->accresp = accresp;
2141 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2142 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2146 if (servers && *servers) {
2147 realm->srvconfs = addsrvconfs(value, servers);
2148 if (!realm->srvconfs)
2152 if (accservers && *accservers) {
2153 realm->accsrvconfs = addsrvconfs(value, accservers);
2154 if (!realm->accsrvconfs)
2158 if (!list_push(realmlist, realm)) {
2159 debug(DBG_ERR, "malloc failed");
2160 pthread_mutex_destroy(&realm->mutex);
2164 debug(DBG_DBG, "addrealm: added realm %s", value);
2168 while (list_shift(realm->srvconfs));
2169 while (list_shift(realm->accsrvconfs));
2176 for (n = 0; servers[n]; n++)
2178 freegconfmstr(servers);
2182 for (n = 0; accservers[n]; n++)
2184 freegconfmstr(accservers);
2186 return newrealmref(realm);
2189 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2190 struct list_node *entry;
2191 struct clsrvconf *conf, *srvconf;
2192 struct list *subrealmservers = NULL;
2195 if (list_first(srvconfs)) {
2196 subrealmservers = list_create();
2197 if (!subrealmservers)
2201 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2202 conf = (struct clsrvconf *)entry->data;
2203 if (!conf->servers && conf->dynamiclookupcommand) {
2204 srvconf = malloc(sizeof(struct clsrvconf));
2206 debug(DBG_ERR, "malloc failed");
2209 debug(DBG_DBG, "%s: copying config %s", __func__, conf->name);
2211 /* Shallow copy -- sharing all the pointers. addserver()
2212 * will take care of servers (which btw has to be NUL) but
2213 * the rest of them are shared with the config found in
2214 * the srvconfs list. */
2215 if (addserver(srvconf)) {
2216 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2217 srvconf->servers->dynstartup = 1;
2218 debug(DBG_DBG, "%s: new client writer for %s",
2219 __func__, srvconf->servers->conf->name);
2220 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2221 pthread_mutex_lock(&srvconf->servers->lock);
2223 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2224 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2225 pthread_mutex_unlock(&srvconf->servers->lock);
2227 debugerrno(errno, DBG_ERR, "pthread_create failed");
2228 freeserver(srvconf->servers, 1);
2229 srvconf->servers = NULL;
2230 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2235 pthread_detach(clientth);
2237 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2238 /* If clientwr() could not find a NAPTR we have to
2239 * wait for dynfailing=1 what is set in clientwr(). */
2240 pthread_mutex_lock(&srvconf->servers->lock);
2241 pthread_mutex_unlock(&srvconf->servers->lock);
2246 if (conf->servers) {
2247 if (list_push(subrealmservers, conf))
2250 debug(DBG_ERR, "malloc failed");
2253 return subrealmservers;
2256 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2257 struct realm *newrealm = NULL;
2258 char *realmname, *s;
2260 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2261 realmname = strrchr(id, '@');
2267 for (s = realmname; *s; s++)
2268 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2271 if (!realm->subrealms)
2272 realm->subrealms = list_create();
2273 if (!realm->subrealms)
2276 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2278 list_destroy(realm->subrealms);
2279 realm->subrealms = NULL;
2283 newrealm->parent = newrealmref(realm);
2284 /* add server and accserver to newrealm */
2285 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2286 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2290 int dynamicconfig(struct server *server) {
2291 int ok, fd[2], status;
2293 struct clsrvconf *conf = server->conf;
2294 struct gconffile *cf = NULL;
2296 /* for now we only learn hostname/address */
2297 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2300 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2305 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2309 } else if (pid == 0) {
2312 if (fd[1] != STDOUT_FILENO) {
2313 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2314 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2317 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2318 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2322 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2323 ok = getgenericconfig(&cf, NULL, "Server", CONF_CBK, confserver_cb,
2324 (void *) conf, NULL);
2327 if (waitpid(pid, &status, 0) < 0) {
2328 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2333 debug(DBG_INFO, "dynamicconfig: command exited with status %d",
2334 WEXITSTATUS(status));
2342 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2346 /* should accept both names and numeric values, only numeric right now */
2347 uint8_t attrname2val(char *attrname) {
2350 val = atoi(attrname);
2351 return val > 0 && val < 256 ? val : 0;
2354 /* ATTRNAME is on the form vendor[:type].
2355 If only vendor is found, TYPE is set to 256 and 1 is returned.
2356 If type is >= 256, 1 is returned.
2357 Otherwise, 0 is returned.
2359 /* should accept both names and numeric values, only numeric right now */
2360 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2363 *vendor = atoi(attrname);
2364 s = strchr(attrname, ':');
2365 if (!s) { /* Only vendor was found. */
2369 *type = atoi(s + 1);
2373 /** Extract attributes from string NAMEVAL, create a struct tlv and
2374 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2375 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2376 * NULL if fields are missing or if conversion fails.
2378 * FIXME: Should accept both names and numeric values, only numeric
2380 struct tlv *extractattr(char *nameval, char vendor_flag) {
2382 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2386 s = strchr(nameval, ':');
2389 name = atoi(nameval);
2392 s2 = strchr(s + 1, ':');
2399 len = strlen(s + 1);
2403 if (name < 1 || name > 255)
2405 a = malloc(sizeof(struct tlv));
2409 a->v = (uint8_t *)stringcopy(s + 1, 0);
2418 a = makevendortlv(vendor, a);
2423 /* should accept both names and numeric values, only numeric right now */
2424 struct modattr *extractmodattr(char *nameval) {
2429 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2433 s = strchr(nameval, ':');
2434 name = atoi(nameval);
2435 if (!s || name < 1 || name > 255 || s[1] != '/')
2439 /* regexp, remove optional trailing / if present */
2440 if (s[strlen(s) - 1] == '/')
2441 s[strlen(s) - 1] = '\0';
2449 m = malloc(sizeof(struct modattr));
2451 debug(DBG_ERR, "malloc failed");
2456 m->replacement = stringcopy(t, 0);
2457 if (!m->replacement) {
2459 debug(DBG_ERR, "malloc failed");
2463 m->regex = malloc(sizeof(regex_t));
2465 free(m->replacement);
2467 debug(DBG_ERR, "malloc failed");
2471 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2473 free(m->replacement);
2475 debug(DBG_ERR, "failed to compile regular expression %s", s);
2482 struct rewrite *getrewrite(char *alt1, char *alt2) {
2486 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2489 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2494 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2496 struct rewrite *rewrite = NULL;
2498 uint8_t *rma = NULL;
2499 uint32_t *p, *rmva = NULL;
2500 struct list *adda = NULL, *moda = NULL;
2505 for (n = 0; rmattrs[n]; n++);
2506 rma = calloc(n + 1, sizeof(uint8_t));
2508 debugx(1, DBG_ERR, "malloc failed");
2510 for (i = 0; i < n; i++)
2511 if (!(rma[i] = attrname2val(rmattrs[i])))
2512 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2513 freegconfmstr(rmattrs);
2518 for (n = 0; rmvattrs[n]; n++);
2519 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2521 debugx(1, DBG_ERR, "malloc failed");
2523 for (p = rmva, i = 0; i < n; i++, p += 2)
2524 if (!vattrname2val(rmvattrs[i], p, p + 1))
2525 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2526 freegconfmstr(rmvattrs);
2531 adda = list_create();
2533 debugx(1, DBG_ERR, "malloc failed");
2534 for (i = 0; addattrs[i]; i++) {
2535 a = extractattr(addattrs[i], 0);
2537 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2538 if (!list_push(adda, a))
2539 debugx(1, DBG_ERR, "malloc failed");
2541 freegconfmstr(addattrs);
2546 adda = list_create();
2548 debugx(1, DBG_ERR, "malloc failed");
2549 for (i = 0; addvattrs[i]; i++) {
2550 a = extractattr(addvattrs[i], 1);
2552 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2553 if (!list_push(adda, a))
2554 debugx(1, DBG_ERR, "malloc failed");
2556 freegconfmstr(addvattrs);
2560 moda = list_create();
2562 debugx(1, DBG_ERR, "malloc failed");
2563 for (i = 0; modattrs[i]; i++) {
2564 m = extractmodattr(modattrs[i]);
2566 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2567 if (!list_push(moda, m))
2568 debugx(1, DBG_ERR, "malloc failed");
2570 freegconfmstr(modattrs);
2573 if (rma || rmva || adda || moda) {
2574 rewrite = malloc(sizeof(struct rewrite));
2576 debugx(1, DBG_ERR, "malloc failed");
2577 rewrite->removeattrs = rma;
2578 rewrite->removevendorattrs = rmva;
2579 rewrite->addattrs = adda;
2580 rewrite->modattrs = moda;
2583 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2584 debugx(1, DBG_ERR, "malloc failed");
2585 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2588 int setttlattr(struct options *opts, char *defaultattr) {
2589 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2591 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2592 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2594 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2598 void freeclsrvconf(struct clsrvconf *conf) {
2601 debug(DBG_DBG, "%s: freeing %p (%s)", __func__, conf, conf->name);
2604 freegconfmstr(conf->hostsrc);
2605 free(conf->portsrc);
2608 free(conf->matchcertattr);
2609 if (conf->certcnregex)
2610 regfree(conf->certcnregex);
2611 if (conf->certuriregex)
2612 regfree(conf->certuriregex);
2613 free(conf->confrewritein);
2614 free(conf->confrewriteout);
2615 if (conf->rewriteusername) {
2616 if (conf->rewriteusername->regex)
2617 regfree(conf->rewriteusername->regex);
2618 free(conf->rewriteusername->replacement);
2619 free(conf->rewriteusername);
2621 free(conf->dynamiclookupcommand);
2622 free(conf->rewritein);
2623 free(conf->rewriteout);
2624 if (conf->hostports)
2625 freehostports(conf->hostports);
2627 pthread_mutex_destroy(conf->lock);
2630 /* not touching ssl_ctx, clients and servers */
2634 int mergeconfstring(char **dst, char **src) {
2643 t = stringcopy(*dst, 0);
2645 debug(DBG_ERR, "malloc failed");
2653 char **mstringcopy(char **in) {
2660 for (n = 0; in[n]; n++);
2661 out = malloc((n + 1) * sizeof(char *));
2664 for (n = 0; in[n]; n++) {
2665 out[n] = stringcopy(in[n], 0);
2675 int mergeconfmstring(char ***dst, char ***src) {
2684 t = mstringcopy(*dst);
2686 debug(DBG_ERR, "malloc failed");
2694 /* assumes dst is a shallow copy */
2695 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2696 if (!mergeconfstring(&dst->name, &src->name) ||
2697 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2698 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2699 !mergeconfstring(&dst->secret, &src->secret) ||
2700 !mergeconfstring(&dst->tls, &src->tls) ||
2701 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2702 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2703 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2704 !mergeconfstring(&dst->confrewriteusername, &src->confrewriteusername) ||
2705 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand) ||
2706 !mergeconfstring(&dst->fticks_viscountry, &src->fticks_viscountry) ||
2707 !mergeconfstring(&dst->fticks_visinst, &src->fticks_visinst))
2710 dst->pdef = src->pdef;
2711 dst->statusserver = src->statusserver;
2712 dst->certnamecheck = src->certnamecheck;
2713 if (src->retryinterval != 255)
2714 dst->retryinterval = src->retryinterval;
2715 if (src->retrycount != 255)
2716 dst->retrycount = src->retrycount;
2720 /** Set *AF according to IPV4ONLY and IPV6ONLY:
2721 - If both are set, the function fails.
2722 - If exactly one is set, *AF is set accordingly.
2723 - If none is set, *AF is not affected.
2724 Return 0 on success and !0 on failure.
2725 In the case of an error, *AF is not affected. */
2726 int config_hostaf(const char *desc, int ipv4only, int ipv6only, int *af) {
2728 if (ipv4only && ipv6only) {
2729 debug(DBG_ERR, "error in block %s, at most one of IPv4Only and "
2730 "IPv6Only can be enabled", desc);
2740 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2741 struct clsrvconf *conf;
2742 char *conftype = NULL, *rewriteinalias = NULL;
2743 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2744 uint8_t ipv4only = 0, ipv6only = 0;
2746 debug(DBG_DBG, "confclient_cb called for %s", block);
2748 conf = malloc(sizeof(struct clsrvconf));
2750 debugx(1, DBG_ERR, "malloc failed");
2751 memset(conf, 0, sizeof(struct clsrvconf));
2752 conf->certnamecheck = 1;
2754 if (!getgenericconfig(
2756 "type", CONF_STR, &conftype,
2757 "host", CONF_MSTR, &conf->hostsrc,
2758 "IPv4Only", CONF_BLN, &ipv4only,
2759 "IPv6Only", CONF_BLN, &ipv6only,
2760 "secret", CONF_STR, &conf->secret,
2761 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2762 "tls", CONF_STR, &conf->tls,
2763 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2764 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2766 "DuplicateInterval", CONF_LINT, &dupinterval,
2767 "addTTL", CONF_LINT, &addttl,
2768 "rewrite", CONF_STR, &rewriteinalias,
2769 "rewriteIn", CONF_STR, &conf->confrewritein,
2770 "rewriteOut", CONF_STR, &conf->confrewriteout,
2771 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2772 #if defined(WANT_FTICKS)
2773 "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2774 "fticksVISINST", CONF_STR, &conf->fticks_visinst,
2778 debugx(1, DBG_ERR, "configuration error");
2780 conf->name = stringcopy(val, 0);
2781 if (conf->name && !conf->hostsrc) {
2782 conf->hostsrc = malloc(2 * sizeof(char *));
2783 if (conf->hostsrc) {
2784 conf->hostsrc[0] = stringcopy(val, 0);
2785 conf->hostsrc[1] = NULL;
2788 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2789 debugx(1, DBG_ERR, "malloc failed");
2792 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2793 conf->type = protoname2int(conftype);
2794 if (conf->type == 255)
2795 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2797 conf->pdef = protodefs[conf->type];
2799 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2800 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2801 conf->tlsconf = conf->tls
2802 ? tlsgettls(conf->tls, NULL)
2803 : tlsgettls("defaultClient", "default");
2805 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2806 if (conf->matchcertattr && !addmatchcertattr(conf))
2807 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2811 conf->hostaf = AF_UNSPEC;
2812 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
2813 debugx(1, DBG_ERR, "config error: ^");
2814 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
2815 debugx(1, DBG_ERR, "error in block %s: ^", block);
2817 if (dupinterval != LONG_MIN) {
2818 if (dupinterval < 0 || dupinterval > 255)
2819 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2820 conf->dupinterval = (uint8_t)dupinterval;
2822 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2824 if (addttl != LONG_MIN) {
2825 if (addttl < 1 || addttl > 255)
2826 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2827 conf->addttl = (uint8_t)addttl;
2830 if (!conf->confrewritein)
2831 conf->confrewritein = rewriteinalias;
2833 free(rewriteinalias);
2834 conf->rewritein = conf->confrewritein
2835 ? getrewrite(conf->confrewritein, NULL)
2836 : getrewrite("defaultClient", "default");
2837 if (conf->confrewriteout)
2838 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2840 if (conf->confrewriteusername) {
2841 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2842 if (!conf->rewriteusername)
2843 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2846 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2847 !resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype))
2848 debugx(1, DBG_ERR, "%s: resolve failed, exiting", __func__);
2850 if (!conf->secret) {
2851 if (!conf->pdef->secretdefault)
2852 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2853 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2855 debugx(1, DBG_ERR, "malloc failed");
2858 conf->lock = malloc(sizeof(pthread_mutex_t));
2860 debugx(1, DBG_ERR, "malloc failed");
2862 pthread_mutex_init(conf->lock, NULL);
2863 if (!list_push(clconfs, conf))
2864 debugx(1, DBG_ERR, "malloc failed");
2868 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2869 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2870 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2871 conf->tlsconf = conf->tls
2872 ? tlsgettls(conf->tls, NULL)
2873 : tlsgettls("defaultServer", "default");
2874 if (!conf->tlsconf) {
2875 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2878 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2879 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2885 if (!conf->portsrc) {
2886 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2887 if (!conf->portsrc) {
2888 debug(DBG_ERR, "malloc failed");
2893 if (conf->retryinterval == 255)
2894 conf->retryinterval = conf->pdef->retryintervaldefault;
2895 if (conf->retrycount == 255)
2896 conf->retrycount = conf->pdef->retrycountdefault;
2898 conf->rewritein = conf->confrewritein
2899 ? getrewrite(conf->confrewritein, NULL)
2900 : getrewrite("defaultServer", "default");
2901 if (conf->confrewriteout)
2902 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2904 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2905 debug(DBG_ERR, "error in block %s, failed to parse %s", block, *conf->hostsrc);
2909 if (!conf->dynamiclookupcommand &&
2910 !resolvehostports(conf->hostports, conf->hostaf,
2911 conf->pdef->socktype)) {
2912 debug(DBG_ERR, "%s: resolve failed", __func__);
2918 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2919 struct clsrvconf *conf, *resconf;
2920 char *conftype = NULL, *rewriteinalias = NULL;
2921 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2922 uint8_t ipv4only = 0, ipv6only = 0;
2924 debug(DBG_DBG, "confserver_cb called for %s", block);
2926 conf = malloc(sizeof(struct clsrvconf));
2928 debug(DBG_ERR, "malloc failed");
2931 memset(conf, 0, sizeof(struct clsrvconf));
2932 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2933 resconf = (struct clsrvconf *)arg;
2935 conf->statusserver = resconf->statusserver;
2936 conf->certnamecheck = resconf->certnamecheck;
2938 conf->certnamecheck = 1;
2940 if (!getgenericconfig(cf, block,
2941 "type", CONF_STR, &conftype,
2942 "host", CONF_MSTR, &conf->hostsrc,
2943 "IPv4Only", CONF_BLN, &ipv4only,
2944 "IPv6Only", CONF_BLN, &ipv6only,
2945 "port", CONF_STR, &conf->portsrc,
2946 "secret", CONF_STR, &conf->secret,
2947 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2948 "tls", CONF_STR, &conf->tls,
2949 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2950 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2952 "addTTL", CONF_LINT, &addttl,
2953 "rewrite", CONF_STR, &rewriteinalias,
2954 "rewriteIn", CONF_STR, &conf->confrewritein,
2955 "rewriteOut", CONF_STR, &conf->confrewriteout,
2956 "StatusServer", CONF_BLN, &conf->statusserver,
2957 "RetryInterval", CONF_LINT, &retryinterval,
2958 "RetryCount", CONF_LINT, &retrycount,
2959 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2960 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2963 debug(DBG_ERR, "configuration error");
2967 conf->name = stringcopy(val, 0);
2968 if (conf->name && !conf->hostsrc) {
2969 conf->hostsrc = malloc(2 * sizeof(char *));
2970 if (conf->hostsrc) {
2971 conf->hostsrc[0] = stringcopy(val, 0);
2972 conf->hostsrc[1] = NULL;
2975 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2976 debug(DBG_ERR, "malloc failed");
2981 debug(DBG_ERR, "error in block %s, option type missing", block);
2984 conf->type = protoname2int(conftype);
2985 if (conf->type == 255) {
2986 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2992 conf->hostaf = AF_UNSPEC;
2993 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
2994 debugx(1, DBG_ERR, "config error: ^");
2995 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
2998 conf->pdef = protodefs[conf->type];
3000 if (!conf->confrewritein)
3001 conf->confrewritein = rewriteinalias;
3003 free(rewriteinalias);
3004 rewriteinalias = NULL;
3006 if (retryinterval != LONG_MIN) {
3007 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3008 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3011 conf->retryinterval = (uint8_t)retryinterval;
3013 conf->retryinterval = 255;
3015 if (retrycount != LONG_MIN) {
3016 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3017 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3020 conf->retrycount = (uint8_t)retrycount;
3022 conf->retrycount = 255;
3024 if (addttl != LONG_MIN) {
3025 if (addttl < 1 || addttl > 255) {
3026 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3029 conf->addttl = (uint8_t)addttl;
3033 if (!mergesrvconf(resconf, conf))
3037 if (conf->dynamiclookupcommand) {
3038 free(conf->dynamiclookupcommand);
3039 conf->dynamiclookupcommand = NULL;
3043 if (resconf || !conf->dynamiclookupcommand) {
3044 if (!compileserverconfig(conf, block))
3045 return 0; /* Don't goto errexit and free resconf -- it's
3046 * not ours to free. */
3049 if (!conf->secret) {
3050 if (!conf->pdef->secretdefault) {
3051 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3054 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3055 if (!conf->secret) {
3056 debug(DBG_ERR, "malloc failed");
3064 if (!list_push(srvconfs, conf)) {
3065 debug(DBG_ERR, "malloc failed");
3072 free(rewriteinalias);
3073 freeclsrvconf(conf);
3077 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3078 char **servers = NULL, **accservers = NULL, *msg = NULL;
3079 uint8_t accresp = 0;
3081 debug(DBG_DBG, "confrealm_cb called for %s", block);
3083 if (!getgenericconfig(cf, block,
3084 "server", CONF_MSTR, &servers,
3085 "accountingServer", CONF_MSTR, &accservers,
3086 "ReplyMessage", CONF_STR, &msg,
3087 "AccountingResponse", CONF_BLN, &accresp,
3090 debugx(1, DBG_ERR, "configuration error");
3092 addrealm(realms, val, servers, accservers, msg, accresp);
3096 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3097 char **rmattrs = NULL, **rmvattrs = NULL;
3098 char **addattrs = NULL, **addvattrs = NULL;
3099 char **modattrs = NULL;
3101 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3103 if (!getgenericconfig(cf, block,
3104 "removeAttribute", CONF_MSTR, &rmattrs,
3105 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3106 "addAttribute", CONF_MSTR, &addattrs,
3107 "addVendorAttribute", CONF_MSTR, &addvattrs,
3108 "modifyAttribute", CONF_MSTR, &modattrs,
3111 debugx(1, DBG_ERR, "configuration error");
3112 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
3116 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3117 struct commonprotoopts *protoopts;
3119 protoopts = malloc(sizeof(struct commonprotoopts));
3122 memset(protoopts, 0, sizeof(struct commonprotoopts));
3123 protoopts->listenargs = listenargs;
3124 protoopts->sourcearg = sourcearg;
3125 protodefs[type]->setprotoopts(protoopts);
3129 void getmainconfig(const char *configfile) {
3130 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3131 struct gconffile *cfs;
3132 char **listenargs[RAD_PROTOCOUNT];
3133 char *sourcearg[RAD_PROTOCOUNT];
3134 #if defined(WANT_FTICKS)
3135 uint8_t *fticks_reporting_str = NULL;
3136 uint8_t *fticks_mac_str = NULL;
3137 uint8_t *fticks_key_str = NULL;
3141 cfs = openconfigfile(configfile);
3142 memset(&options, 0, sizeof(options));
3143 memset(&listenargs, 0, sizeof(listenargs));
3144 memset(&sourcearg, 0, sizeof(sourcearg));
3146 clconfs = list_create();
3148 debugx(1, DBG_ERR, "malloc failed");
3150 srvconfs = list_create();
3152 debugx(1, DBG_ERR, "malloc failed");
3154 realms = list_create();
3156 debugx(1, DBG_ERR, "malloc failed");
3158 rewriteconfs = hash_create();
3160 debugx(1, DBG_ERR, "malloc failed");
3162 if (!getgenericconfig(
3165 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3166 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3169 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3170 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3173 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3174 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3177 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3178 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3180 "PidFile", CONF_STR, &options.pidfile,
3181 "TTLAttribute", CONF_STR, &options.ttlattr,
3182 "addTTL", CONF_LINT, &addttl,
3183 "LogLevel", CONF_LINT, &loglevel,
3184 "LogDestination", CONF_STR, &options.logdestination,
3185 "LoopPrevention", CONF_BLN, &options.loopprevention,
3186 "Client", CONF_CBK, confclient_cb, NULL,
3187 "Server", CONF_CBK, confserver_cb, NULL,
3188 "Realm", CONF_CBK, confrealm_cb, NULL,
3189 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3190 "TLS", CONF_CBK, conftls_cb, NULL,
3192 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3193 #if defined(WANT_FTICKS)
3194 "FTicksReporting", CONF_STR, &fticks_reporting_str,
3195 "FTicksMAC", CONF_STR, &fticks_mac_str,
3196 "FTicksKey", CONF_STR, &fticks_key_str,
3197 "FTicksSyslogFacility", CONF_STR, &options.ftickssyslogfacility,
3199 "IPv4Only", CONF_BLN, &options.ipv4only,
3200 "IPv6Only", CONF_BLN, &options.ipv6only,
3203 debugx(1, DBG_ERR, "configuration error");
3205 if (loglevel != LONG_MIN) {
3206 if (loglevel < 1 || loglevel > 5)
3207 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3208 options.loglevel = (uint8_t)loglevel;
3210 if (addttl != LONG_MIN) {
3211 if (addttl < 1 || addttl > 255)
3212 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3213 options.addttl = (uint8_t)addttl;
3215 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3216 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3218 #if defined(WANT_FTICKS)
3219 fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3223 for (i = 0; i < RAD_PROTOCOUNT; i++)
3224 if (listenargs[i] || sourcearg[i])
3225 setprotoopts(i, listenargs[i], sourcearg[i]);
3228 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3231 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3234 *configfile = optarg;
3237 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3238 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3239 *loglevel = *optarg - '0';
3251 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3252 debug(DBG_ERR, "This binary was built with support for the following transports:");
3254 debug(DBG_ERR, " UDP");
3257 debug(DBG_ERR, " TCP");
3260 debug(DBG_ERR, " TLS");
3263 debug(DBG_ERR, " DTLS");
3270 if (!(argc - optind))
3274 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3278 int daemon(int a, int b) {
3286 for (i = 0; i < 3; i++) {
3288 open("/dev/null", O_RDWR);
3294 void *sighandler(void *arg) {
3299 sigemptyset(&sigset);
3300 sigaddset(&sigset, SIGHUP);
3301 sigaddset(&sigset, SIGPIPE);
3302 sigwait(&sigset, &sig);
3305 /* completely ignoring this */
3308 debug(DBG_INFO, "sighandler: got SIGHUP");
3312 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3315 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3320 int createpidfile(const char *pidfile) {
3322 FILE *f = fopen(pidfile, "w");
3324 r = fprintf(f, "%ld\n", (long) getpid());
3325 return f && !fclose(f) && r >= 0;
3328 int radsecproxy_main(int argc, char **argv) {
3331 struct list_node *entry;
3332 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3333 char *configfile = NULL, *pidfile = NULL;
3334 struct clsrvconf *srvconf;
3337 debug_init("radsecproxy");
3338 debug_set_level(DEBUG_LEVEL);
3340 for (i = 0; i < RAD_PROTOCOUNT; i++)
3341 protodefs[i] = protoinits[i](i);
3343 /* needed even if no TLS/DTLS transport */
3346 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3348 debug_set_level(loglevel);
3349 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3351 options.loglevel = loglevel;
3352 else if (options.loglevel)
3353 debug_set_level(options.loglevel);
3355 debug_set_destination(options.logdestination
3356 ? options.logdestination
3357 : "x-syslog:///", LOG_TYPE_DEBUG);
3358 #if defined(WANT_FTICKS)
3359 if (options.ftickssyslogfacility) {
3360 debug_set_destination(options.ftickssyslogfacility,
3362 free(options.ftickssyslogfacility);
3366 free(options.logdestination);
3368 if (!list_first(clconfs))
3369 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3370 if (!list_first(realms))
3371 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3374 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3376 if (!foreground && (daemon(0, 0) < 0))
3377 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3379 debug_timestamp_on();
3380 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3382 pidfile = options.pidfile;
3383 if (pidfile && !createpidfile(pidfile))
3384 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3386 sigemptyset(&sigset);
3387 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3388 sigaddset(&sigset, SIGHUP);
3389 sigaddset(&sigset, SIGPIPE);
3390 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3391 pthread_create(&sigth, NULL, sighandler, NULL);
3393 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3394 srvconf = (struct clsrvconf *)entry->data;
3395 if (srvconf->dynamiclookupcommand)
3397 if (!addserver(srvconf))
3398 debugx(1, DBG_ERR, "failed to add server");
3399 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3400 (void *)(srvconf->servers)))
3401 debugx(1, DBG_ERR, "pthread_create failed");
3404 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3407 if (protodefs[i]->initextra)
3408 protodefs[i]->initextra();
3409 if (find_clconf_type(i, NULL))
3413 /* just hang around doing nothing, anything to do here? */
3418 /* Local Variables: */
3419 /* c-file-style: "stroustrup" */