2 * Copyright (C) 2006-2009 Stig Venaas <venaas@uninett.no>
3 * Copyright (C) 2010,2011,2012 NORDUnet A/S
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
10 /* Code contributions from:
12 * Arne Schwabe <schwabe at uni-paderborn.de>
13 * Maja Wolniewicz <mgw@umk.pl>
14 * Simon Leinen <simon.leinen@switch.ch>
15 * Stefan Winter <stefan.winter@restena.lu>
18 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
19 * rd is responsible for init and launching wr
20 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
21 * each tlsserverrd launches tlsserverwr
22 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
23 * for init and launching rd
25 * serverrd will receive a request, processes it and puts it in the requestq of
26 * the appropriate clientwr
27 * clientwr monitors its requestq and sends requests
28 * clientrd looks for responses, processes them and puts them in the replyq of
29 * the peer the request came from
30 * serverwr monitors its reply and sends replies
32 * In addition to the main thread, we have:
33 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
34 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
35 * For each TLS peer connecting to us there will be 2 more TLS threads
36 * This is only for connected peers
37 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
38 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
42 * May segfault when dtls connections go down? More testing needed
43 * Remove expired stuff from clients request list?
44 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
45 * Useful for TCP accounting? Now we require separate server config for alt port
49 #include <sys/socket.h>
50 #include <netinet/in.h>
55 #if defined(HAVE_MALLOPT)
62 #include <sys/types.h>
65 #include <arpa/inet.h>
71 #include <openssl/ssl.h>
72 #include <openssl/rand.h>
73 #include <openssl/err.h>
74 #include <openssl/md5.h>
79 #include "radsecproxy.h"
84 #if defined(WANT_FTICKS)
88 static struct options options;
89 static struct list *clconfs, *srvconfs;
90 static struct list *realms;
91 static struct hash *rewriteconfs;
93 static pthread_mutex_t *ssl_locks = NULL;
94 static long *ssl_lock_count;
97 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
99 /* minimum required declarations to avoid reordering code */
100 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
101 int dynamicconfig(struct server *server);
102 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
103 void freerealm(struct realm *realm);
104 void freeclsrvconf(struct clsrvconf *conf);
105 void freerq(struct request *rq);
106 void freerqoutdata(struct rqout *rqout);
107 void rmclientrq(struct request *rq, uint8_t id);
109 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
111 uint8_t protoname2int(const char *name) {
114 for (i = 0; i < RAD_PROTOCOUNT; i++)
115 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
120 /* callbacks for making OpenSSL thread safe */
121 unsigned long ssl_thread_id() {
122 return (unsigned long)pthread_self();
125 void ssl_locking_callback(int mode, int type, const char *file, int line) {
126 if (mode & CRYPTO_LOCK) {
127 pthread_mutex_lock(&ssl_locks[type]);
128 ssl_lock_count[type]++;
130 pthread_mutex_unlock(&ssl_locks[type]);
133 /* returns 1 if the len first bits are equal, else 0 */
134 int prefixmatch(void *a1, void *a2, uint8_t len) {
135 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
136 uint8_t r, l = len / 8;
137 if (l && memcmp(a1, a2, l))
142 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
145 /* returns next config with matching address, or NULL */
146 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
147 struct list_node *entry;
148 struct clsrvconf *conf;
150 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
151 conf = (struct clsrvconf *)entry->data;
152 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
161 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
162 return find_conf(type, addr, clconfs, cur, 0);
165 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
166 return find_conf(type, addr, srvconfs, cur, 1);
169 /* returns next config of given type, or NULL */
170 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
171 struct list_node *entry;
172 struct clsrvconf *conf;
174 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
175 conf = (struct clsrvconf *)entry->data;
176 if (conf->type == type) {
185 struct gqueue *newqueue() {
188 q = malloc(sizeof(struct gqueue));
190 debugx(1, DBG_ERR, "malloc failed");
191 q->entries = list_create();
193 debugx(1, DBG_ERR, "malloc failed");
194 pthread_mutex_init(&q->mutex, NULL);
195 pthread_cond_init(&q->cond, NULL);
199 void removequeue(struct gqueue *q) {
200 struct list_node *entry;
204 pthread_mutex_lock(&q->mutex);
205 for (entry = list_first(q->entries); entry; entry = list_next(entry))
206 freerq((struct request *)entry);
207 list_destroy(q->entries);
208 pthread_cond_destroy(&q->cond);
209 pthread_mutex_unlock(&q->mutex);
210 pthread_mutex_destroy(&q->mutex);
214 void freebios(struct gqueue *q) {
217 pthread_mutex_lock(&q->mutex);
218 while ((bio = (BIO *)list_shift(q->entries)))
220 pthread_mutex_unlock(&q->mutex);
224 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
225 struct client *new = malloc(sizeof(struct client));
228 debug(DBG_ERR, "malloc failed");
233 pthread_mutex_lock(conf->lock);
234 if (!conf->clients) {
235 conf->clients = list_create();
236 if (!conf->clients) {
238 pthread_mutex_unlock(conf->lock);
239 debug(DBG_ERR, "malloc failed");
244 memset(new, 0, sizeof(struct client));
246 if (conf->pdef->addclient)
247 conf->pdef->addclient(new);
249 new->replyq = newqueue();
250 list_push(conf->clients, new);
252 pthread_mutex_unlock(conf->lock);
256 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
257 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
260 pthread_mutex_lock(&lock);
262 pthread_mutex_unlock(&lock);
265 void removeclientrqs(struct client *client) {
270 removeclientrqs_sendrq_freeserver_lock(1);
271 for (i = 0; i < MAX_REQUESTS; i++) {
276 rqout = rq->to->requests + rq->newid;
277 pthread_mutex_lock(rqout->lock);
278 if (rqout->rq == rq) /* still pointing to our request */
279 freerqoutdata(rqout);
280 pthread_mutex_unlock(rqout->lock);
284 removeclientrqs_sendrq_freeserver_lock(0);
287 void removelockedclient(struct client *client) {
288 struct clsrvconf *conf;
292 removeclientrqs(client);
293 removequeue(client->replyq);
294 list_removedata(conf->clients, client);
300 void removeclient(struct client *client) {
301 struct clsrvconf *conf;
307 pthread_mutex_lock(conf->lock);
308 removelockedclient(client);
309 pthread_mutex_unlock(conf->lock);
312 void freeserver(struct server *server, uint8_t destroymutex) {
313 struct rqout *rqout, *end;
318 removeclientrqs_sendrq_freeserver_lock(1);
319 if (server->requests) {
320 rqout = server->requests;
321 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
323 rqout->rq->to = NULL;
324 freerqoutdata(rqout);
325 pthread_mutex_destroy(rqout->lock);
328 free(server->requests);
331 freebios(server->rbios);
332 free(server->dynamiclookuparg);
334 #if defined ENABLE_EXPERIMENTAL_DYNDISC
335 if (server->sock >= 0)
338 SSL_free(server->ssl);
341 pthread_mutex_destroy(&server->lock);
342 pthread_cond_destroy(&server->newrq_cond);
343 pthread_mutex_destroy(&server->newrq_mutex);
345 removeclientrqs_sendrq_freeserver_lock(0);
349 int addserver(struct clsrvconf *conf) {
353 debug(DBG_ERR, "addserver: currently works with just one server per conf");
356 conf->servers = malloc(sizeof(struct server));
357 if (!conf->servers) {
358 debug(DBG_ERR, "malloc failed");
361 memset(conf->servers, 0, sizeof(struct server));
362 conf->servers->conf = conf;
365 if (conf->type == RAD_DTLS)
366 conf->servers->rbios = newqueue();
368 conf->pdef->setsrcres();
370 conf->servers->sock = -1;
371 if (conf->pdef->addserverextra)
372 conf->pdef->addserverextra(conf);
374 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
375 if (!conf->servers->requests) {
376 debug(DBG_ERR, "malloc failed");
379 for (i = 0; i < MAX_REQUESTS; i++) {
380 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
381 if (!conf->servers->requests[i].lock) {
382 debug(DBG_ERR, "malloc failed");
385 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
386 debugerrno(errno, DBG_ERR, "mutex init failed");
387 free(conf->servers->requests[i].lock);
388 conf->servers->requests[i].lock = NULL;
392 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
393 debugerrno(errno, DBG_ERR, "mutex init failed");
396 conf->servers->newrq = 0;
397 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
398 debugerrno(errno, DBG_ERR, "mutex init failed");
399 pthread_mutex_destroy(&conf->servers->lock);
402 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
403 debugerrno(errno, DBG_ERR, "mutex init failed");
404 pthread_mutex_destroy(&conf->servers->newrq_mutex);
405 pthread_mutex_destroy(&conf->servers->lock);
412 freeserver(conf->servers, 0);
413 conf->servers = NULL;
417 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
419 if (ATTRTYPE(attrs) == type)
421 length -= ATTRLEN(attrs);
422 attrs += ATTRLEN(attrs);
427 struct request *newrqref(struct request *rq) {
433 void freerq(struct request *rq) {
436 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
439 if (rq->origusername)
440 free(rq->origusername);
446 radmsg_free(rq->msg);
450 void freerqoutdata(struct rqout *rqout) {
454 if (rqout->rq->buf) {
455 free(rqout->rq->buf);
456 rqout->rq->buf = NULL;
462 memset(&rqout->expiry, 0, sizeof(struct timeval));
465 void sendrq(struct request *rq) {
469 removeclientrqs_sendrq_freeserver_lock(1);
474 start = to->conf->statusserver ? 1 : 0;
475 pthread_mutex_lock(&to->newrq_mutex);
476 if (start && rq->msg->code == RAD_Status_Server) {
477 pthread_mutex_lock(to->requests[0].lock);
478 if (to->requests[0].rq) {
479 pthread_mutex_unlock(to->requests[0].lock);
480 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
487 /* might simplify if only try nextid, might be ok */
488 for (i = to->nextid; i < MAX_REQUESTS; i++) {
489 if (!to->requests[i].rq) {
490 pthread_mutex_lock(to->requests[i].lock);
491 if (!to->requests[i].rq)
493 pthread_mutex_unlock(to->requests[i].lock);
496 if (i == MAX_REQUESTS) {
497 for (i = start; i < to->nextid; i++) {
498 if (!to->requests[i].rq) {
499 pthread_mutex_lock(to->requests[i].lock);
500 if (!to->requests[i].rq)
502 pthread_mutex_unlock(to->requests[i].lock);
505 if (i == to->nextid) {
506 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
511 rq->newid = (uint8_t)i;
512 rq->msg->id = (uint8_t)i;
513 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
515 pthread_mutex_unlock(to->requests[i].lock);
516 debug(DBG_ERR, "sendrq: radmsg2buf failed");
520 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
521 to->requests[i].rq = rq;
522 pthread_mutex_unlock(to->requests[i].lock);
523 if (i >= start) /* i is not reserved for statusserver */
528 debug(DBG_DBG, "sendrq: signalling client writer");
529 pthread_cond_signal(&to->newrq_cond);
532 pthread_mutex_unlock(&to->newrq_mutex);
533 removeclientrqs_sendrq_freeserver_lock(0);
538 rmclientrq(rq, rq->msg->id);
540 pthread_mutex_unlock(&to->newrq_mutex);
541 removeclientrqs_sendrq_freeserver_lock(0);
544 void sendreply(struct request *rq) {
546 struct client *to = rq->from;
549 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
550 radmsg_free(rq->msg);
554 debug(DBG_ERR, "sendreply: radmsg2buf failed");
558 pthread_mutex_lock(&to->replyq->mutex);
559 first = list_first(to->replyq->entries) == NULL;
561 if (!list_push(to->replyq->entries, rq)) {
562 pthread_mutex_unlock(&to->replyq->mutex);
564 debug(DBG_ERR, "sendreply: malloc failed");
569 debug(DBG_DBG, "signalling server writer");
570 pthread_cond_signal(&to->replyq->cond);
572 pthread_mutex_unlock(&to->replyq->mutex);
575 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
576 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
577 static unsigned char first = 1;
578 static EVP_MD_CTX mdctx;
579 unsigned char hash[EVP_MAX_MD_SIZE], *input;
581 uint8_t i, offset = 0, out[128];
583 pthread_mutex_lock(&lock);
585 EVP_MD_CTX_init(&mdctx);
591 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
592 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
593 !EVP_DigestUpdate(&mdctx, input, 16) ||
594 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
596 pthread_mutex_unlock(&lock);
599 for (i = 0; i < 16; i++)
600 out[offset + i] = hash[i] ^ in[offset + i];
602 input = out + offset;
609 memcpy(in, out, len);
610 pthread_mutex_unlock(&lock);
614 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
615 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
616 static unsigned char first = 1;
617 static EVP_MD_CTX mdctx;
618 unsigned char hash[EVP_MAX_MD_SIZE];
622 pthread_mutex_lock(&lock);
624 EVP_MD_CTX_init(&mdctx);
629 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
630 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
631 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
634 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
635 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
636 !EVP_DigestUpdate(&mdctx, auth, 16) ||
637 !EVP_DigestUpdate(&mdctx, salt, 2) ||
638 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
639 pthread_mutex_unlock(&lock);
644 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
647 for (i = 0; i < 16; i++)
650 for (offset = 16; offset < len; offset += 16) {
652 printf("text + offset - 16 c(%d): ", offset / 16);
653 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
655 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
656 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
657 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
658 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
660 pthread_mutex_unlock(&lock);
664 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
667 for (i = 0; i < 16; i++)
668 text[offset + i] ^= hash[i];
672 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
675 pthread_mutex_unlock(&lock);
679 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
680 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
681 static unsigned char first = 1;
682 static EVP_MD_CTX mdctx;
683 unsigned char hash[EVP_MAX_MD_SIZE];
688 pthread_mutex_lock(&lock);
690 EVP_MD_CTX_init(&mdctx);
695 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
696 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
697 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
700 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
701 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
702 !EVP_DigestUpdate(&mdctx, auth, 16) ||
703 !EVP_DigestUpdate(&mdctx, salt, 2) ||
704 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
705 pthread_mutex_unlock(&lock);
710 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
713 for (i = 0; i < 16; i++)
714 plain[i] = text[i] ^ hash[i];
716 for (offset = 16; offset < len; offset += 16) {
718 printf("text + offset - 16 c(%d): ", offset / 16);
719 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
721 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
722 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
723 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
724 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
726 pthread_mutex_unlock(&lock);
730 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
733 for (i = 0; i < 16; i++)
734 plain[offset + i] = text[offset + i] ^ hash[i];
737 memcpy(text, plain, len);
739 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
742 pthread_mutex_unlock(&lock);
746 struct realm *newrealmref(struct realm *r) {
752 /* returns with lock on realm */
753 struct realm *id2realm(struct list *realmlist, char *id) {
754 struct list_node *entry;
755 struct realm *realm, *subrealm;
757 /* need to do locking for subrealms and check subrealm timers */
758 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
759 realm = (struct realm *)entry->data;
760 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
761 pthread_mutex_lock(&realm->mutex);
762 if (realm->subrealms) {
763 subrealm = id2realm(realm->subrealms, id);
765 pthread_mutex_unlock(&realm->mutex);
769 return newrealmref(realm);
775 int hasdynamicserver(struct list *srvconfs) {
776 struct list_node *entry;
778 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
779 #if defined ENABLE_EXPERIMENTAL_DYNDISC
780 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand
781 || ((struct clsrvconf *)entry->data)->servers->in_use)
783 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
789 /* helper function, only used by removeserversubrealms() */
790 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
791 struct list_node *entry, *entry2;
794 for (entry = list_first(realmlist); entry;) {
795 realm = newrealmref((struct realm *)entry->data);
796 pthread_mutex_lock(&realm->mutex);
797 entry = list_next(entry);
799 if (realm->srvconfs) {
800 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
801 if (entry2->data == srv)
803 list_removedata(realm->srvconfs, srv);
805 if (realm->accsrvconfs) {
806 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
807 if (entry2->data == srv)
809 list_removedata(realm->accsrvconfs, srv);
812 /* remove subrealm if no dynamic servers left */
813 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
814 while (list_shift(realm->srvconfs))
816 list_destroy(realm->srvconfs);
817 realm->srvconfs = NULL;
818 while (list_shift(realm->accsrvconfs))
820 list_destroy(realm->accsrvconfs);
821 realm->accsrvconfs = NULL;
822 list_removedata(realmlist, realm);
824 pthread_mutex_unlock(&realm->mutex);
829 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
830 struct list_node *entry;
833 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
834 realm = (struct realm *)entry->data;
835 pthread_mutex_lock(&realm->mutex);
836 if (realm->subrealms) {
837 _internal_removeserversubrealms(realm->subrealms, srv);
838 if (!list_first(realm->subrealms)) {
839 list_destroy(realm->subrealms);
840 realm->subrealms = NULL;
843 pthread_mutex_unlock(&realm->mutex);
847 int attrvalidate(unsigned char *attrs, int length) {
849 if (ATTRLEN(attrs) < 2) {
850 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
853 length -= ATTRLEN(attrs);
855 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
858 attrs += ATTRLEN(attrs);
861 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
865 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
866 if (len < 16 || len > 128 || len % 16) {
867 debug(DBG_WARN, "pwdrecrypt: invalid password length");
871 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
872 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
876 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
878 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
879 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
885 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
888 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
889 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
892 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
893 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
899 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
900 char *oldsecret, char *newsecret) {
903 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
904 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
905 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
911 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
915 for (; attrs[0]; attrs += 2)
916 if (attrs[0] == vendor && attrs[1] == subattr)
921 /* returns 1 if entire element is to be removed, else 0 */
922 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
923 uint8_t alen, sublen;
927 if (!removevendorattrs)
930 memcpy(&vendor, attr->v, 4);
931 vendor = ntohl(vendor);
932 while (*removevendorattrs && *removevendorattrs != vendor)
933 removevendorattrs += 2;
934 if (!*removevendorattrs)
937 if (findvendorsubattr(removevendorattrs, vendor, 256))
938 return 1; /* remove entire vendor attribute */
940 sublen = attr->l - 4;
941 subattrs = attr->v + 4;
943 if (!attrvalidate(subattrs, sublen)) {
944 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
949 alen = ATTRLEN(subattrs);
951 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
952 memmove(subattrs, subattrs + alen, sublen);
960 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
961 struct list_node *n, *p;
965 n = list_first(msg->attrs);
967 attr = (struct tlv *)n->data;
968 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
969 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
970 list_removedata(msg->attrs, attr);
972 n = p ? list_next(p) : list_first(msg->attrs);
980 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
984 for (n = list_first(addattrs); n; n = list_next(n)) {
985 a = copytlv((struct tlv *)n->data);
988 if (!radmsg_add(msg, a)) {
996 int resizeattr(struct tlv *attr, uint8_t newlen) {
999 if (newlen != attr->l) {
1000 newv = realloc(attr->v, newlen);
1009 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1010 size_t nmatch = 10, reslen = 0, start = 0;
1011 regmatch_t pmatch[10], *pfield;
1015 in = stringcopy((char *)attr->v, attr->l);
1019 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1024 out = modattr->replacement;
1026 for (i = start; out[i]; i++) {
1027 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1028 pfield = &pmatch[out[i + 1] - '0'];
1029 if (pfield->rm_so >= 0) {
1030 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1036 reslen += i - start;
1038 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1043 if (!resizeattr(attr, reslen)) {
1050 for (i = start; out[i]; i++) {
1051 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1052 pfield = &pmatch[out[i + 1] - '0'];
1053 if (pfield->rm_so >= 0) {
1054 memcpy(attr->v + reslen, out + start, i - start);
1055 reslen += i - start;
1056 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1057 reslen += pfield->rm_eo - pfield->rm_so;
1064 memcpy(attr->v + reslen, out + start, i - start);
1068 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1069 struct list_node *n, *m;
1071 for (n = list_first(msg->attrs); n; n = list_next(n))
1072 for (m = list_first(modattrs); m; m = list_next(m))
1073 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1074 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1079 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1080 int rv = 1; /* Success. */
1083 if (rewrite->removeattrs || rewrite->removevendorattrs)
1084 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1085 if (rewrite->modattrs)
1086 if (!dorewritemod(msg, rewrite->modattrs))
1088 if (rewrite->addattrs)
1089 if (!dorewriteadd(msg, rewrite->addattrs))
1095 int rewriteusername(struct request *rq, struct tlv *attr) {
1096 char *orig = (char *)tlv2str(attr);
1097 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1101 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1102 rq->origusername = (char *)orig;
1108 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1109 * all is well with the new tlv, i.e. if the function returns
1112 makevendortlv(uint32_t vendor, struct tlv *attr)
1114 struct tlv *newtlv = NULL;
1122 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1123 memcpy(v, &vendor, 4);
1124 tlv2buf(v + 4, attr);
1125 v[5] += 2; /* Vendor length increased for type and length fields. */
1126 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1135 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1137 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1140 vattr = makevendortlv(vendor, attr);
1145 if (!radmsg_add(msg, vattr)) {
1152 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1159 if (attrtype[1] == 256) { /* not vendor */
1160 attr = maketlv(attrtype[0], 4, ttl);
1161 if (attr && !radmsg_add(msg, attr))
1164 attr = maketlv(attrtype[1], 4, ttl);
1166 addvendorattr(msg, attrtype[0], attr);
1170 int decttl(uint8_t l, uint8_t *v) {
1177 while (i >= 0 && !v[i])
1181 for (i--; i >= 0 && !v[i]; i--);
1190 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1191 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1192 uint8_t alen, *subattrs;
1194 struct list_node *node;
1198 if (attrtype[1] == 256) { /* not vendor */
1199 attr = radmsg_gettype(msg, attrtype[0]);
1201 return decttl(attr->l, attr->v);
1203 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1204 attr = (struct tlv *)node->data;
1205 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1207 memcpy(&vendor, attr->v, 4);
1208 if (ntohl(vendor) != attrtype[0])
1210 sublen = attr->l - 4;
1211 subattrs = attr->v + 4;
1212 if (!attrvalidate(subattrs, sublen))
1214 while (sublen > 1) {
1215 if (ATTRTYPE(subattrs) == attrtype[1])
1216 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1217 alen = ATTRLEN(subattrs);
1225 const char *radmsgtype2string(uint8_t code) {
1226 static const char *rad_msg_names[] = {
1227 "", "Access-Request", "Access-Accept", "Access-Reject",
1228 "Accounting-Request", "Accounting-Response", "", "",
1229 "", "", "", "Access-Challenge",
1230 "Status-Server", "Status-Client"
1232 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1235 void char2hex(char *h, unsigned char c) {
1236 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1237 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1238 h[0] = hexdigits[c / 16];
1239 h[1] = hexdigits[c % 16];
1243 uint8_t *radattr2ascii(struct tlv *attr) {
1251 for (i = 0; i < attr->l; i++)
1252 if (attr->v[i] < 32 || attr->v[i] > 126)
1255 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1262 for (i = 0; i < attr->l; i++)
1263 if (attr->v[i] < 32 || attr->v[i] > 126) {
1265 char2hex((char *)d, attr->v[i]);
1273 void acclog(struct radmsg *msg, struct client *from) {
1277 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1279 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1282 username = radattr2ascii(attr);
1284 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1290 void respond(struct request *rq, uint8_t code, char *message) {
1294 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1296 debug(DBG_ERR, "respond: malloc failed");
1299 if (message && *message) {
1300 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1301 if (!attr || !radmsg_add(msg, attr)) {
1304 debug(DBG_ERR, "respond: malloc failed");
1309 radmsg_free(rq->msg);
1311 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1312 sendreply(newrqref(rq));
1315 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1316 struct list_node *entry;
1317 struct clsrvconf *server, *best = NULL, *first = NULL;
1319 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1320 server = (struct clsrvconf *)entry->data;
1321 if (!server->servers)
1323 if (server->servers->dynfailing)
1327 if (!server->servers->connectionok && !server->servers->dynstartup)
1329 if (!server->servers->lostrqs)
1335 if (server->servers->lostrqs < best->servers->lostrqs)
1338 return best ? best : first;
1341 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1342 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1343 struct clsrvconf *srvconf;
1344 struct realm *subrealm;
1345 struct server *server = NULL;
1346 char *id = (char *)tlv2str(username);
1350 /* returns with lock on realm */
1351 *realm = id2realm(realms, id);
1354 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1355 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1356 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1357 subrealm = adddynamicrealmserver(*realm, id);
1359 pthread_mutex_lock(&subrealm->mutex);
1360 pthread_mutex_unlock(&(*realm)->mutex);
1363 debug(DBG_DBG, "added realm: %s", (*realm)->name);
1364 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1365 debug(DBG_DBG, "found conf for new realm: %s", srvconf->name);
1369 debug(DBG_DBG, "found matching conf: %s", srvconf->name);
1370 server = srvconf->servers;
1379 struct request *newrequest() {
1382 rq = malloc(sizeof(struct request));
1384 debug(DBG_ERR, "newrequest: malloc failed");
1387 memset(rq, 0, sizeof(struct request));
1389 gettimeofday(&rq->created, NULL);
1394 purgedupcache(struct client *client) {
1399 gettimeofday(&now, NULL);
1400 for (i = 0; i < MAX_REQUESTS; i++) {
1402 if (r && now.tv_sec - r->created.tv_sec > r->from->conf->dupinterval) {
1404 client->rqs[i] = NULL;
1409 int addclientrq(struct request *rq) {
1413 r = rq->from->rqs[rq->rqid];
1415 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1416 gettimeofday(&now, NULL);
1417 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1419 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1420 sendreply(newrqref(r));
1422 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1428 rq->from->rqs[rq->rqid] = newrqref(rq);
1432 void rmclientrq(struct request *rq, uint8_t id) {
1435 r = rq->from->rqs[id];
1438 rq->from->rqs[id] = NULL;
1442 /* returns 0 if validation/authentication fails, else 1 */
1443 int radsrv(struct request *rq) {
1444 struct radmsg *msg = NULL;
1446 uint8_t *userascii = NULL;
1447 struct realm *realm = NULL;
1448 struct server *to = NULL;
1449 struct client *from = rq->from;
1452 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1457 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1464 memcpy(rq->rqauth, msg->auth, 16);
1466 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1467 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1468 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1472 purgedupcache(from);
1473 if (!addclientrq(rq))
1476 if (msg->code == RAD_Status_Server) {
1477 respond(rq, RAD_Access_Accept, NULL);
1481 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1483 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1486 ttlres = checkttl(msg, options.ttlattrtype);
1488 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1492 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1494 if (msg->code == RAD_Accounting_Request) {
1496 respond(rq, RAD_Accounting_Response, NULL);
1498 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1502 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1503 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1507 userascii = radattr2ascii(attr);
1510 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1512 /* will return with lock on the realm */
1513 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1515 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1520 if (realm->message && msg->code == RAD_Access_Request) {
1521 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1522 respond(rq, RAD_Access_Reject, realm->message);
1523 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1525 respond(rq, RAD_Accounting_Response, NULL);
1530 if ((to->conf->loopprevention == 1
1531 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1532 && !strcmp(from->conf->name, to->conf->name)) {
1533 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1534 from->conf->name, addr2string(from->addr), to->conf->name);
1538 if (msg->code == RAD_Accounting_Request)
1539 memset(msg->auth, 0, 16);
1540 else if (!RAND_bytes(msg->auth, 16)) {
1541 debug(DBG_WARN, "radsrv: failed to generate random auth");
1546 printfchars(NULL, "auth", "%02x ", auth, 16);
1549 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1551 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1552 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1556 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1558 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1559 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1563 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1566 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1567 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1572 pthread_mutex_unlock(&realm->mutex);
1577 rmclientrq(rq, msg->id);
1582 pthread_mutex_unlock(&realm->mutex);
1588 void replyh(struct server *server, unsigned char *buf) {
1589 struct client *from;
1590 struct rqout *rqout;
1592 unsigned char *subattrs;
1593 uint8_t *username, *stationid, *replymsg;
1594 struct radmsg *msg = NULL;
1596 struct list_node *node;
1598 server->connectionok = 1;
1599 server->lostrqs = 0;
1601 rqout = server->requests + buf[1];
1602 pthread_mutex_lock(rqout->lock);
1603 if (!rqout->tries) {
1606 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1610 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1614 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1617 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1618 && msg->code != RAD_Accounting_Response) {
1619 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1622 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1624 gettimeofday(&server->lastrcv, NULL);
1626 if (rqout->rq->msg->code == RAD_Status_Server) {
1627 freerqoutdata(rqout);
1628 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1632 gettimeofday(&server->lastreply, NULL);
1633 from = rqout->rq->from;
1635 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1636 debug(DBG_INFO, "replyh: rewritein failed");
1640 ttlres = checkttl(msg, options.ttlattrtype);
1642 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1647 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1648 attr = (struct tlv *)node->data;
1649 if (attr->t != RAD_Attr_Vendor_Specific)
1653 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1656 sublen = attr->l - 4;
1657 subattrs = attr->v + 4;
1658 if (!attrvalidate(subattrs, sublen) ||
1659 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1660 rqout->rq, server->conf->secret, from->conf->secret) ||
1661 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1662 rqout->rq, server->conf->secret, from->conf->secret))
1666 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1670 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1671 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1673 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1674 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1678 "%s for user %s stationid %s from %s (%s) to %s (%s)",
1679 radmsgtype2string(msg->code), username, stationid,
1680 server->conf->name, replymsg, from->conf->name,
1681 addr2string(from->addr));
1685 "%s for user %s stationid %s from %s to %s (%s)",
1686 radmsgtype2string(msg->code), username, stationid,
1687 server->conf->name, from->conf->name,
1688 addr2string(from->addr));
1692 debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1693 radmsgtype2string(msg->code), username,
1694 server->conf->name, replymsg, from->conf->name,
1695 addr2string(from->addr));
1698 debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1699 radmsgtype2string(msg->code), username,
1700 server->conf->name, from->conf->name,
1701 addr2string(from->addr));
1707 #if defined(WANT_FTICKS)
1708 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject)
1709 if (options.fticks_reporting && from->conf->fticks_viscountry != NULL)
1710 fticks_log(&options, from, msg, rqout);
1713 msg->id = (char)rqout->rq->rqid;
1714 memcpy(msg->auth, rqout->rq->rqauth, 16);
1717 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1720 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1721 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1722 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1725 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1728 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1729 debug(DBG_WARN, "replyh: rewriteout failed");
1733 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1734 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1736 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1737 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1739 radmsg_free(rqout->rq->msg);
1740 rqout->rq->msg = msg;
1741 sendreply(newrqref(rqout->rq));
1742 freerqoutdata(rqout);
1743 pthread_mutex_unlock(rqout->lock);
1748 pthread_mutex_unlock(rqout->lock);
1752 struct request *createstatsrvrq() {
1759 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1762 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1765 if (!radmsg_add(rq->msg, attr)) {
1776 /* code for removing state not finished */
1777 void *clientwr(void *arg) {
1778 struct server *server = (struct server *)arg;
1779 struct rqout *rqout = NULL;
1780 pthread_t clientrdth;
1781 int i, dynconffail = 0;
1784 struct timeval now, laststatsrv;
1785 struct timespec timeout;
1786 struct request *statsrvrq;
1787 struct clsrvconf *conf;
1789 conf = server->conf;
1793 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1795 server->dynstartup = 0;
1796 server->dynfailing = 1;
1797 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1798 pthread_mutex_unlock(&server->lock);
1800 debug(DBG_WARN, "%s: dynamicconfig(%s) failed, sleeping %ds",
1801 __func__, server->conf->name, ZZZ);
1805 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1806 pthread_mutex_unlock(&server->lock);
1808 /* FIXME: Is resolving not always done by compileserverconfig(),
1809 * either as part of static configuration setup or by
1810 * dynamicconfig() above? */
1811 if (!resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype)) {
1812 debug(DBG_WARN, "%s: resolve failed, sleeping %ds", __func__, ZZZ);
1817 memset(&timeout, 0, sizeof(struct timespec));
1819 if (conf->statusserver) {
1820 gettimeofday(&server->lastrcv, NULL);
1821 gettimeofday(&laststatsrv, NULL);
1824 if (conf->pdef->connecter) {
1825 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1826 if (server->dynamiclookuparg) {
1827 server->dynstartup = 0;
1828 server->dynfailing = 1;
1829 debug(DBG_WARN, "%s: connect failed, sleeping %ds",
1835 server->connectionok = 1;
1836 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1839 if (pthread_create(&clientrdth, &pthread_attr, conf->pdef->clientconnreader, (void *)server)) {
1840 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1844 server->connectionok = 1;
1845 server->dynstartup = 0;
1848 pthread_mutex_lock(&server->newrq_mutex);
1849 if (!server->newrq) {
1850 gettimeofday(&now, NULL);
1851 /* random 0-7 seconds */
1852 RAND_bytes(&rnd, 1);
1854 if (conf->statusserver) {
1855 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1856 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1858 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1859 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1861 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1862 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1865 if (timeout.tv_sec > now.tv_sec)
1866 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1868 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1871 if (server->newrq) {
1872 debug(DBG_DBG, "clientwr: got new request");
1877 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1879 pthread_mutex_unlock(&server->newrq_mutex);
1881 for (i = 0; i < MAX_REQUESTS; i++) {
1882 if (server->clientrdgone) {
1883 pthread_join(clientrdth, NULL);
1887 for (; i < MAX_REQUESTS; i++) {
1888 rqout = server->requests + i;
1890 pthread_mutex_lock(rqout->lock);
1893 pthread_mutex_unlock(rqout->lock);
1897 if (i == MAX_REQUESTS)
1900 gettimeofday(&now, NULL);
1901 if (now.tv_sec < rqout->expiry.tv_sec) {
1902 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1903 timeout.tv_sec = rqout->expiry.tv_sec;
1904 pthread_mutex_unlock(rqout->lock);
1908 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1909 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1910 if (conf->statusserver) {
1911 if (*rqout->rq->buf == RAD_Status_Server) {
1912 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1913 if (server->lostrqs < 255)
1917 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1918 if (server->lostrqs < 255)
1921 freerqoutdata(rqout);
1922 pthread_mutex_unlock(rqout->lock);
1926 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1927 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1928 timeout.tv_sec = rqout->expiry.tv_sec;
1930 conf->pdef->clientradput(server, rqout->rq->buf);
1931 pthread_mutex_unlock(rqout->lock);
1933 if (conf->statusserver && server->connectionok) {
1934 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1935 gettimeofday(&now, NULL);
1936 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1938 statsrvrq = createstatsrvrq();
1940 statsrvrq->to = server;
1941 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1948 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1951 conf->servers = NULL;
1952 if (server->dynamiclookuparg) {
1953 removeserversubrealms(realms, conf);
1957 freeclsrvconf(conf);
1959 freeserver(server, 1);
1960 ERR_remove_state(0);
1964 void createlistener(uint8_t type, char *arg) {
1966 struct addrinfo *res;
1967 int s = -1, on = 1, *sp = NULL;
1968 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1970 if (!hp || !resolvehostport(hp, AF_UNSPEC, protodefs[type]->socktype, 1))
1971 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1973 for (res = hp->addrinfo; res; res = res->ai_next) {
1974 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1976 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1979 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1981 disable_DF_bit(s, res);
1984 if (res->ai_family == AF_INET6)
1985 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1987 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1988 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1994 sp = malloc(sizeof(int));
1996 debugx(1, DBG_ERR, "malloc failed");
1998 if (pthread_create(&th, &pthread_attr, protodefs[type]->listener, (void *)sp))
1999 debugerrnox(errno, DBG_ERR, "pthread_create failed");
2003 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2005 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
2009 void createlisteners(uint8_t type) {
2013 args = protodefs[type]->getlistenerargs();
2015 for (i = 0; args[i]; i++)
2016 createlistener(type, args[i]);
2018 createlistener(type, NULL);
2026 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2027 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2028 for (i = 0; i < CRYPTO_num_locks(); i++) {
2029 ssl_lock_count[i] = 0;
2030 pthread_mutex_init(&ssl_locks[i], NULL);
2032 CRYPTO_set_id_callback(ssl_thread_id);
2033 CRYPTO_set_locking_callback(ssl_locking_callback);
2035 SSL_load_error_strings();
2038 while (!RAND_status()) {
2041 RAND_seed((unsigned char *)&t, sizeof(time_t));
2042 RAND_seed((unsigned char *)&pid, sizeof(pid));
2046 struct list *addsrvconfs(char *value, char **names) {
2047 struct list *conflist;
2049 struct list_node *entry;
2050 struct clsrvconf *conf = NULL;
2052 if (!names || !*names)
2055 conflist = list_create();
2057 debug(DBG_ERR, "malloc failed");
2061 for (n = 0; names[n]; n++) {
2062 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2063 conf = (struct clsrvconf *)entry->data;
2064 if (!strcasecmp(names[n], conf->name))
2068 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2069 list_destroy(conflist);
2072 if (!list_push(conflist, conf)) {
2073 debug(DBG_ERR, "malloc failed");
2074 list_destroy(conflist);
2077 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2082 void freerealm(struct realm *realm) {
2085 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2086 if (--realm->refcount)
2090 free(realm->message);
2091 regfree(&realm->regex);
2092 pthread_mutex_destroy(&realm->mutex);
2093 /* if refcount == 0, all subrealms gone */
2094 list_destroy(realm->subrealms);
2095 /* if refcount == 0, all srvconfs gone */
2096 list_destroy(realm->srvconfs);
2097 /* if refcount == 0, all accsrvconfs gone */
2098 list_destroy(realm->accsrvconfs);
2099 freerealm(realm->parent);
2103 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2105 struct realm *realm;
2106 char *s, *regex = NULL;
2108 if (*value == '/') {
2109 /* regexp, remove optional trailing / if present */
2110 if (value[strlen(value) - 1] == '/')
2111 value[strlen(value) - 1] = '\0';
2113 /* not a regexp, let us make it one */
2114 if (*value == '*' && !value[1])
2115 regex = stringcopy(".*", 0);
2117 for (n = 0, s = value; *s;)
2120 regex = malloc(strlen(value) + n + 3);
2123 for (n = 1, s = value; *s; s++) {
2133 debug(DBG_ERR, "malloc failed");
2137 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2140 realm = malloc(sizeof(struct realm));
2142 debug(DBG_ERR, "malloc failed");
2145 memset(realm, 0, sizeof(struct realm));
2147 if (pthread_mutex_init(&realm->mutex, NULL)) {
2148 debugerrno(errno, DBG_ERR, "mutex init failed");
2154 realm->name = stringcopy(value, 0);
2156 debug(DBG_ERR, "malloc failed");
2159 if (message && strlen(message) > 253) {
2160 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2163 realm->message = message;
2164 realm->accresp = accresp;
2166 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2167 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2171 if (servers && *servers) {
2172 realm->srvconfs = addsrvconfs(value, servers);
2173 if (!realm->srvconfs)
2177 if (accservers && *accservers) {
2178 realm->accsrvconfs = addsrvconfs(value, accservers);
2179 if (!realm->accsrvconfs)
2183 if (!list_push(realmlist, realm)) {
2184 debug(DBG_ERR, "malloc failed");
2185 pthread_mutex_destroy(&realm->mutex);
2189 debug(DBG_DBG, "addrealm: added realm %s", value);
2193 while (list_shift(realm->srvconfs));
2194 while (list_shift(realm->accsrvconfs));
2201 for (n = 0; servers[n]; n++)
2203 freegconfmstr(servers);
2207 for (n = 0; accservers[n]; n++)
2209 freegconfmstr(accservers);
2211 return newrealmref(realm);
2214 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2215 struct list_node *entry;
2216 struct clsrvconf *conf, *srvconf;
2217 struct list *subrealmservers = NULL;
2220 if (list_first(srvconfs)) {
2221 subrealmservers = list_create();
2222 if (!subrealmservers)
2226 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2227 conf = (struct clsrvconf *)entry->data;
2228 if (!conf->servers && conf->dynamiclookupcommand) {
2229 srvconf = malloc(sizeof(struct clsrvconf));
2231 debug(DBG_ERR, "malloc failed");
2234 debug(DBG_DBG, "%s: copying config %s", __func__, conf->name);
2236 /* Shallow copy -- sharing all the pointers. addserver()
2237 * will take care of servers (which btw has to be NUL) but
2238 * the rest of them are shared with the config found in
2239 * the srvconfs list. */
2240 if (addserver(srvconf)) {
2241 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2242 srvconf->servers->dynstartup = 1;
2243 debug(DBG_DBG, "%s: new client writer for %s",
2244 __func__, srvconf->servers->conf->name);
2245 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2246 pthread_mutex_lock(&srvconf->servers->lock);
2248 if (pthread_create(&clientth, &pthread_attr, clientwr, (void *)(srvconf->servers))) {
2249 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2250 pthread_mutex_unlock(&srvconf->servers->lock);
2252 debugerrno(errno, DBG_ERR, "pthread_create failed");
2253 freeserver(srvconf->servers, 1);
2254 srvconf->servers = NULL;
2255 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2260 pthread_detach(clientth);
2262 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2263 /* If clientwr() could not find a NAPTR we have to
2264 * wait for dynfailing=1 what is set in clientwr(). */
2265 pthread_mutex_lock(&srvconf->servers->lock);
2266 pthread_mutex_unlock(&srvconf->servers->lock);
2271 if (conf->servers) {
2272 if (list_push(subrealmservers, conf))
2275 debug(DBG_ERR, "malloc failed");
2278 return subrealmservers;
2281 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2282 struct realm *newrealm = NULL;
2283 char *realmname, *s;
2285 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2286 realmname = strrchr(id, '@');
2292 for (s = realmname; *s; s++)
2293 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2296 if (!realm->subrealms)
2297 realm->subrealms = list_create();
2298 if (!realm->subrealms)
2301 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2303 list_destroy(realm->subrealms);
2304 realm->subrealms = NULL;
2308 newrealm->parent = newrealmref(realm);
2309 /* add server and accserver to newrealm */
2310 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2311 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2315 int dynamicconfig(struct server *server) {
2316 int ok, fd[2], status;
2318 struct clsrvconf *conf = server->conf;
2319 struct gconffile *cf = NULL;
2321 /* for now we only learn hostname/address */
2322 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2325 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2330 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2334 } else if (pid == 0) {
2337 if (fd[1] != STDOUT_FILENO) {
2338 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2339 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2342 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2343 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2347 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2348 ok = getgenericconfig(&cf, NULL, "Server", CONF_CBK, confserver_cb,
2349 (void *) conf, NULL);
2352 if (waitpid(pid, &status, 0) < 0) {
2353 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2358 debug(DBG_INFO, "dynamicconfig: command exited with status %d",
2359 WEXITSTATUS(status));
2367 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2371 /* should accept both names and numeric values, only numeric right now */
2372 uint8_t attrname2val(char *attrname) {
2375 val = atoi(attrname);
2376 return val > 0 && val < 256 ? val : 0;
2379 /* ATTRNAME is on the form vendor[:type].
2380 If only vendor is found, TYPE is set to 256 and 1 is returned.
2381 If type is >= 256, 1 is returned.
2382 Otherwise, 0 is returned.
2384 /* should accept both names and numeric values, only numeric right now */
2385 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2388 *vendor = atoi(attrname);
2389 s = strchr(attrname, ':');
2390 if (!s) { /* Only vendor was found. */
2394 *type = atoi(s + 1);
2398 /** Extract attributes from string NAMEVAL, create a struct tlv and
2399 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2400 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2401 * NULL if fields are missing or if conversion fails.
2403 * FIXME: Should accept both names and numeric values, only numeric
2405 struct tlv *extractattr(char *nameval, char vendor_flag) {
2407 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2411 s = strchr(nameval, ':');
2414 name = atoi(nameval);
2417 s2 = strchr(s + 1, ':');
2424 len = strlen(s + 1);
2428 if (name < 1 || name > 255)
2430 a = malloc(sizeof(struct tlv));
2434 a->v = (uint8_t *)stringcopy(s + 1, 0);
2443 a = makevendortlv(vendor, a);
2448 /* should accept both names and numeric values, only numeric right now */
2449 struct modattr *extractmodattr(char *nameval) {
2454 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2458 s = strchr(nameval, ':');
2459 name = atoi(nameval);
2460 if (!s || name < 1 || name > 255 || s[1] != '/')
2464 /* regexp, remove optional trailing / if present */
2465 if (s[strlen(s) - 1] == '/')
2466 s[strlen(s) - 1] = '\0';
2468 for (t = strchr(s, '/'); t; t = strchr(t+1, '/'))
2469 if (t == s || t[-1] != '\\')
2476 m = malloc(sizeof(struct modattr));
2478 debug(DBG_ERR, "malloc failed");
2483 m->replacement = stringcopy(t, 0);
2484 if (!m->replacement) {
2486 debug(DBG_ERR, "malloc failed");
2490 m->regex = malloc(sizeof(regex_t));
2492 free(m->replacement);
2494 debug(DBG_ERR, "malloc failed");
2498 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2500 free(m->replacement);
2502 debug(DBG_ERR, "failed to compile regular expression %s", s);
2509 struct rewrite *getrewrite(char *alt1, char *alt2) {
2513 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2516 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2521 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2523 struct rewrite *rewrite = NULL;
2525 uint8_t *rma = NULL;
2526 uint32_t *p, *rmva = NULL;
2527 struct list *adda = NULL, *moda = NULL;
2532 for (n = 0; rmattrs[n]; n++);
2533 rma = calloc(n + 1, sizeof(uint8_t));
2535 debugx(1, DBG_ERR, "malloc failed");
2537 for (i = 0; i < n; i++)
2538 if (!(rma[i] = attrname2val(rmattrs[i])))
2539 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2540 freegconfmstr(rmattrs);
2545 for (n = 0; rmvattrs[n]; n++);
2546 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2548 debugx(1, DBG_ERR, "malloc failed");
2550 for (p = rmva, i = 0; i < n; i++, p += 2)
2551 if (!vattrname2val(rmvattrs[i], p, p + 1))
2552 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2553 freegconfmstr(rmvattrs);
2558 adda = list_create();
2560 debugx(1, DBG_ERR, "malloc failed");
2561 for (i = 0; addattrs[i]; i++) {
2562 a = extractattr(addattrs[i], 0);
2564 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2565 if (!list_push(adda, a))
2566 debugx(1, DBG_ERR, "malloc failed");
2568 freegconfmstr(addattrs);
2573 adda = list_create();
2575 debugx(1, DBG_ERR, "malloc failed");
2576 for (i = 0; addvattrs[i]; i++) {
2577 a = extractattr(addvattrs[i], 1);
2579 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2580 if (!list_push(adda, a))
2581 debugx(1, DBG_ERR, "malloc failed");
2583 freegconfmstr(addvattrs);
2587 moda = list_create();
2589 debugx(1, DBG_ERR, "malloc failed");
2590 for (i = 0; modattrs[i]; i++) {
2591 m = extractmodattr(modattrs[i]);
2593 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2594 if (!list_push(moda, m))
2595 debugx(1, DBG_ERR, "malloc failed");
2597 freegconfmstr(modattrs);
2600 if (rma || rmva || adda || moda) {
2601 rewrite = malloc(sizeof(struct rewrite));
2603 debugx(1, DBG_ERR, "malloc failed");
2604 rewrite->removeattrs = rma;
2605 rewrite->removevendorattrs = rmva;
2606 rewrite->addattrs = adda;
2607 rewrite->modattrs = moda;
2610 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2611 debugx(1, DBG_ERR, "malloc failed");
2612 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2615 int setttlattr(struct options *opts, char *defaultattr) {
2616 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2618 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2619 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2621 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2625 void freeclsrvconf(struct clsrvconf *conf) {
2628 debug(DBG_DBG, "%s: freeing %p (%s)", __func__, conf, conf->name);
2631 freegconfmstr(conf->hostsrc);
2632 free(conf->portsrc);
2635 free(conf->matchcertattr);
2636 if (conf->certcnregex)
2637 regfree(conf->certcnregex);
2638 if (conf->certuriregex)
2639 regfree(conf->certuriregex);
2640 free(conf->confrewritein);
2641 free(conf->confrewriteout);
2642 if (conf->rewriteusername) {
2643 if (conf->rewriteusername->regex)
2644 regfree(conf->rewriteusername->regex);
2645 free(conf->rewriteusername->replacement);
2646 free(conf->rewriteusername);
2648 free(conf->dynamiclookupcommand);
2649 conf->rewritein=NULL;
2650 conf->rewriteout=NULL;
2651 if (conf->hostports)
2652 freehostports(conf->hostports);
2654 pthread_mutex_destroy(conf->lock);
2657 /* not touching ssl_ctx, clients and servers */
2661 int mergeconfstring(char **dst, char **src) {
2670 t = stringcopy(*dst, 0);
2672 debug(DBG_ERR, "malloc failed");
2680 char **mstringcopy(char **in) {
2687 for (n = 0; in[n]; n++);
2688 out = malloc((n + 1) * sizeof(char *));
2691 for (n = 0; in[n]; n++) {
2692 out[n] = stringcopy(in[n], 0);
2702 int mergeconfmstring(char ***dst, char ***src) {
2711 t = mstringcopy(*dst);
2713 debug(DBG_ERR, "malloc failed");
2721 /* assumes dst is a shallow copy */
2722 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2723 if (!mergeconfstring(&dst->name, &src->name) ||
2724 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2725 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2726 !mergeconfstring(&dst->secret, &src->secret) ||
2727 !mergeconfstring(&dst->tls, &src->tls) ||
2728 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2729 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2730 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2731 !mergeconfstring(&dst->confrewriteusername, &src->confrewriteusername) ||
2732 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand) ||
2733 !mergeconfstring(&dst->fticks_viscountry, &src->fticks_viscountry) ||
2734 !mergeconfstring(&dst->fticks_visinst, &src->fticks_visinst))
2737 dst->pdef = src->pdef;
2738 dst->statusserver = src->statusserver;
2739 dst->certnamecheck = src->certnamecheck;
2740 if (src->retryinterval != 255)
2741 dst->retryinterval = src->retryinterval;
2742 if (src->retrycount != 255)
2743 dst->retrycount = src->retrycount;
2747 /** Set *AF according to IPV4ONLY and IPV6ONLY:
2748 - If both are set, the function fails.
2749 - If exactly one is set, *AF is set accordingly.
2750 - If none is set, *AF is not affected.
2751 Return 0 on success and !0 on failure.
2752 In the case of an error, *AF is not affected. */
2753 int config_hostaf(const char *desc, int ipv4only, int ipv6only, int *af) {
2755 if (ipv4only && ipv6only) {
2756 debug(DBG_ERR, "error in block %s, at most one of IPv4Only and "
2757 "IPv6Only can be enabled", desc);
2767 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2768 struct clsrvconf *conf;
2769 char *conftype = NULL, *rewriteinalias = NULL;
2770 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2771 uint8_t ipv4only = 0, ipv6only = 0;
2773 debug(DBG_DBG, "confclient_cb called for %s", block);
2775 conf = malloc(sizeof(struct clsrvconf));
2777 debugx(1, DBG_ERR, "malloc failed");
2778 memset(conf, 0, sizeof(struct clsrvconf));
2779 conf->certnamecheck = 1;
2781 if (!getgenericconfig(
2783 "type", CONF_STR, &conftype,
2784 "host", CONF_MSTR, &conf->hostsrc,
2785 "IPv4Only", CONF_BLN, &ipv4only,
2786 "IPv6Only", CONF_BLN, &ipv6only,
2787 "secret", CONF_STR, &conf->secret,
2788 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2789 "tls", CONF_STR, &conf->tls,
2790 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2791 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2793 "DuplicateInterval", CONF_LINT, &dupinterval,
2794 "addTTL", CONF_LINT, &addttl,
2795 "rewrite", CONF_STR, &rewriteinalias,
2796 "rewriteIn", CONF_STR, &conf->confrewritein,
2797 "rewriteOut", CONF_STR, &conf->confrewriteout,
2798 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2799 #if defined(WANT_FTICKS)
2800 "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2801 "fticksVISINST", CONF_STR, &conf->fticks_visinst,
2805 debugx(1, DBG_ERR, "configuration error");
2807 conf->name = stringcopy(val, 0);
2808 if (conf->name && !conf->hostsrc) {
2809 conf->hostsrc = malloc(2 * sizeof(char *));
2810 if (conf->hostsrc) {
2811 conf->hostsrc[0] = stringcopy(val, 0);
2812 conf->hostsrc[1] = NULL;
2815 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2816 debugx(1, DBG_ERR, "malloc failed");
2819 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2820 conf->type = protoname2int(conftype);
2821 if (conf->type == 255)
2822 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2824 conf->pdef = protodefs[conf->type];
2826 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2827 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2828 conf->tlsconf = conf->tls
2829 ? tlsgettls(conf->tls, NULL)
2830 : tlsgettls("defaultClient", "default");
2832 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2833 if (conf->matchcertattr && !addmatchcertattr(conf))
2834 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2838 conf->hostaf = AF_UNSPEC;
2839 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
2840 debugx(1, DBG_ERR, "config error: ^");
2841 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
2842 debugx(1, DBG_ERR, "error in block %s: ^", block);
2844 if (dupinterval != LONG_MIN) {
2845 if (dupinterval < 0 || dupinterval > 255)
2846 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2847 conf->dupinterval = (uint8_t)dupinterval;
2849 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2851 if (addttl != LONG_MIN) {
2852 if (addttl < 1 || addttl > 255)
2853 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2854 conf->addttl = (uint8_t)addttl;
2857 if (!conf->confrewritein)
2858 conf->confrewritein = rewriteinalias;
2860 free(rewriteinalias);
2861 conf->rewritein = conf->confrewritein
2862 ? getrewrite(conf->confrewritein, NULL)
2863 : getrewrite("defaultClient", "default");
2864 if (conf->confrewriteout)
2865 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2867 if (conf->confrewriteusername) {
2868 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2869 if (!conf->rewriteusername)
2870 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2873 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2874 !resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype))
2875 debugx(1, DBG_ERR, "%s: resolve failed, exiting", __func__);
2877 if (!conf->secret) {
2878 if (!conf->pdef->secretdefault)
2879 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2880 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2882 debugx(1, DBG_ERR, "malloc failed");
2885 conf->lock = malloc(sizeof(pthread_mutex_t));
2887 debugx(1, DBG_ERR, "malloc failed");
2889 pthread_mutex_init(conf->lock, NULL);
2890 if (!list_push(clconfs, conf))
2891 debugx(1, DBG_ERR, "malloc failed");
2895 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2896 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2897 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2898 conf->tlsconf = conf->tls
2899 ? tlsgettls(conf->tls, NULL)
2900 : tlsgettls("defaultServer", "default");
2901 if (!conf->tlsconf) {
2902 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2905 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2906 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2912 if (!conf->portsrc) {
2913 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2914 if (!conf->portsrc) {
2915 debug(DBG_ERR, "malloc failed");
2920 if (conf->retryinterval == 255)
2921 conf->retryinterval = conf->pdef->retryintervaldefault;
2922 if (conf->retrycount == 255)
2923 conf->retrycount = conf->pdef->retrycountdefault;
2925 conf->rewritein = conf->confrewritein
2926 ? getrewrite(conf->confrewritein, NULL)
2927 : getrewrite("defaultServer", "default");
2928 if (conf->confrewriteout)
2929 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2931 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2932 debug(DBG_ERR, "error in block %s, failed to parse %s", block, *conf->hostsrc);
2936 if (!conf->dynamiclookupcommand &&
2937 !resolvehostports(conf->hostports, conf->hostaf,
2938 conf->pdef->socktype)) {
2939 debug(DBG_ERR, "%s: resolve failed", __func__);
2945 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2946 struct clsrvconf *conf, *resconf;
2947 char *conftype = NULL, *rewriteinalias = NULL;
2948 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2949 uint8_t ipv4only = 0, ipv6only = 0;
2951 debug(DBG_DBG, "confserver_cb called for %s", block);
2953 conf = malloc(sizeof(struct clsrvconf));
2955 debug(DBG_ERR, "malloc failed");
2958 memset(conf, 0, sizeof(struct clsrvconf));
2959 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2960 resconf = (struct clsrvconf *)arg;
2962 conf->statusserver = resconf->statusserver;
2963 conf->certnamecheck = resconf->certnamecheck;
2965 conf->certnamecheck = 1;
2967 if (!getgenericconfig(cf, block,
2968 "type", CONF_STR, &conftype,
2969 "host", CONF_MSTR, &conf->hostsrc,
2970 "IPv4Only", CONF_BLN, &ipv4only,
2971 "IPv6Only", CONF_BLN, &ipv6only,
2972 "port", CONF_STR, &conf->portsrc,
2973 "secret", CONF_STR, &conf->secret,
2974 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2975 "tls", CONF_STR, &conf->tls,
2976 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2977 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2979 "addTTL", CONF_LINT, &addttl,
2980 "rewrite", CONF_STR, &rewriteinalias,
2981 "rewriteIn", CONF_STR, &conf->confrewritein,
2982 "rewriteOut", CONF_STR, &conf->confrewriteout,
2983 "StatusServer", CONF_BLN, &conf->statusserver,
2984 "RetryInterval", CONF_LINT, &retryinterval,
2985 "RetryCount", CONF_LINT, &retrycount,
2986 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2987 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2990 debug(DBG_ERR, "configuration error");
2994 conf->name = stringcopy(val, 0);
2995 if (conf->name && !conf->hostsrc) {
2996 conf->hostsrc = malloc(2 * sizeof(char *));
2997 if (conf->hostsrc) {
2998 conf->hostsrc[0] = stringcopy(val, 0);
2999 conf->hostsrc[1] = NULL;
3002 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
3003 debug(DBG_ERR, "malloc failed");
3008 debug(DBG_ERR, "error in block %s, option type missing", block);
3011 conf->type = protoname2int(conftype);
3012 if (conf->type == 255) {
3013 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3019 conf->hostaf = AF_UNSPEC;
3020 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
3021 debugx(1, DBG_ERR, "config error: ^");
3022 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
3025 conf->pdef = protodefs[conf->type];
3027 if (!conf->confrewritein)
3028 conf->confrewritein = rewriteinalias;
3030 free(rewriteinalias);
3031 rewriteinalias = NULL;
3033 if (retryinterval != LONG_MIN) {
3034 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3035 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3038 conf->retryinterval = (uint8_t)retryinterval;
3040 conf->retryinterval = 255;
3042 if (retrycount != LONG_MIN) {
3043 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3044 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3047 conf->retrycount = (uint8_t)retrycount;
3049 conf->retrycount = 255;
3051 if (addttl != LONG_MIN) {
3052 if (addttl < 1 || addttl > 255) {
3053 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3056 conf->addttl = (uint8_t)addttl;
3060 if (!mergesrvconf(resconf, conf))
3064 if (conf->dynamiclookupcommand) {
3065 free(conf->dynamiclookupcommand);
3066 conf->dynamiclookupcommand = NULL;
3070 if (resconf || !conf->dynamiclookupcommand) {
3071 if (!compileserverconfig(conf, block))
3072 return 0; /* Don't goto errexit and free resconf -- it's
3073 * not ours to free. */
3076 if (!conf->secret) {
3077 if (!conf->pdef->secretdefault) {
3078 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3081 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3082 if (!conf->secret) {
3083 debug(DBG_ERR, "malloc failed");
3091 if (!list_push(srvconfs, conf)) {
3092 debug(DBG_ERR, "malloc failed");
3099 free(rewriteinalias);
3100 freeclsrvconf(conf);
3104 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3105 char **servers = NULL, **accservers = NULL, *msg = NULL;
3106 uint8_t accresp = 0;
3108 debug(DBG_DBG, "confrealm_cb called for %s", block);
3110 if (!getgenericconfig(cf, block,
3111 "server", CONF_MSTR, &servers,
3112 "accountingServer", CONF_MSTR, &accservers,
3113 "ReplyMessage", CONF_STR, &msg,
3114 "AccountingResponse", CONF_BLN, &accresp,
3117 debugx(1, DBG_ERR, "configuration error");
3119 addrealm(realms, val, servers, accservers, msg, accresp);
3123 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3124 char **rmattrs = NULL, **rmvattrs = NULL;
3125 char **addattrs = NULL, **addvattrs = NULL;
3126 char **modattrs = NULL;
3128 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3130 if (!getgenericconfig(cf, block,
3131 "removeAttribute", CONF_MSTR, &rmattrs,
3132 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3133 "addAttribute", CONF_MSTR, &addattrs,
3134 "addVendorAttribute", CONF_MSTR, &addvattrs,
3135 "modifyAttribute", CONF_MSTR, &modattrs,
3138 debugx(1, DBG_ERR, "configuration error");
3139 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
3143 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3144 struct commonprotoopts *protoopts;
3146 protoopts = malloc(sizeof(struct commonprotoopts));
3149 memset(protoopts, 0, sizeof(struct commonprotoopts));
3150 protoopts->listenargs = listenargs;
3151 protoopts->sourcearg = sourcearg;
3152 protodefs[type]->setprotoopts(protoopts);
3156 void getmainconfig(const char *configfile) {
3157 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3158 struct gconffile *cfs;
3159 char **listenargs[RAD_PROTOCOUNT];
3160 char *sourcearg[RAD_PROTOCOUNT];
3161 #if defined(WANT_FTICKS)
3162 uint8_t *fticks_reporting_str = NULL;
3163 uint8_t *fticks_mac_str = NULL;
3164 uint8_t *fticks_key_str = NULL;
3168 cfs = openconfigfile(configfile);
3169 memset(&options, 0, sizeof(options));
3170 memset(&listenargs, 0, sizeof(listenargs));
3171 memset(&sourcearg, 0, sizeof(sourcearg));
3173 clconfs = list_create();
3175 debugx(1, DBG_ERR, "malloc failed");
3177 srvconfs = list_create();
3179 debugx(1, DBG_ERR, "malloc failed");
3181 realms = list_create();
3183 debugx(1, DBG_ERR, "malloc failed");
3185 rewriteconfs = hash_create();
3187 debugx(1, DBG_ERR, "malloc failed");
3189 if (!getgenericconfig(
3192 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3193 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3196 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3197 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3200 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3201 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3204 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3205 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3207 "PidFile", CONF_STR, &options.pidfile,
3208 "TTLAttribute", CONF_STR, &options.ttlattr,
3209 "addTTL", CONF_LINT, &addttl,
3210 "LogLevel", CONF_LINT, &loglevel,
3211 "LogDestination", CONF_STR, &options.logdestination,
3212 "LoopPrevention", CONF_BLN, &options.loopprevention,
3213 "Client", CONF_CBK, confclient_cb, NULL,
3214 "Server", CONF_CBK, confserver_cb, NULL,
3215 "Realm", CONF_CBK, confrealm_cb, NULL,
3216 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3217 "TLS", CONF_CBK, conftls_cb, NULL,
3219 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3220 #if defined(WANT_FTICKS)
3221 "FTicksReporting", CONF_STR, &fticks_reporting_str,
3222 "FTicksMAC", CONF_STR, &fticks_mac_str,
3223 "FTicksKey", CONF_STR, &fticks_key_str,
3224 "FTicksSyslogFacility", CONF_STR, &options.ftickssyslogfacility,
3226 "IPv4Only", CONF_BLN, &options.ipv4only,
3227 "IPv6Only", CONF_BLN, &options.ipv6only,
3230 debugx(1, DBG_ERR, "configuration error");
3232 if (loglevel != LONG_MIN) {
3233 if (loglevel < 1 || loglevel > 5)
3234 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3235 options.loglevel = (uint8_t)loglevel;
3237 if (addttl != LONG_MIN) {
3238 if (addttl < 1 || addttl > 255)
3239 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3240 options.addttl = (uint8_t)addttl;
3242 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3243 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3245 #if defined(WANT_FTICKS)
3246 fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3250 for (i = 0; i < RAD_PROTOCOUNT; i++)
3251 if (listenargs[i] || sourcearg[i])
3252 setprotoopts(i, listenargs[i], sourcearg[i]);
3255 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3258 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3261 *configfile = optarg;
3264 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3265 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3266 *loglevel = *optarg - '0';
3278 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3279 debug(DBG_ERR, "This binary was built with support for the following transports:");
3281 debug(DBG_ERR, " UDP");
3284 debug(DBG_ERR, " TCP");
3287 debug(DBG_ERR, " TLS");
3290 debug(DBG_ERR, " DTLS");
3297 if (!(argc - optind))
3301 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3305 int daemon(int a, int b) {
3313 for (i = 0; i < 3; i++) {
3315 open("/dev/null", O_RDWR);
3321 void *sighandler(void *arg) {
3326 sigemptyset(&sigset);
3327 sigaddset(&sigset, SIGHUP);
3328 sigaddset(&sigset, SIGPIPE);
3329 sigwait(&sigset, &sig);
3332 /* completely ignoring this */
3335 debug(DBG_INFO, "sighandler: got SIGHUP");
3339 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3342 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3347 int createpidfile(const char *pidfile) {
3349 FILE *f = fopen(pidfile, "w");
3351 r = fprintf(f, "%ld\n", (long) getpid());
3352 return f && !fclose(f) && r >= 0;
3355 int radsecproxy_main(int argc, char **argv) {
3358 struct list_node *entry;
3359 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3360 char *configfile = NULL, *pidfile = NULL;
3361 struct clsrvconf *srvconf;
3364 debug_init("radsecproxy");
3365 debug_set_level(DEBUG_LEVEL);
3367 if (pthread_attr_init(&pthread_attr))
3368 debugx(1, DBG_ERR, "pthread_attr_init failed");
3369 if (pthread_attr_setstacksize(&pthread_attr, PTHREAD_STACK_SIZE))
3370 debugx(1, DBG_ERR, "pthread_attr_setstacksize failed");
3371 #if defined(HAVE_MALLOPT)
3372 if (mallopt(M_TRIM_THRESHOLD, 4 * 1024) != 1)
3373 debugx(1, DBG_ERR, "mallopt failed");
3376 for (i = 0; i < RAD_PROTOCOUNT; i++)
3377 protodefs[i] = protoinits[i](i);
3379 /* needed even if no TLS/DTLS transport */
3382 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3384 debug_set_level(loglevel);
3385 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3387 options.loglevel = loglevel;
3388 else if (options.loglevel)
3389 debug_set_level(options.loglevel);
3391 debug_set_destination(options.logdestination
3392 ? options.logdestination
3393 : "x-syslog:///", LOG_TYPE_DEBUG);
3394 #if defined(WANT_FTICKS)
3395 if (options.ftickssyslogfacility) {
3396 debug_set_destination(options.ftickssyslogfacility,
3398 free(options.ftickssyslogfacility);
3402 free(options.logdestination);
3404 if (!list_first(clconfs))
3405 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3406 if (!list_first(realms))
3407 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3410 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3412 if (!foreground && (daemon(0, 0) < 0))
3413 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3415 debug_timestamp_on();
3416 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3418 pidfile = options.pidfile;
3419 if (pidfile && !createpidfile(pidfile))
3420 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3422 sigemptyset(&sigset);
3423 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3424 sigaddset(&sigset, SIGHUP);
3425 sigaddset(&sigset, SIGPIPE);
3426 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3427 pthread_create(&sigth, &pthread_attr, sighandler, NULL);
3429 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3430 srvconf = (struct clsrvconf *)entry->data;
3431 if (srvconf->dynamiclookupcommand)
3433 if (!addserver(srvconf))
3434 debugx(1, DBG_ERR, "failed to add server");
3435 if (pthread_create(&srvconf->servers->clientth, &pthread_attr, clientwr,
3436 (void *)(srvconf->servers)))
3437 debugx(1, DBG_ERR, "pthread_create failed");
3440 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3443 if (protodefs[i]->initextra)
3444 protodefs[i]->initextra();
3445 if (find_clconf_type(i, NULL))
3449 /* just hang around doing nothing, anything to do here? */
3454 /* Local Variables: */
3455 /* c-file-style: "stroustrup" */