1 /* Copyright (c) 2006-2009, Stig Venaas, UNINETT AS.
2 * Copyright (c) 2010, UNINETT AS, NORDUnet A/S.
3 * Copyright (c) 2010-2012, NORDUnet A/S. */
4 /* See LICENSE for licensing information. */
6 /* Code contributions from:
8 * Arne Schwabe <schwabe at uni-paderborn.de>
9 * Maja Wolniewicz <mgw@umk.pl>
10 * Simon Leinen <simon.leinen@switch.ch>
11 * Stefan Winter <stefan.winter@restena.lu>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 * May segfault when dtls connections go down? More testing needed
39 * Remove expired stuff from clients request list?
40 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
41 * Useful for TCP accounting? Now we require separate server config for alt port
45 #include <sys/socket.h>
46 #include <netinet/in.h>
55 #include <sys/types.h>
58 #include <arpa/inet.h>
64 #include <openssl/ssl.h>
65 #include <openssl/rand.h>
66 #include <openssl/err.h>
67 #include <openssl/md5.h>
72 #include "radsecproxy.h"
77 #if defined(WANT_FTICKS)
81 static struct options options;
82 static struct list *clconfs, *srvconfs;
83 static struct list *realms;
84 static struct hash *rewriteconfs;
86 static pthread_mutex_t *ssl_locks = NULL;
87 static long *ssl_lock_count;
90 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
92 /* minimum required declarations to avoid reordering code */
93 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
94 int dynamicconfig(struct server *server);
95 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
96 void freerealm(struct realm *realm);
97 void freeclsrvconf(struct clsrvconf *conf);
98 void freerq(struct request *rq);
99 void freerqoutdata(struct rqout *rqout);
100 void rmclientrq(struct request *rq, uint8_t id);
102 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
104 uint8_t protoname2int(const char *name) {
107 for (i = 0; i < RAD_PROTOCOUNT; i++)
108 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
113 /* callbacks for making OpenSSL thread safe */
114 unsigned long ssl_thread_id() {
115 return (unsigned long)pthread_self();
118 void ssl_locking_callback(int mode, int type, const char *file, int line) {
119 if (mode & CRYPTO_LOCK) {
120 pthread_mutex_lock(&ssl_locks[type]);
121 ssl_lock_count[type]++;
123 pthread_mutex_unlock(&ssl_locks[type]);
126 /* returns 1 if the len first bits are equal, else 0 */
127 int prefixmatch(void *a1, void *a2, uint8_t len) {
128 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
129 uint8_t r, l = len / 8;
130 if (l && memcmp(a1, a2, l))
135 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
138 /* returns next config with matching address, or NULL */
139 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
140 struct list_node *entry;
141 struct clsrvconf *conf;
143 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
144 conf = (struct clsrvconf *)entry->data;
145 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
154 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
155 return find_conf(type, addr, clconfs, cur, 0);
158 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
159 return find_conf(type, addr, srvconfs, cur, 1);
162 /* returns next config of given type, or NULL */
163 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
164 struct list_node *entry;
165 struct clsrvconf *conf;
167 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
168 conf = (struct clsrvconf *)entry->data;
169 if (conf->type == type) {
178 struct gqueue *newqueue() {
181 q = malloc(sizeof(struct gqueue));
183 debugx(1, DBG_ERR, "malloc failed");
184 q->entries = list_create();
186 debugx(1, DBG_ERR, "malloc failed");
187 pthread_mutex_init(&q->mutex, NULL);
188 pthread_cond_init(&q->cond, NULL);
192 void removequeue(struct gqueue *q) {
193 struct list_node *entry;
197 pthread_mutex_lock(&q->mutex);
198 for (entry = list_first(q->entries); entry; entry = list_next(entry))
199 freerq((struct request *)entry);
200 list_destroy(q->entries);
201 pthread_cond_destroy(&q->cond);
202 pthread_mutex_unlock(&q->mutex);
203 pthread_mutex_destroy(&q->mutex);
207 void freebios(struct gqueue *q) {
210 pthread_mutex_lock(&q->mutex);
211 while ((bio = (BIO *)list_shift(q->entries)))
213 pthread_mutex_unlock(&q->mutex);
217 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
218 struct client *new = malloc(sizeof(struct client));
221 debug(DBG_ERR, "malloc failed");
226 pthread_mutex_lock(conf->lock);
227 if (!conf->clients) {
228 conf->clients = list_create();
229 if (!conf->clients) {
231 pthread_mutex_unlock(conf->lock);
232 debug(DBG_ERR, "malloc failed");
237 memset(new, 0, sizeof(struct client));
239 if (conf->pdef->addclient)
240 conf->pdef->addclient(new);
242 new->replyq = newqueue();
243 list_push(conf->clients, new);
245 pthread_mutex_unlock(conf->lock);
249 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
250 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
253 pthread_mutex_lock(&lock);
255 pthread_mutex_unlock(&lock);
258 void removeclientrqs(struct client *client) {
263 removeclientrqs_sendrq_freeserver_lock(1);
264 for (i = 0; i < MAX_REQUESTS; i++) {
269 rqout = rq->to->requests + rq->newid;
270 pthread_mutex_lock(rqout->lock);
271 if (rqout->rq == rq) /* still pointing to our request */
272 freerqoutdata(rqout);
273 pthread_mutex_unlock(rqout->lock);
277 removeclientrqs_sendrq_freeserver_lock(0);
280 void removelockedclient(struct client *client) {
281 struct clsrvconf *conf;
285 removeclientrqs(client);
286 removequeue(client->replyq);
287 list_removedata(conf->clients, client);
293 void removeclient(struct client *client) {
294 struct clsrvconf *conf;
300 pthread_mutex_lock(conf->lock);
301 removelockedclient(client);
302 pthread_mutex_unlock(conf->lock);
305 void freeserver(struct server *server, uint8_t destroymutex) {
306 struct rqout *rqout, *end;
311 removeclientrqs_sendrq_freeserver_lock(1);
312 if (server->requests) {
313 rqout = server->requests;
314 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
316 rqout->rq->to = NULL;
317 freerqoutdata(rqout);
318 pthread_mutex_destroy(rqout->lock);
321 free(server->requests);
324 freebios(server->rbios);
325 free(server->dynamiclookuparg);
327 #if defined ENABLE_EXPERIMENTAL_DYNDISC
328 if (server->sock >= 0)
331 SSL_free(server->ssl);
334 pthread_mutex_destroy(&server->lock);
335 pthread_cond_destroy(&server->newrq_cond);
336 pthread_mutex_destroy(&server->newrq_mutex);
338 removeclientrqs_sendrq_freeserver_lock(0);
342 int addserver(struct clsrvconf *conf) {
346 debug(DBG_ERR, "addserver: currently works with just one server per conf");
349 conf->servers = malloc(sizeof(struct server));
350 if (!conf->servers) {
351 debug(DBG_ERR, "malloc failed");
354 memset(conf->servers, 0, sizeof(struct server));
355 conf->servers->conf = conf;
358 if (conf->type == RAD_DTLS)
359 conf->servers->rbios = newqueue();
361 conf->pdef->setsrcres();
363 conf->servers->sock = -1;
364 if (conf->pdef->addserverextra)
365 conf->pdef->addserverextra(conf);
367 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
368 if (!conf->servers->requests) {
369 debug(DBG_ERR, "malloc failed");
372 for (i = 0; i < MAX_REQUESTS; i++) {
373 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
374 if (!conf->servers->requests[i].lock) {
375 debug(DBG_ERR, "malloc failed");
378 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
379 debugerrno(errno, DBG_ERR, "mutex init failed");
380 free(conf->servers->requests[i].lock);
381 conf->servers->requests[i].lock = NULL;
385 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
386 debugerrno(errno, DBG_ERR, "mutex init failed");
389 conf->servers->newrq = 0;
390 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
391 debugerrno(errno, DBG_ERR, "mutex init failed");
392 pthread_mutex_destroy(&conf->servers->lock);
395 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
396 debugerrno(errno, DBG_ERR, "mutex init failed");
397 pthread_mutex_destroy(&conf->servers->newrq_mutex);
398 pthread_mutex_destroy(&conf->servers->lock);
405 freeserver(conf->servers, 0);
406 conf->servers = NULL;
410 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
412 if (ATTRTYPE(attrs) == type)
414 length -= ATTRLEN(attrs);
415 attrs += ATTRLEN(attrs);
420 struct request *newrqref(struct request *rq) {
426 void freerq(struct request *rq) {
429 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
432 if (rq->origusername)
433 free(rq->origusername);
439 radmsg_free(rq->msg);
443 void freerqoutdata(struct rqout *rqout) {
447 if (rqout->rq->buf) {
448 free(rqout->rq->buf);
449 rqout->rq->buf = NULL;
455 memset(&rqout->expiry, 0, sizeof(struct timeval));
458 void sendrq(struct request *rq) {
462 removeclientrqs_sendrq_freeserver_lock(1);
467 start = to->conf->statusserver ? 1 : 0;
468 pthread_mutex_lock(&to->newrq_mutex);
469 if (start && rq->msg->code == RAD_Status_Server) {
470 pthread_mutex_lock(to->requests[0].lock);
471 if (to->requests[0].rq) {
472 pthread_mutex_unlock(to->requests[0].lock);
473 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
480 /* might simplify if only try nextid, might be ok */
481 for (i = to->nextid; i < MAX_REQUESTS; i++) {
482 if (!to->requests[i].rq) {
483 pthread_mutex_lock(to->requests[i].lock);
484 if (!to->requests[i].rq)
486 pthread_mutex_unlock(to->requests[i].lock);
489 if (i == MAX_REQUESTS) {
490 for (i = start; i < to->nextid; i++) {
491 if (!to->requests[i].rq) {
492 pthread_mutex_lock(to->requests[i].lock);
493 if (!to->requests[i].rq)
495 pthread_mutex_unlock(to->requests[i].lock);
498 if (i == to->nextid) {
499 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
504 rq->newid = (uint8_t)i;
505 rq->msg->id = (uint8_t)i;
506 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
508 pthread_mutex_unlock(to->requests[i].lock);
509 debug(DBG_ERR, "sendrq: radmsg2buf failed");
513 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
514 to->requests[i].rq = rq;
515 pthread_mutex_unlock(to->requests[i].lock);
516 if (i >= start) /* i is not reserved for statusserver */
521 debug(DBG_DBG, "sendrq: signalling client writer");
522 pthread_cond_signal(&to->newrq_cond);
525 pthread_mutex_unlock(&to->newrq_mutex);
526 removeclientrqs_sendrq_freeserver_lock(0);
531 rmclientrq(rq, rq->msg->id);
533 pthread_mutex_unlock(&to->newrq_mutex);
534 removeclientrqs_sendrq_freeserver_lock(0);
537 void sendreply(struct request *rq) {
539 struct client *to = rq->from;
542 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
543 radmsg_free(rq->msg);
547 debug(DBG_ERR, "sendreply: radmsg2buf failed");
551 pthread_mutex_lock(&to->replyq->mutex);
552 first = list_first(to->replyq->entries) == NULL;
554 if (!list_push(to->replyq->entries, rq)) {
555 pthread_mutex_unlock(&to->replyq->mutex);
557 debug(DBG_ERR, "sendreply: malloc failed");
562 debug(DBG_DBG, "signalling server writer");
563 pthread_cond_signal(&to->replyq->cond);
565 pthread_mutex_unlock(&to->replyq->mutex);
568 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
569 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
570 static unsigned char first = 1;
571 static EVP_MD_CTX mdctx;
572 unsigned char hash[EVP_MAX_MD_SIZE], *input;
574 uint8_t i, offset = 0, out[128];
576 pthread_mutex_lock(&lock);
578 EVP_MD_CTX_init(&mdctx);
584 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
585 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
586 !EVP_DigestUpdate(&mdctx, input, 16) ||
587 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
589 pthread_mutex_unlock(&lock);
592 for (i = 0; i < 16; i++)
593 out[offset + i] = hash[i] ^ in[offset + i];
595 input = out + offset;
602 memcpy(in, out, len);
603 pthread_mutex_unlock(&lock);
607 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
608 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
609 static unsigned char first = 1;
610 static EVP_MD_CTX mdctx;
611 unsigned char hash[EVP_MAX_MD_SIZE];
615 pthread_mutex_lock(&lock);
617 EVP_MD_CTX_init(&mdctx);
622 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
623 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
624 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
627 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
628 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
629 !EVP_DigestUpdate(&mdctx, auth, 16) ||
630 !EVP_DigestUpdate(&mdctx, salt, 2) ||
631 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
632 pthread_mutex_unlock(&lock);
637 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
640 for (i = 0; i < 16; i++)
643 for (offset = 16; offset < len; offset += 16) {
645 printf("text + offset - 16 c(%d): ", offset / 16);
646 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
648 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
649 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
650 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
651 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
653 pthread_mutex_unlock(&lock);
657 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
660 for (i = 0; i < 16; i++)
661 text[offset + i] ^= hash[i];
665 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
668 pthread_mutex_unlock(&lock);
672 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
673 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
674 static unsigned char first = 1;
675 static EVP_MD_CTX mdctx;
676 unsigned char hash[EVP_MAX_MD_SIZE];
681 pthread_mutex_lock(&lock);
683 EVP_MD_CTX_init(&mdctx);
688 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
689 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
690 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
693 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
694 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
695 !EVP_DigestUpdate(&mdctx, auth, 16) ||
696 !EVP_DigestUpdate(&mdctx, salt, 2) ||
697 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
698 pthread_mutex_unlock(&lock);
703 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
706 for (i = 0; i < 16; i++)
707 plain[i] = text[i] ^ hash[i];
709 for (offset = 16; offset < len; offset += 16) {
711 printf("text + offset - 16 c(%d): ", offset / 16);
712 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
714 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
715 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
716 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
717 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
719 pthread_mutex_unlock(&lock);
723 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
726 for (i = 0; i < 16; i++)
727 plain[offset + i] = text[offset + i] ^ hash[i];
730 memcpy(text, plain, len);
732 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
735 pthread_mutex_unlock(&lock);
739 struct realm *newrealmref(struct realm *r) {
745 /* returns with lock on realm */
746 struct realm *id2realm(struct list *realmlist, char *id) {
747 struct list_node *entry;
748 struct realm *realm, *subrealm;
750 /* need to do locking for subrealms and check subrealm timers */
751 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
752 realm = (struct realm *)entry->data;
753 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
754 pthread_mutex_lock(&realm->mutex);
755 if (realm->subrealms) {
756 subrealm = id2realm(realm->subrealms, id);
758 pthread_mutex_unlock(&realm->mutex);
762 return newrealmref(realm);
768 int hasdynamicserver(struct list *srvconfs) {
769 struct list_node *entry;
771 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
772 #if defined ENABLE_EXPERIMENTAL_DYNDISC
773 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand
774 || ((struct clsrvconf *)entry->data)->servers->in_use)
776 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
782 /* helper function, only used by removeserversubrealms() */
783 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
784 struct list_node *entry, *entry2;
787 for (entry = list_first(realmlist); entry;) {
788 realm = newrealmref((struct realm *)entry->data);
789 pthread_mutex_lock(&realm->mutex);
790 entry = list_next(entry);
792 if (realm->srvconfs) {
793 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
794 if (entry2->data == srv)
796 list_removedata(realm->srvconfs, srv);
798 if (realm->accsrvconfs) {
799 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
800 if (entry2->data == srv)
802 list_removedata(realm->accsrvconfs, srv);
805 /* remove subrealm if no dynamic servers left */
806 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
807 while (list_shift(realm->srvconfs))
809 list_destroy(realm->srvconfs);
810 realm->srvconfs = NULL;
811 while (list_shift(realm->accsrvconfs))
813 list_destroy(realm->accsrvconfs);
814 realm->accsrvconfs = NULL;
815 list_removedata(realmlist, realm);
817 pthread_mutex_unlock(&realm->mutex);
822 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
823 struct list_node *entry;
826 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
827 realm = (struct realm *)entry->data;
828 pthread_mutex_lock(&realm->mutex);
829 if (realm->subrealms) {
830 _internal_removeserversubrealms(realm->subrealms, srv);
831 if (!list_first(realm->subrealms)) {
832 list_destroy(realm->subrealms);
833 realm->subrealms = NULL;
836 pthread_mutex_unlock(&realm->mutex);
840 int attrvalidate(unsigned char *attrs, int length) {
842 if (ATTRLEN(attrs) < 2) {
843 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
846 length -= ATTRLEN(attrs);
848 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
851 attrs += ATTRLEN(attrs);
854 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
858 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
859 if (len < 16 || len > 128 || len % 16) {
860 debug(DBG_WARN, "pwdrecrypt: invalid password length");
864 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
865 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
869 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
871 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
872 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
878 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
881 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
882 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
885 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
886 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
892 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
893 char *oldsecret, char *newsecret) {
896 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
897 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
898 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
904 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
908 for (; attrs[0]; attrs += 2)
909 if (attrs[0] == vendor && attrs[1] == subattr)
914 /* returns 1 if entire element is to be removed, else 0 */
915 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
916 uint8_t alen, sublen;
920 if (!removevendorattrs)
923 memcpy(&vendor, attr->v, 4);
924 vendor = ntohl(vendor);
925 while (*removevendorattrs && *removevendorattrs != vendor)
926 removevendorattrs += 2;
927 if (!*removevendorattrs)
930 if (findvendorsubattr(removevendorattrs, vendor, 256))
931 return 1; /* remove entire vendor attribute */
933 sublen = attr->l - 4;
934 subattrs = attr->v + 4;
936 if (!attrvalidate(subattrs, sublen)) {
937 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
942 alen = ATTRLEN(subattrs);
944 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
945 memmove(subattrs, subattrs + alen, sublen);
953 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
954 struct list_node *n, *p;
958 n = list_first(msg->attrs);
960 attr = (struct tlv *)n->data;
961 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
962 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
963 list_removedata(msg->attrs, attr);
965 n = p ? list_next(p) : list_first(msg->attrs);
973 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
977 for (n = list_first(addattrs); n; n = list_next(n)) {
978 a = copytlv((struct tlv *)n->data);
981 if (!radmsg_add(msg, a)) {
989 int resizeattr(struct tlv *attr, uint8_t newlen) {
992 if (newlen != attr->l) {
993 newv = realloc(attr->v, newlen);
1002 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1003 size_t nmatch = 10, reslen = 0, start = 0;
1004 regmatch_t pmatch[10], *pfield;
1008 in = stringcopy((char *)attr->v, attr->l);
1012 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1017 out = modattr->replacement;
1019 for (i = start; out[i]; i++) {
1020 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1021 pfield = &pmatch[out[i + 1] - '0'];
1022 if (pfield->rm_so >= 0) {
1023 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1029 reslen += i - start;
1031 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1036 if (!resizeattr(attr, reslen)) {
1043 for (i = start; out[i]; i++) {
1044 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1045 pfield = &pmatch[out[i + 1] - '0'];
1046 if (pfield->rm_so >= 0) {
1047 memcpy(attr->v + reslen, out + start, i - start);
1048 reslen += i - start;
1049 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1050 reslen += pfield->rm_eo - pfield->rm_so;
1057 memcpy(attr->v + reslen, out + start, i - start);
1061 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1062 struct list_node *n, *m;
1064 for (n = list_first(msg->attrs); n; n = list_next(n))
1065 for (m = list_first(modattrs); m; m = list_next(m))
1066 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1067 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1072 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1073 int rv = 1; /* Success. */
1076 if (rewrite->removeattrs || rewrite->removevendorattrs)
1077 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1078 if (rewrite->modattrs)
1079 if (!dorewritemod(msg, rewrite->modattrs))
1081 if (rewrite->addattrs)
1082 if (!dorewriteadd(msg, rewrite->addattrs))
1088 int rewriteusername(struct request *rq, struct tlv *attr) {
1089 char *orig = (char *)tlv2str(attr);
1090 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1094 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1095 rq->origusername = (char *)orig;
1101 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1102 * all is well with the new tlv, i.e. if the function returns
1105 makevendortlv(uint32_t vendor, struct tlv *attr)
1107 struct tlv *newtlv = NULL;
1115 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1116 memcpy(v, &vendor, 4);
1117 tlv2buf(v + 4, attr);
1118 v[5] += 2; /* Vendor length increased for type and length fields. */
1119 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1128 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1130 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1133 vattr = makevendortlv(vendor, attr);
1138 if (!radmsg_add(msg, vattr)) {
1145 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1152 if (attrtype[1] == 256) { /* not vendor */
1153 attr = maketlv(attrtype[0], 4, ttl);
1154 if (attr && !radmsg_add(msg, attr))
1157 attr = maketlv(attrtype[1], 4, ttl);
1159 addvendorattr(msg, attrtype[0], attr);
1163 int decttl(uint8_t l, uint8_t *v) {
1170 while (i >= 0 && !v[i])
1174 for (i--; i >= 0 && !v[i]; i--);
1183 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1184 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1185 uint8_t alen, *subattrs;
1187 struct list_node *node;
1191 if (attrtype[1] == 256) { /* not vendor */
1192 attr = radmsg_gettype(msg, attrtype[0]);
1194 return decttl(attr->l, attr->v);
1196 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1197 attr = (struct tlv *)node->data;
1198 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1200 memcpy(&vendor, attr->v, 4);
1201 if (ntohl(vendor) != attrtype[0])
1203 sublen = attr->l - 4;
1204 subattrs = attr->v + 4;
1205 if (!attrvalidate(subattrs, sublen))
1207 while (sublen > 1) {
1208 if (ATTRTYPE(subattrs) == attrtype[1])
1209 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1210 alen = ATTRLEN(subattrs);
1218 const char *radmsgtype2string(uint8_t code) {
1219 static const char *rad_msg_names[] = {
1220 "", "Access-Request", "Access-Accept", "Access-Reject",
1221 "Accounting-Request", "Accounting-Response", "", "",
1222 "", "", "", "Access-Challenge",
1223 "Status-Server", "Status-Client"
1225 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1228 void char2hex(char *h, unsigned char c) {
1229 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1230 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1231 h[0] = hexdigits[c / 16];
1232 h[1] = hexdigits[c % 16];
1236 uint8_t *radattr2ascii(struct tlv *attr) {
1244 for (i = 0; i < attr->l; i++)
1245 if (attr->v[i] < 32 || attr->v[i] > 126)
1248 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1255 for (i = 0; i < attr->l; i++)
1256 if (attr->v[i] < 32 || attr->v[i] > 126) {
1258 char2hex((char *)d, attr->v[i]);
1266 void acclog(struct radmsg *msg, struct client *from) {
1270 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1272 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1275 username = radattr2ascii(attr);
1277 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1283 void respond(struct request *rq, uint8_t code, char *message) {
1287 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1289 debug(DBG_ERR, "respond: malloc failed");
1292 if (message && *message) {
1293 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1294 if (!attr || !radmsg_add(msg, attr)) {
1297 debug(DBG_ERR, "respond: malloc failed");
1302 radmsg_free(rq->msg);
1304 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1305 sendreply(newrqref(rq));
1308 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1309 struct list_node *entry;
1310 struct clsrvconf *server, *best = NULL, *first = NULL;
1312 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1313 server = (struct clsrvconf *)entry->data;
1314 if (!server->servers)
1316 if (server->servers->dynfailing)
1320 if (!server->servers->connectionok && !server->servers->dynstartup)
1322 if (!server->servers->lostrqs)
1328 if (server->servers->lostrqs < best->servers->lostrqs)
1331 return best ? best : first;
1334 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1335 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1336 struct clsrvconf *srvconf;
1337 struct realm *subrealm;
1338 struct server *server = NULL;
1339 char *id = (char *)tlv2str(username);
1343 /* returns with lock on realm */
1344 *realm = id2realm(realms, id);
1347 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1348 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1349 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1350 subrealm = adddynamicrealmserver(*realm, id);
1352 pthread_mutex_lock(&subrealm->mutex);
1353 pthread_mutex_unlock(&(*realm)->mutex);
1356 debug(DBG_DBG, "added realm: %s", (*realm)->name);
1357 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1358 debug(DBG_DBG, "found conf for new realm: %s", srvconf->name);
1362 debug(DBG_DBG, "found matching conf: %s", srvconf->name);
1363 server = srvconf->servers;
1372 struct request *newrequest() {
1375 rq = malloc(sizeof(struct request));
1377 debug(DBG_ERR, "newrequest: malloc failed");
1380 memset(rq, 0, sizeof(struct request));
1382 gettimeofday(&rq->created, NULL);
1386 int addclientrq(struct request *rq) {
1390 r = rq->from->rqs[rq->rqid];
1392 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1393 gettimeofday(&now, NULL);
1394 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1396 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1397 sendreply(newrqref(r));
1399 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1405 rq->from->rqs[rq->rqid] = newrqref(rq);
1409 void rmclientrq(struct request *rq, uint8_t id) {
1412 r = rq->from->rqs[id];
1415 rq->from->rqs[id] = NULL;
1419 /* returns 0 if validation/authentication fails, else 1 */
1420 int radsrv(struct request *rq) {
1421 struct radmsg *msg = NULL;
1423 uint8_t *userascii = NULL;
1424 struct realm *realm = NULL;
1425 struct server *to = NULL;
1426 struct client *from = rq->from;
1429 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1434 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1441 memcpy(rq->rqauth, msg->auth, 16);
1443 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1444 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1445 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1449 if (!addclientrq(rq))
1452 if (msg->code == RAD_Status_Server) {
1453 respond(rq, RAD_Access_Accept, NULL);
1457 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1459 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1462 ttlres = checkttl(msg, options.ttlattrtype);
1464 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1468 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1470 if (msg->code == RAD_Accounting_Request) {
1472 respond(rq, RAD_Accounting_Response, NULL);
1474 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1478 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1479 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1483 userascii = radattr2ascii(attr);
1486 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1488 /* will return with lock on the realm */
1489 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1491 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1496 if (realm->message && msg->code == RAD_Access_Request) {
1497 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1498 respond(rq, RAD_Access_Reject, realm->message);
1499 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1501 respond(rq, RAD_Accounting_Response, NULL);
1506 if ((to->conf->loopprevention == 1
1507 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1508 && !strcmp(from->conf->name, to->conf->name)) {
1509 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1510 from->conf->name, addr2string(from->addr), to->conf->name);
1514 if (msg->code == RAD_Accounting_Request)
1515 memset(msg->auth, 0, 16);
1516 else if (!RAND_bytes(msg->auth, 16)) {
1517 debug(DBG_WARN, "radsrv: failed to generate random auth");
1522 printfchars(NULL, "auth", "%02x ", auth, 16);
1525 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1527 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1528 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1532 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1534 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1535 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1539 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1542 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1543 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1548 pthread_mutex_unlock(&realm->mutex);
1553 rmclientrq(rq, msg->id);
1558 pthread_mutex_unlock(&realm->mutex);
1564 void replyh(struct server *server, unsigned char *buf) {
1565 struct client *from;
1566 struct rqout *rqout;
1568 unsigned char *subattrs;
1569 uint8_t *username, *stationid, *replymsg;
1570 struct radmsg *msg = NULL;
1572 struct list_node *node;
1574 server->connectionok = 1;
1575 server->lostrqs = 0;
1577 rqout = server->requests + buf[1];
1578 pthread_mutex_lock(rqout->lock);
1579 if (!rqout->tries) {
1582 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1586 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1590 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1593 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1594 && msg->code != RAD_Accounting_Response) {
1595 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1598 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1600 gettimeofday(&server->lastrcv, NULL);
1602 if (rqout->rq->msg->code == RAD_Status_Server) {
1603 freerqoutdata(rqout);
1604 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1608 gettimeofday(&server->lastreply, NULL);
1609 from = rqout->rq->from;
1611 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1612 debug(DBG_INFO, "replyh: rewritein failed");
1616 ttlres = checkttl(msg, options.ttlattrtype);
1618 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1623 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1624 attr = (struct tlv *)node->data;
1625 if (attr->t != RAD_Attr_Vendor_Specific)
1629 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1632 sublen = attr->l - 4;
1633 subattrs = attr->v + 4;
1634 if (!attrvalidate(subattrs, sublen) ||
1635 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1636 rqout->rq, server->conf->secret, from->conf->secret) ||
1637 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1638 rqout->rq, server->conf->secret, from->conf->secret))
1642 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1646 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1647 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1649 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1650 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1654 "%s for user %s stationid %s from %s (%s) to %s (%s)",
1655 radmsgtype2string(msg->code), username, stationid,
1656 server->conf->name, replymsg, from->conf->name,
1657 addr2string(from->addr));
1661 "%s for user %s stationid %s from %s to %s (%s)",
1662 radmsgtype2string(msg->code), username, stationid,
1663 server->conf->name, from->conf->name,
1664 addr2string(from->addr));
1668 debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1669 radmsgtype2string(msg->code), username,
1670 server->conf->name, replymsg, from->conf->name,
1671 addr2string(from->addr));
1674 debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1675 radmsgtype2string(msg->code), username,
1676 server->conf->name, from->conf->name,
1677 addr2string(from->addr));
1683 #if defined(WANT_FTICKS)
1684 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject)
1685 if (options.fticks_reporting && from->conf->fticks_viscountry != NULL)
1686 fticks_log(&options, from, msg, rqout);
1689 msg->id = (char)rqout->rq->rqid;
1690 memcpy(msg->auth, rqout->rq->rqauth, 16);
1693 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1696 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1697 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1698 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1701 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1704 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1705 debug(DBG_WARN, "replyh: rewriteout failed");
1709 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1710 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1712 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1713 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1715 radmsg_free(rqout->rq->msg);
1716 rqout->rq->msg = msg;
1717 sendreply(newrqref(rqout->rq));
1718 freerqoutdata(rqout);
1719 pthread_mutex_unlock(rqout->lock);
1724 pthread_mutex_unlock(rqout->lock);
1728 struct request *createstatsrvrq() {
1735 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1738 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1741 if (!radmsg_add(rq->msg, attr)) {
1752 /* code for removing state not finished */
1753 void *clientwr(void *arg) {
1754 struct server *server = (struct server *)arg;
1755 struct rqout *rqout = NULL;
1756 pthread_t clientrdth;
1757 int i, dynconffail = 0;
1760 struct timeval now, laststatsrv;
1761 struct timespec timeout;
1762 struct request *statsrvrq;
1763 struct clsrvconf *conf;
1765 conf = server->conf;
1769 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1771 server->dynstartup = 0;
1772 server->dynfailing = 1;
1773 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1774 pthread_mutex_unlock(&server->lock);
1776 debug(DBG_WARN, "%s: dynamicconfig(%s) failed, sleeping %ds",
1777 __func__, server->conf->name, ZZZ);
1781 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1782 pthread_mutex_unlock(&server->lock);
1784 /* FIXME: Is resolving not always done by compileserverconfig(),
1785 * either as part of static configuration setup or by
1786 * dynamicconfig() above? */
1787 if (!resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype)) {
1788 debug(DBG_WARN, "%s: resolve failed, sleeping %ds", __func__, ZZZ);
1793 memset(&timeout, 0, sizeof(struct timespec));
1795 if (conf->statusserver) {
1796 gettimeofday(&server->lastrcv, NULL);
1797 gettimeofday(&laststatsrv, NULL);
1800 if (conf->pdef->connecter) {
1801 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1802 if (server->dynamiclookuparg) {
1803 server->dynstartup = 0;
1804 server->dynfailing = 1;
1805 debug(DBG_WARN, "%s: connect failed, sleeping %ds",
1811 server->connectionok = 1;
1812 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1815 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1816 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1820 server->connectionok = 1;
1821 server->dynstartup = 0;
1824 pthread_mutex_lock(&server->newrq_mutex);
1825 if (!server->newrq) {
1826 gettimeofday(&now, NULL);
1827 /* random 0-7 seconds */
1828 RAND_bytes(&rnd, 1);
1830 if (conf->statusserver) {
1831 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1832 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1834 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1835 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1837 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1838 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1841 if (timeout.tv_sec > now.tv_sec)
1842 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1844 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1847 if (server->newrq) {
1848 debug(DBG_DBG, "clientwr: got new request");
1853 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1855 pthread_mutex_unlock(&server->newrq_mutex);
1857 for (i = 0; i < MAX_REQUESTS; i++) {
1858 if (server->clientrdgone) {
1859 pthread_join(clientrdth, NULL);
1863 for (; i < MAX_REQUESTS; i++) {
1864 rqout = server->requests + i;
1866 pthread_mutex_lock(rqout->lock);
1869 pthread_mutex_unlock(rqout->lock);
1873 if (i == MAX_REQUESTS)
1876 gettimeofday(&now, NULL);
1877 if (now.tv_sec < rqout->expiry.tv_sec) {
1878 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1879 timeout.tv_sec = rqout->expiry.tv_sec;
1880 pthread_mutex_unlock(rqout->lock);
1884 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1885 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1886 if (conf->statusserver) {
1887 if (*rqout->rq->buf == RAD_Status_Server) {
1888 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1889 if (server->lostrqs < 255)
1893 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1894 if (server->lostrqs < 255)
1897 freerqoutdata(rqout);
1898 pthread_mutex_unlock(rqout->lock);
1902 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1903 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1904 timeout.tv_sec = rqout->expiry.tv_sec;
1906 conf->pdef->clientradput(server, rqout->rq->buf);
1907 pthread_mutex_unlock(rqout->lock);
1909 if (conf->statusserver && server->connectionok) {
1910 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1911 gettimeofday(&now, NULL);
1912 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1914 statsrvrq = createstatsrvrq();
1916 statsrvrq->to = server;
1917 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1924 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1927 conf->servers = NULL;
1928 if (server->dynamiclookuparg) {
1929 removeserversubrealms(realms, conf);
1933 freeclsrvconf(conf);
1935 freeserver(server, 1);
1936 ERR_remove_state(0);
1940 void createlistener(uint8_t type, char *arg) {
1942 struct addrinfo *res;
1943 int s = -1, on = 1, *sp = NULL;
1944 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1946 if (!hp || !resolvehostport(hp, AF_UNSPEC, protodefs[type]->socktype, 1))
1947 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1949 for (res = hp->addrinfo; res; res = res->ai_next) {
1950 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1952 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1955 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1957 disable_DF_bit(s, res);
1960 if (res->ai_family == AF_INET6)
1961 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1963 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1964 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1970 sp = malloc(sizeof(int));
1972 debugx(1, DBG_ERR, "malloc failed");
1974 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1975 debugerrnox(errno, DBG_ERR, "pthread_create failed");
1979 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1981 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1985 void createlisteners(uint8_t type) {
1989 args = protodefs[type]->getlistenerargs();
1991 for (i = 0; args[i]; i++)
1992 createlistener(type, args[i]);
1994 createlistener(type, NULL);
2002 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2003 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2004 for (i = 0; i < CRYPTO_num_locks(); i++) {
2005 ssl_lock_count[i] = 0;
2006 pthread_mutex_init(&ssl_locks[i], NULL);
2008 CRYPTO_set_id_callback(ssl_thread_id);
2009 CRYPTO_set_locking_callback(ssl_locking_callback);
2011 SSL_load_error_strings();
2014 while (!RAND_status()) {
2017 RAND_seed((unsigned char *)&t, sizeof(time_t));
2018 RAND_seed((unsigned char *)&pid, sizeof(pid));
2022 struct list *addsrvconfs(char *value, char **names) {
2023 struct list *conflist;
2025 struct list_node *entry;
2026 struct clsrvconf *conf = NULL;
2028 if (!names || !*names)
2031 conflist = list_create();
2033 debug(DBG_ERR, "malloc failed");
2037 for (n = 0; names[n]; n++) {
2038 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2039 conf = (struct clsrvconf *)entry->data;
2040 if (!strcasecmp(names[n], conf->name))
2044 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2045 list_destroy(conflist);
2048 if (!list_push(conflist, conf)) {
2049 debug(DBG_ERR, "malloc failed");
2050 list_destroy(conflist);
2053 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2058 void freerealm(struct realm *realm) {
2061 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2062 if (--realm->refcount)
2066 free(realm->message);
2067 regfree(&realm->regex);
2068 pthread_mutex_destroy(&realm->mutex);
2069 /* if refcount == 0, all subrealms gone */
2070 list_destroy(realm->subrealms);
2071 /* if refcount == 0, all srvconfs gone */
2072 list_destroy(realm->srvconfs);
2073 /* if refcount == 0, all accsrvconfs gone */
2074 list_destroy(realm->accsrvconfs);
2075 freerealm(realm->parent);
2079 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2081 struct realm *realm;
2082 char *s, *regex = NULL;
2084 if (*value == '/') {
2085 /* regexp, remove optional trailing / if present */
2086 if (value[strlen(value) - 1] == '/')
2087 value[strlen(value) - 1] = '\0';
2089 /* not a regexp, let us make it one */
2090 if (*value == '*' && !value[1])
2091 regex = stringcopy(".*", 0);
2093 for (n = 0, s = value; *s;)
2096 regex = malloc(strlen(value) + n + 3);
2099 for (n = 1, s = value; *s; s++) {
2109 debug(DBG_ERR, "malloc failed");
2113 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2116 realm = malloc(sizeof(struct realm));
2118 debug(DBG_ERR, "malloc failed");
2121 memset(realm, 0, sizeof(struct realm));
2123 if (pthread_mutex_init(&realm->mutex, NULL)) {
2124 debugerrno(errno, DBG_ERR, "mutex init failed");
2130 realm->name = stringcopy(value, 0);
2132 debug(DBG_ERR, "malloc failed");
2135 if (message && strlen(message) > 253) {
2136 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2139 realm->message = message;
2140 realm->accresp = accresp;
2142 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2143 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2147 if (servers && *servers) {
2148 realm->srvconfs = addsrvconfs(value, servers);
2149 if (!realm->srvconfs)
2153 if (accservers && *accservers) {
2154 realm->accsrvconfs = addsrvconfs(value, accservers);
2155 if (!realm->accsrvconfs)
2159 if (!list_push(realmlist, realm)) {
2160 debug(DBG_ERR, "malloc failed");
2161 pthread_mutex_destroy(&realm->mutex);
2165 debug(DBG_DBG, "addrealm: added realm %s", value);
2169 while (list_shift(realm->srvconfs));
2170 while (list_shift(realm->accsrvconfs));
2177 for (n = 0; servers[n]; n++)
2179 freegconfmstr(servers);
2183 for (n = 0; accservers[n]; n++)
2185 freegconfmstr(accservers);
2187 return newrealmref(realm);
2190 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2191 struct list_node *entry;
2192 struct clsrvconf *conf, *srvconf;
2193 struct list *subrealmservers = NULL;
2196 if (list_first(srvconfs)) {
2197 subrealmservers = list_create();
2198 if (!subrealmservers)
2202 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2203 conf = (struct clsrvconf *)entry->data;
2204 if (!conf->servers && conf->dynamiclookupcommand) {
2205 srvconf = malloc(sizeof(struct clsrvconf));
2207 debug(DBG_ERR, "malloc failed");
2210 debug(DBG_DBG, "%s: copying config %s", __func__, conf->name);
2212 /* Shallow copy -- sharing all the pointers. addserver()
2213 * will take care of servers (which btw has to be NUL) but
2214 * the rest of them are shared with the config found in
2215 * the srvconfs list. */
2216 if (addserver(srvconf)) {
2217 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2218 srvconf->servers->dynstartup = 1;
2219 debug(DBG_DBG, "%s: new client writer for %s",
2220 __func__, srvconf->servers->conf->name);
2221 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2222 pthread_mutex_lock(&srvconf->servers->lock);
2224 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2225 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2226 pthread_mutex_unlock(&srvconf->servers->lock);
2228 debugerrno(errno, DBG_ERR, "pthread_create failed");
2229 freeserver(srvconf->servers, 1);
2230 srvconf->servers = NULL;
2231 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2236 pthread_detach(clientth);
2238 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2239 /* If clientwr() could not find a NAPTR we have to
2240 * wait for dynfailing=1 what is set in clientwr(). */
2241 pthread_mutex_lock(&srvconf->servers->lock);
2242 pthread_mutex_unlock(&srvconf->servers->lock);
2247 if (conf->servers) {
2248 if (list_push(subrealmservers, conf))
2251 debug(DBG_ERR, "malloc failed");
2254 return subrealmservers;
2257 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2258 struct realm *newrealm = NULL;
2259 char *realmname, *s;
2261 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2262 realmname = strrchr(id, '@');
2268 for (s = realmname; *s; s++)
2269 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2272 if (!realm->subrealms)
2273 realm->subrealms = list_create();
2274 if (!realm->subrealms)
2277 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2279 list_destroy(realm->subrealms);
2280 realm->subrealms = NULL;
2284 newrealm->parent = newrealmref(realm);
2285 /* add server and accserver to newrealm */
2286 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2287 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2291 int dynamicconfig(struct server *server) {
2292 int ok, fd[2], status;
2294 struct clsrvconf *conf = server->conf;
2295 struct gconffile *cf = NULL;
2297 /* for now we only learn hostname/address */
2298 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2301 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2306 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2310 } else if (pid == 0) {
2313 if (fd[1] != STDOUT_FILENO) {
2314 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2315 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2318 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2319 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2323 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2324 ok = getgenericconfig(&cf, NULL, "Server", CONF_CBK, confserver_cb,
2325 (void *) conf, NULL);
2328 if (waitpid(pid, &status, 0) < 0) {
2329 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2334 debug(DBG_INFO, "dynamicconfig: command exited with status %d",
2335 WEXITSTATUS(status));
2343 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2347 /* should accept both names and numeric values, only numeric right now */
2348 uint8_t attrname2val(char *attrname) {
2351 val = atoi(attrname);
2352 return val > 0 && val < 256 ? val : 0;
2355 /* ATTRNAME is on the form vendor[:type].
2356 If only vendor is found, TYPE is set to 256 and 1 is returned.
2357 If type is >= 256, 1 is returned.
2358 Otherwise, 0 is returned.
2360 /* should accept both names and numeric values, only numeric right now */
2361 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2364 *vendor = atoi(attrname);
2365 s = strchr(attrname, ':');
2366 if (!s) { /* Only vendor was found. */
2370 *type = atoi(s + 1);
2374 /** Extract attributes from string NAMEVAL, create a struct tlv and
2375 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2376 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2377 * NULL if fields are missing or if conversion fails.
2379 * FIXME: Should accept both names and numeric values, only numeric
2381 struct tlv *extractattr(char *nameval, char vendor_flag) {
2383 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2387 s = strchr(nameval, ':');
2390 name = atoi(nameval);
2393 s2 = strchr(s + 1, ':');
2400 len = strlen(s + 1);
2404 if (name < 1 || name > 255)
2406 a = malloc(sizeof(struct tlv));
2410 a->v = (uint8_t *)stringcopy(s + 1, 0);
2419 a = makevendortlv(vendor, a);
2424 /* should accept both names and numeric values, only numeric right now */
2425 struct modattr *extractmodattr(char *nameval) {
2430 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2434 s = strchr(nameval, ':');
2435 name = atoi(nameval);
2436 if (!s || name < 1 || name > 255 || s[1] != '/')
2440 /* regexp, remove optional trailing / if present */
2441 if (s[strlen(s) - 1] == '/')
2442 s[strlen(s) - 1] = '\0';
2450 m = malloc(sizeof(struct modattr));
2452 debug(DBG_ERR, "malloc failed");
2457 m->replacement = stringcopy(t, 0);
2458 if (!m->replacement) {
2460 debug(DBG_ERR, "malloc failed");
2464 m->regex = malloc(sizeof(regex_t));
2466 free(m->replacement);
2468 debug(DBG_ERR, "malloc failed");
2472 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2474 free(m->replacement);
2476 debug(DBG_ERR, "failed to compile regular expression %s", s);
2483 struct rewrite *getrewrite(char *alt1, char *alt2) {
2487 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2490 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2495 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2497 struct rewrite *rewrite = NULL;
2499 uint8_t *rma = NULL;
2500 uint32_t *p, *rmva = NULL;
2501 struct list *adda = NULL, *moda = NULL;
2506 for (n = 0; rmattrs[n]; n++);
2507 rma = calloc(n + 1, sizeof(uint8_t));
2509 debugx(1, DBG_ERR, "malloc failed");
2511 for (i = 0; i < n; i++)
2512 if (!(rma[i] = attrname2val(rmattrs[i])))
2513 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2514 freegconfmstr(rmattrs);
2519 for (n = 0; rmvattrs[n]; n++);
2520 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2522 debugx(1, DBG_ERR, "malloc failed");
2524 for (p = rmva, i = 0; i < n; i++, p += 2)
2525 if (!vattrname2val(rmvattrs[i], p, p + 1))
2526 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2527 freegconfmstr(rmvattrs);
2532 adda = list_create();
2534 debugx(1, DBG_ERR, "malloc failed");
2535 for (i = 0; addattrs[i]; i++) {
2536 a = extractattr(addattrs[i], 0);
2538 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2539 if (!list_push(adda, a))
2540 debugx(1, DBG_ERR, "malloc failed");
2542 freegconfmstr(addattrs);
2547 adda = list_create();
2549 debugx(1, DBG_ERR, "malloc failed");
2550 for (i = 0; addvattrs[i]; i++) {
2551 a = extractattr(addvattrs[i], 1);
2553 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2554 if (!list_push(adda, a))
2555 debugx(1, DBG_ERR, "malloc failed");
2557 freegconfmstr(addvattrs);
2561 moda = list_create();
2563 debugx(1, DBG_ERR, "malloc failed");
2564 for (i = 0; modattrs[i]; i++) {
2565 m = extractmodattr(modattrs[i]);
2567 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2568 if (!list_push(moda, m))
2569 debugx(1, DBG_ERR, "malloc failed");
2571 freegconfmstr(modattrs);
2574 if (rma || rmva || adda || moda) {
2575 rewrite = malloc(sizeof(struct rewrite));
2577 debugx(1, DBG_ERR, "malloc failed");
2578 rewrite->removeattrs = rma;
2579 rewrite->removevendorattrs = rmva;
2580 rewrite->addattrs = adda;
2581 rewrite->modattrs = moda;
2584 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2585 debugx(1, DBG_ERR, "malloc failed");
2586 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2589 int setttlattr(struct options *opts, char *defaultattr) {
2590 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2592 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2593 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2595 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2599 void freeclsrvconf(struct clsrvconf *conf) {
2602 debug(DBG_DBG, "%s: freeing %p (%s)", __func__, conf, conf->name);
2605 freegconfmstr(conf->hostsrc);
2606 free(conf->portsrc);
2609 free(conf->matchcertattr);
2610 if (conf->certcnregex)
2611 regfree(conf->certcnregex);
2612 if (conf->certuriregex)
2613 regfree(conf->certuriregex);
2614 free(conf->confrewritein);
2615 free(conf->confrewriteout);
2616 if (conf->rewriteusername) {
2617 if (conf->rewriteusername->regex)
2618 regfree(conf->rewriteusername->regex);
2619 free(conf->rewriteusername->replacement);
2620 free(conf->rewriteusername);
2622 free(conf->dynamiclookupcommand);
2623 free(conf->rewritein);
2624 free(conf->rewriteout);
2625 if (conf->hostports)
2626 freehostports(conf->hostports);
2628 pthread_mutex_destroy(conf->lock);
2631 /* not touching ssl_ctx, clients and servers */
2635 int mergeconfstring(char **dst, char **src) {
2644 t = stringcopy(*dst, 0);
2646 debug(DBG_ERR, "malloc failed");
2654 char **mstringcopy(char **in) {
2661 for (n = 0; in[n]; n++);
2662 out = malloc((n + 1) * sizeof(char *));
2665 for (n = 0; in[n]; n++) {
2666 out[n] = stringcopy(in[n], 0);
2676 int mergeconfmstring(char ***dst, char ***src) {
2685 t = mstringcopy(*dst);
2687 debug(DBG_ERR, "malloc failed");
2695 /* assumes dst is a shallow copy */
2696 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2697 if (!mergeconfstring(&dst->name, &src->name) ||
2698 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2699 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2700 !mergeconfstring(&dst->secret, &src->secret) ||
2701 !mergeconfstring(&dst->tls, &src->tls) ||
2702 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2703 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2704 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2705 !mergeconfstring(&dst->confrewriteusername, &src->confrewriteusername) ||
2706 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand) ||
2707 !mergeconfstring(&dst->fticks_viscountry, &src->fticks_viscountry) ||
2708 !mergeconfstring(&dst->fticks_visinst, &src->fticks_visinst))
2711 dst->pdef = src->pdef;
2712 dst->statusserver = src->statusserver;
2713 dst->certnamecheck = src->certnamecheck;
2714 if (src->retryinterval != 255)
2715 dst->retryinterval = src->retryinterval;
2716 if (src->retrycount != 255)
2717 dst->retrycount = src->retrycount;
2721 /** Set *AF according to IPV4ONLY and IPV6ONLY:
2722 - If both are set, the function fails.
2723 - If exactly one is set, *AF is set accordingly.
2724 - If none is set, *AF is not affected.
2725 Return 0 on success and !0 on failure.
2726 In the case of an error, *AF is not affected. */
2727 int config_hostaf(const char *desc, int ipv4only, int ipv6only, int *af) {
2729 if (ipv4only && ipv6only) {
2730 debug(DBG_ERR, "error in block %s, at most one of IPv4Only and "
2731 "IPv6Only can be enabled", desc);
2741 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2742 struct clsrvconf *conf;
2743 char *conftype = NULL, *rewriteinalias = NULL;
2744 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2745 uint8_t ipv4only = 0, ipv6only = 0;
2747 debug(DBG_DBG, "confclient_cb called for %s", block);
2749 conf = malloc(sizeof(struct clsrvconf));
2751 debugx(1, DBG_ERR, "malloc failed");
2752 memset(conf, 0, sizeof(struct clsrvconf));
2753 conf->certnamecheck = 1;
2755 if (!getgenericconfig(
2757 "type", CONF_STR, &conftype,
2758 "host", CONF_MSTR, &conf->hostsrc,
2759 "IPv4Only", CONF_BLN, &ipv4only,
2760 "IPv6Only", CONF_BLN, &ipv6only,
2761 "secret", CONF_STR, &conf->secret,
2762 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2763 "tls", CONF_STR, &conf->tls,
2764 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2765 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2767 "DuplicateInterval", CONF_LINT, &dupinterval,
2768 "addTTL", CONF_LINT, &addttl,
2769 "rewrite", CONF_STR, &rewriteinalias,
2770 "rewriteIn", CONF_STR, &conf->confrewritein,
2771 "rewriteOut", CONF_STR, &conf->confrewriteout,
2772 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2773 #if defined(WANT_FTICKS)
2774 "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2775 "fticksVISINST", CONF_STR, &conf->fticks_visinst,
2779 debugx(1, DBG_ERR, "configuration error");
2781 conf->name = stringcopy(val, 0);
2782 if (conf->name && !conf->hostsrc) {
2783 conf->hostsrc = malloc(2 * sizeof(char *));
2784 if (conf->hostsrc) {
2785 conf->hostsrc[0] = stringcopy(val, 0);
2786 conf->hostsrc[1] = NULL;
2789 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2790 debugx(1, DBG_ERR, "malloc failed");
2793 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2794 conf->type = protoname2int(conftype);
2795 if (conf->type == 255)
2796 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2798 conf->pdef = protodefs[conf->type];
2800 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2801 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2802 conf->tlsconf = conf->tls
2803 ? tlsgettls(conf->tls, NULL)
2804 : tlsgettls("defaultClient", "default");
2806 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2807 if (conf->matchcertattr && !addmatchcertattr(conf))
2808 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2812 conf->hostaf = AF_UNSPEC;
2813 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
2814 debugx(1, DBG_ERR, "config error: ^");
2815 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
2816 debugx(1, DBG_ERR, "error in block %s: ^", block);
2818 if (dupinterval != LONG_MIN) {
2819 if (dupinterval < 0 || dupinterval > 255)
2820 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2821 conf->dupinterval = (uint8_t)dupinterval;
2823 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2825 if (addttl != LONG_MIN) {
2826 if (addttl < 1 || addttl > 255)
2827 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2828 conf->addttl = (uint8_t)addttl;
2831 if (!conf->confrewritein)
2832 conf->confrewritein = rewriteinalias;
2834 free(rewriteinalias);
2835 conf->rewritein = conf->confrewritein
2836 ? getrewrite(conf->confrewritein, NULL)
2837 : getrewrite("defaultClient", "default");
2838 if (conf->confrewriteout)
2839 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2841 if (conf->confrewriteusername) {
2842 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2843 if (!conf->rewriteusername)
2844 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2847 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2848 !resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype))
2849 debugx(1, DBG_ERR, "%s: resolve failed, exiting", __func__);
2851 if (!conf->secret) {
2852 if (!conf->pdef->secretdefault)
2853 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2854 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2856 debugx(1, DBG_ERR, "malloc failed");
2859 conf->lock = malloc(sizeof(pthread_mutex_t));
2861 debugx(1, DBG_ERR, "malloc failed");
2863 pthread_mutex_init(conf->lock, NULL);
2864 if (!list_push(clconfs, conf))
2865 debugx(1, DBG_ERR, "malloc failed");
2869 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2870 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2871 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2872 conf->tlsconf = conf->tls
2873 ? tlsgettls(conf->tls, NULL)
2874 : tlsgettls("defaultServer", "default");
2875 if (!conf->tlsconf) {
2876 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2879 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2880 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2886 if (!conf->portsrc) {
2887 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2888 if (!conf->portsrc) {
2889 debug(DBG_ERR, "malloc failed");
2894 if (conf->retryinterval == 255)
2895 conf->retryinterval = conf->pdef->retryintervaldefault;
2896 if (conf->retrycount == 255)
2897 conf->retrycount = conf->pdef->retrycountdefault;
2899 conf->rewritein = conf->confrewritein
2900 ? getrewrite(conf->confrewritein, NULL)
2901 : getrewrite("defaultServer", "default");
2902 if (conf->confrewriteout)
2903 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2905 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2906 debug(DBG_ERR, "error in block %s, failed to parse %s", block, *conf->hostsrc);
2910 if (!conf->dynamiclookupcommand &&
2911 !resolvehostports(conf->hostports, conf->hostaf,
2912 conf->pdef->socktype)) {
2913 debug(DBG_ERR, "%s: resolve failed", __func__);
2919 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2920 struct clsrvconf *conf, *resconf;
2921 char *conftype = NULL, *rewriteinalias = NULL;
2922 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2923 uint8_t ipv4only = 0, ipv6only = 0;
2925 debug(DBG_DBG, "confserver_cb called for %s", block);
2927 conf = malloc(sizeof(struct clsrvconf));
2929 debug(DBG_ERR, "malloc failed");
2932 memset(conf, 0, sizeof(struct clsrvconf));
2933 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2934 resconf = (struct clsrvconf *)arg;
2936 conf->statusserver = resconf->statusserver;
2937 conf->certnamecheck = resconf->certnamecheck;
2939 conf->certnamecheck = 1;
2941 if (!getgenericconfig(cf, block,
2942 "type", CONF_STR, &conftype,
2943 "host", CONF_MSTR, &conf->hostsrc,
2944 "IPv4Only", CONF_BLN, &ipv4only,
2945 "IPv6Only", CONF_BLN, &ipv6only,
2946 "port", CONF_STR, &conf->portsrc,
2947 "secret", CONF_STR, &conf->secret,
2948 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2949 "tls", CONF_STR, &conf->tls,
2950 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2951 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2953 "addTTL", CONF_LINT, &addttl,
2954 "rewrite", CONF_STR, &rewriteinalias,
2955 "rewriteIn", CONF_STR, &conf->confrewritein,
2956 "rewriteOut", CONF_STR, &conf->confrewriteout,
2957 "StatusServer", CONF_BLN, &conf->statusserver,
2958 "RetryInterval", CONF_LINT, &retryinterval,
2959 "RetryCount", CONF_LINT, &retrycount,
2960 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2961 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2964 debug(DBG_ERR, "configuration error");
2968 conf->name = stringcopy(val, 0);
2969 if (conf->name && !conf->hostsrc) {
2970 conf->hostsrc = malloc(2 * sizeof(char *));
2971 if (conf->hostsrc) {
2972 conf->hostsrc[0] = stringcopy(val, 0);
2973 conf->hostsrc[1] = NULL;
2976 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2977 debug(DBG_ERR, "malloc failed");
2982 debug(DBG_ERR, "error in block %s, option type missing", block);
2985 conf->type = protoname2int(conftype);
2986 if (conf->type == 255) {
2987 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2993 conf->hostaf = AF_UNSPEC;
2994 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
2995 debugx(1, DBG_ERR, "config error: ^");
2996 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
2999 conf->pdef = protodefs[conf->type];
3001 if (!conf->confrewritein)
3002 conf->confrewritein = rewriteinalias;
3004 free(rewriteinalias);
3005 rewriteinalias = NULL;
3007 if (retryinterval != LONG_MIN) {
3008 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3009 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3012 conf->retryinterval = (uint8_t)retryinterval;
3014 conf->retryinterval = 255;
3016 if (retrycount != LONG_MIN) {
3017 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3018 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3021 conf->retrycount = (uint8_t)retrycount;
3023 conf->retrycount = 255;
3025 if (addttl != LONG_MIN) {
3026 if (addttl < 1 || addttl > 255) {
3027 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3030 conf->addttl = (uint8_t)addttl;
3034 if (!mergesrvconf(resconf, conf))
3038 if (conf->dynamiclookupcommand) {
3039 free(conf->dynamiclookupcommand);
3040 conf->dynamiclookupcommand = NULL;
3044 if (resconf || !conf->dynamiclookupcommand) {
3045 if (!compileserverconfig(conf, block))
3046 return 0; /* Don't goto errexit and free resconf -- it's
3047 * not ours to free. */
3050 if (!conf->secret) {
3051 if (!conf->pdef->secretdefault) {
3052 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3055 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3056 if (!conf->secret) {
3057 debug(DBG_ERR, "malloc failed");
3065 if (!list_push(srvconfs, conf)) {
3066 debug(DBG_ERR, "malloc failed");
3073 free(rewriteinalias);
3074 freeclsrvconf(conf);
3078 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3079 char **servers = NULL, **accservers = NULL, *msg = NULL;
3080 uint8_t accresp = 0;
3082 debug(DBG_DBG, "confrealm_cb called for %s", block);
3084 if (!getgenericconfig(cf, block,
3085 "server", CONF_MSTR, &servers,
3086 "accountingServer", CONF_MSTR, &accservers,
3087 "ReplyMessage", CONF_STR, &msg,
3088 "AccountingResponse", CONF_BLN, &accresp,
3091 debugx(1, DBG_ERR, "configuration error");
3093 addrealm(realms, val, servers, accservers, msg, accresp);
3097 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3098 char **rmattrs = NULL, **rmvattrs = NULL;
3099 char **addattrs = NULL, **addvattrs = NULL;
3100 char **modattrs = NULL;
3102 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3104 if (!getgenericconfig(cf, block,
3105 "removeAttribute", CONF_MSTR, &rmattrs,
3106 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3107 "addAttribute", CONF_MSTR, &addattrs,
3108 "addVendorAttribute", CONF_MSTR, &addvattrs,
3109 "modifyAttribute", CONF_MSTR, &modattrs,
3112 debugx(1, DBG_ERR, "configuration error");
3113 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
3117 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3118 struct commonprotoopts *protoopts;
3120 protoopts = malloc(sizeof(struct commonprotoopts));
3123 memset(protoopts, 0, sizeof(struct commonprotoopts));
3124 protoopts->listenargs = listenargs;
3125 protoopts->sourcearg = sourcearg;
3126 protodefs[type]->setprotoopts(protoopts);
3130 void getmainconfig(const char *configfile) {
3131 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3132 struct gconffile *cfs;
3133 char **listenargs[RAD_PROTOCOUNT];
3134 char *sourcearg[RAD_PROTOCOUNT];
3135 #if defined(WANT_FTICKS)
3136 uint8_t *fticks_reporting_str = NULL;
3137 uint8_t *fticks_mac_str = NULL;
3138 uint8_t *fticks_key_str = NULL;
3142 cfs = openconfigfile(configfile);
3143 memset(&options, 0, sizeof(options));
3144 memset(&listenargs, 0, sizeof(listenargs));
3145 memset(&sourcearg, 0, sizeof(sourcearg));
3147 clconfs = list_create();
3149 debugx(1, DBG_ERR, "malloc failed");
3151 srvconfs = list_create();
3153 debugx(1, DBG_ERR, "malloc failed");
3155 realms = list_create();
3157 debugx(1, DBG_ERR, "malloc failed");
3159 rewriteconfs = hash_create();
3161 debugx(1, DBG_ERR, "malloc failed");
3163 if (!getgenericconfig(
3166 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3167 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3170 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3171 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3174 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3175 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3178 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3179 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3181 "PidFile", CONF_STR, &options.pidfile,
3182 "TTLAttribute", CONF_STR, &options.ttlattr,
3183 "addTTL", CONF_LINT, &addttl,
3184 "LogLevel", CONF_LINT, &loglevel,
3185 "LogDestination", CONF_STR, &options.logdestination,
3186 "LoopPrevention", CONF_BLN, &options.loopprevention,
3187 "Client", CONF_CBK, confclient_cb, NULL,
3188 "Server", CONF_CBK, confserver_cb, NULL,
3189 "Realm", CONF_CBK, confrealm_cb, NULL,
3190 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3191 "TLS", CONF_CBK, conftls_cb, NULL,
3193 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3194 #if defined(WANT_FTICKS)
3195 "FTicksReporting", CONF_STR, &fticks_reporting_str,
3196 "FTicksMAC", CONF_STR, &fticks_mac_str,
3197 "FTicksKey", CONF_STR, &fticks_key_str,
3198 "FTicksSyslogFacility", CONF_STR, &options.ftickssyslogfacility,
3200 "IPv4Only", CONF_BLN, &options.ipv4only,
3201 "IPv6Only", CONF_BLN, &options.ipv6only,
3204 debugx(1, DBG_ERR, "configuration error");
3206 if (loglevel != LONG_MIN) {
3207 if (loglevel < 1 || loglevel > 5)
3208 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3209 options.loglevel = (uint8_t)loglevel;
3211 if (addttl != LONG_MIN) {
3212 if (addttl < 1 || addttl > 255)
3213 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3214 options.addttl = (uint8_t)addttl;
3216 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3217 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3219 #if defined(WANT_FTICKS)
3220 fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3224 for (i = 0; i < RAD_PROTOCOUNT; i++)
3225 if (listenargs[i] || sourcearg[i])
3226 setprotoopts(i, listenargs[i], sourcearg[i]);
3229 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3232 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3235 *configfile = optarg;
3238 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3239 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3240 *loglevel = *optarg - '0';
3252 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3253 debug(DBG_ERR, "This binary was built with support for the following transports:");
3255 debug(DBG_ERR, " UDP");
3258 debug(DBG_ERR, " TCP");
3261 debug(DBG_ERR, " TLS");
3264 debug(DBG_ERR, " DTLS");
3271 if (!(argc - optind))
3275 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3279 int daemon(int a, int b) {
3287 for (i = 0; i < 3; i++) {
3289 open("/dev/null", O_RDWR);
3295 void *sighandler(void *arg) {
3300 sigemptyset(&sigset);
3301 sigaddset(&sigset, SIGHUP);
3302 sigaddset(&sigset, SIGPIPE);
3303 sigwait(&sigset, &sig);
3306 /* completely ignoring this */
3309 debug(DBG_INFO, "sighandler: got SIGHUP");
3313 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3316 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3321 int createpidfile(const char *pidfile) {
3323 FILE *f = fopen(pidfile, "w");
3325 r = fprintf(f, "%ld\n", (long) getpid());
3326 return f && !fclose(f) && r >= 0;
3329 int radsecproxy_main(int argc, char **argv) {
3332 struct list_node *entry;
3333 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3334 char *configfile = NULL, *pidfile = NULL;
3335 struct clsrvconf *srvconf;
3338 debug_init("radsecproxy");
3339 debug_set_level(DEBUG_LEVEL);
3341 for (i = 0; i < RAD_PROTOCOUNT; i++)
3342 protodefs[i] = protoinits[i](i);
3344 /* needed even if no TLS/DTLS transport */
3347 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3349 debug_set_level(loglevel);
3350 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3352 options.loglevel = loglevel;
3353 else if (options.loglevel)
3354 debug_set_level(options.loglevel);
3356 debug_set_destination(options.logdestination
3357 ? options.logdestination
3358 : "x-syslog:///", LOG_TYPE_DEBUG);
3359 #if defined(WANT_FTICKS)
3360 if (options.ftickssyslogfacility) {
3361 debug_set_destination(options.ftickssyslogfacility,
3363 free(options.ftickssyslogfacility);
3367 free(options.logdestination);
3369 if (!list_first(clconfs))
3370 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3371 if (!list_first(realms))
3372 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3375 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3377 if (!foreground && (daemon(0, 0) < 0))
3378 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3380 debug_timestamp_on();
3381 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3383 pidfile = options.pidfile;
3384 if (pidfile && !createpidfile(pidfile))
3385 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3387 sigemptyset(&sigset);
3388 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3389 sigaddset(&sigset, SIGHUP);
3390 sigaddset(&sigset, SIGPIPE);
3391 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3392 pthread_create(&sigth, NULL, sighandler, NULL);
3394 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3395 srvconf = (struct clsrvconf *)entry->data;
3396 if (srvconf->dynamiclookupcommand)
3398 if (!addserver(srvconf))
3399 debugx(1, DBG_ERR, "failed to add server");
3400 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3401 (void *)(srvconf->servers)))
3402 debugx(1, DBG_ERR, "pthread_create failed");
3405 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3408 if (protodefs[i]->initextra)
3409 protodefs[i]->initextra();
3410 if (find_clconf_type(i, NULL))
3414 /* just hang around doing nothing, anything to do here? */
3419 /* Local Variables: */
3420 /* c-file-style: "stroustrup" */