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>
59 #include <sys/types.h>
62 #include <arpa/inet.h>
68 #include <openssl/ssl.h>
69 #include <openssl/rand.h>
70 #include <openssl/err.h>
71 #include <openssl/md5.h>
76 #include "radsecproxy.h"
81 #if defined(WANT_FTICKS)
85 static struct options options;
86 static struct list *clconfs, *srvconfs;
87 static struct list *realms;
88 static struct hash *rewriteconfs;
90 static pthread_mutex_t *ssl_locks = NULL;
91 static long *ssl_lock_count;
94 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
96 /* minimum required declarations to avoid reordering code */
97 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
98 int dynamicconfig(struct server *server);
99 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
100 void freerealm(struct realm *realm);
101 void freeclsrvconf(struct clsrvconf *conf);
102 void freerq(struct request *rq);
103 void freerqoutdata(struct rqout *rqout);
104 void rmclientrq(struct request *rq, uint8_t id);
106 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
108 uint8_t protoname2int(const char *name) {
111 for (i = 0; i < RAD_PROTOCOUNT; i++)
112 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
117 /* callbacks for making OpenSSL thread safe */
118 unsigned long ssl_thread_id() {
119 return (unsigned long)pthread_self();
122 void ssl_locking_callback(int mode, int type, const char *file, int line) {
123 if (mode & CRYPTO_LOCK) {
124 pthread_mutex_lock(&ssl_locks[type]);
125 ssl_lock_count[type]++;
127 pthread_mutex_unlock(&ssl_locks[type]);
130 /* returns 1 if the len first bits are equal, else 0 */
131 int prefixmatch(void *a1, void *a2, uint8_t len) {
132 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
133 uint8_t r, l = len / 8;
134 if (l && memcmp(a1, a2, l))
139 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
142 /* returns next config with matching address, or NULL */
143 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
144 struct list_node *entry;
145 struct clsrvconf *conf;
147 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
148 conf = (struct clsrvconf *)entry->data;
149 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
158 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
159 return find_conf(type, addr, clconfs, cur, 0);
162 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
163 return find_conf(type, addr, srvconfs, cur, 1);
166 /* returns next config of given type, or NULL */
167 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
168 struct list_node *entry;
169 struct clsrvconf *conf;
171 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
172 conf = (struct clsrvconf *)entry->data;
173 if (conf->type == type) {
182 struct gqueue *newqueue() {
185 q = malloc(sizeof(struct gqueue));
187 debugx(1, DBG_ERR, "malloc failed");
188 q->entries = list_create();
190 debugx(1, DBG_ERR, "malloc failed");
191 pthread_mutex_init(&q->mutex, NULL);
192 pthread_cond_init(&q->cond, NULL);
196 void removequeue(struct gqueue *q) {
197 struct list_node *entry;
201 pthread_mutex_lock(&q->mutex);
202 for (entry = list_first(q->entries); entry; entry = list_next(entry))
203 freerq((struct request *)entry);
204 list_destroy(q->entries);
205 pthread_cond_destroy(&q->cond);
206 pthread_mutex_unlock(&q->mutex);
207 pthread_mutex_destroy(&q->mutex);
211 void freebios(struct gqueue *q) {
214 pthread_mutex_lock(&q->mutex);
215 while ((bio = (BIO *)list_shift(q->entries)))
217 pthread_mutex_unlock(&q->mutex);
221 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
222 struct client *new = malloc(sizeof(struct client));
225 debug(DBG_ERR, "malloc failed");
230 pthread_mutex_lock(conf->lock);
231 if (!conf->clients) {
232 conf->clients = list_create();
233 if (!conf->clients) {
235 pthread_mutex_unlock(conf->lock);
236 debug(DBG_ERR, "malloc failed");
241 memset(new, 0, sizeof(struct client));
243 if (conf->pdef->addclient)
244 conf->pdef->addclient(new);
246 new->replyq = newqueue();
247 list_push(conf->clients, new);
249 pthread_mutex_unlock(conf->lock);
253 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
254 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
257 pthread_mutex_lock(&lock);
259 pthread_mutex_unlock(&lock);
262 void removeclientrqs(struct client *client) {
267 removeclientrqs_sendrq_freeserver_lock(1);
268 for (i = 0; i < MAX_REQUESTS; i++) {
273 rqout = rq->to->requests + rq->newid;
274 pthread_mutex_lock(rqout->lock);
275 if (rqout->rq == rq) /* still pointing to our request */
276 freerqoutdata(rqout);
277 pthread_mutex_unlock(rqout->lock);
281 removeclientrqs_sendrq_freeserver_lock(0);
284 void removelockedclient(struct client *client) {
285 struct clsrvconf *conf;
289 removeclientrqs(client);
290 removequeue(client->replyq);
291 list_removedata(conf->clients, client);
297 void removeclient(struct client *client) {
298 struct clsrvconf *conf;
304 pthread_mutex_lock(conf->lock);
305 removelockedclient(client);
306 pthread_mutex_unlock(conf->lock);
309 void freeserver(struct server *server, uint8_t destroymutex) {
310 struct rqout *rqout, *end;
315 removeclientrqs_sendrq_freeserver_lock(1);
316 if (server->requests) {
317 rqout = server->requests;
318 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
320 rqout->rq->to = NULL;
321 freerqoutdata(rqout);
322 pthread_mutex_destroy(rqout->lock);
325 free(server->requests);
328 freebios(server->rbios);
329 free(server->dynamiclookuparg);
331 #if defined ENABLE_EXPERIMENTAL_DYNDISC
332 if (server->sock >= 0)
335 SSL_free(server->ssl);
338 pthread_mutex_destroy(&server->lock);
339 pthread_cond_destroy(&server->newrq_cond);
340 pthread_mutex_destroy(&server->newrq_mutex);
342 removeclientrqs_sendrq_freeserver_lock(0);
346 int addserver(struct clsrvconf *conf) {
350 debug(DBG_ERR, "addserver: currently works with just one server per conf");
353 conf->servers = malloc(sizeof(struct server));
354 if (!conf->servers) {
355 debug(DBG_ERR, "malloc failed");
358 memset(conf->servers, 0, sizeof(struct server));
359 conf->servers->conf = conf;
362 if (conf->type == RAD_DTLS)
363 conf->servers->rbios = newqueue();
365 conf->pdef->setsrcres();
367 conf->servers->sock = -1;
368 if (conf->pdef->addserverextra)
369 conf->pdef->addserverextra(conf);
371 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
372 if (!conf->servers->requests) {
373 debug(DBG_ERR, "malloc failed");
376 for (i = 0; i < MAX_REQUESTS; i++) {
377 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
378 if (!conf->servers->requests[i].lock) {
379 debug(DBG_ERR, "malloc failed");
382 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
383 debugerrno(errno, DBG_ERR, "mutex init failed");
384 free(conf->servers->requests[i].lock);
385 conf->servers->requests[i].lock = NULL;
389 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
390 debugerrno(errno, DBG_ERR, "mutex init failed");
393 conf->servers->newrq = 0;
394 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
395 debugerrno(errno, DBG_ERR, "mutex init failed");
396 pthread_mutex_destroy(&conf->servers->lock);
399 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
400 debugerrno(errno, DBG_ERR, "mutex init failed");
401 pthread_mutex_destroy(&conf->servers->newrq_mutex);
402 pthread_mutex_destroy(&conf->servers->lock);
409 freeserver(conf->servers, 0);
410 conf->servers = NULL;
414 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
416 if (ATTRTYPE(attrs) == type)
418 length -= ATTRLEN(attrs);
419 attrs += ATTRLEN(attrs);
424 struct request *newrqref(struct request *rq) {
430 void freerq(struct request *rq) {
433 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
436 if (rq->origusername)
437 free(rq->origusername);
443 radmsg_free(rq->msg);
447 void freerqoutdata(struct rqout *rqout) {
451 if (rqout->rq->buf) {
452 free(rqout->rq->buf);
453 rqout->rq->buf = NULL;
459 memset(&rqout->expiry, 0, sizeof(struct timeval));
462 void sendrq(struct request *rq) {
466 removeclientrqs_sendrq_freeserver_lock(1);
471 start = to->conf->statusserver ? 1 : 0;
472 pthread_mutex_lock(&to->newrq_mutex);
473 if (start && rq->msg->code == RAD_Status_Server) {
474 pthread_mutex_lock(to->requests[0].lock);
475 if (to->requests[0].rq) {
476 pthread_mutex_unlock(to->requests[0].lock);
477 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
484 /* might simplify if only try nextid, might be ok */
485 for (i = to->nextid; i < MAX_REQUESTS; i++) {
486 if (!to->requests[i].rq) {
487 pthread_mutex_lock(to->requests[i].lock);
488 if (!to->requests[i].rq)
490 pthread_mutex_unlock(to->requests[i].lock);
493 if (i == MAX_REQUESTS) {
494 for (i = start; i < to->nextid; i++) {
495 if (!to->requests[i].rq) {
496 pthread_mutex_lock(to->requests[i].lock);
497 if (!to->requests[i].rq)
499 pthread_mutex_unlock(to->requests[i].lock);
502 if (i == to->nextid) {
503 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
508 rq->newid = (uint8_t)i;
509 rq->msg->id = (uint8_t)i;
510 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
512 pthread_mutex_unlock(to->requests[i].lock);
513 debug(DBG_ERR, "sendrq: radmsg2buf failed");
517 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
518 to->requests[i].rq = rq;
519 pthread_mutex_unlock(to->requests[i].lock);
520 if (i >= start) /* i is not reserved for statusserver */
525 debug(DBG_DBG, "sendrq: signalling client writer");
526 pthread_cond_signal(&to->newrq_cond);
529 pthread_mutex_unlock(&to->newrq_mutex);
530 removeclientrqs_sendrq_freeserver_lock(0);
535 rmclientrq(rq, rq->msg->id);
537 pthread_mutex_unlock(&to->newrq_mutex);
538 removeclientrqs_sendrq_freeserver_lock(0);
541 void sendreply(struct request *rq) {
543 struct client *to = rq->from;
546 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
547 radmsg_free(rq->msg);
551 debug(DBG_ERR, "sendreply: radmsg2buf failed");
555 pthread_mutex_lock(&to->replyq->mutex);
556 first = list_first(to->replyq->entries) == NULL;
558 if (!list_push(to->replyq->entries, rq)) {
559 pthread_mutex_unlock(&to->replyq->mutex);
561 debug(DBG_ERR, "sendreply: malloc failed");
566 debug(DBG_DBG, "signalling server writer");
567 pthread_cond_signal(&to->replyq->cond);
569 pthread_mutex_unlock(&to->replyq->mutex);
572 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
573 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
574 static unsigned char first = 1;
575 static EVP_MD_CTX mdctx;
576 unsigned char hash[EVP_MAX_MD_SIZE], *input;
578 uint8_t i, offset = 0, out[128];
580 pthread_mutex_lock(&lock);
582 EVP_MD_CTX_init(&mdctx);
588 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
589 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
590 !EVP_DigestUpdate(&mdctx, input, 16) ||
591 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
593 pthread_mutex_unlock(&lock);
596 for (i = 0; i < 16; i++)
597 out[offset + i] = hash[i] ^ in[offset + i];
599 input = out + offset;
606 memcpy(in, out, len);
607 pthread_mutex_unlock(&lock);
611 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
612 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
613 static unsigned char first = 1;
614 static EVP_MD_CTX mdctx;
615 unsigned char hash[EVP_MAX_MD_SIZE];
619 pthread_mutex_lock(&lock);
621 EVP_MD_CTX_init(&mdctx);
626 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
627 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
628 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
631 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
632 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
633 !EVP_DigestUpdate(&mdctx, auth, 16) ||
634 !EVP_DigestUpdate(&mdctx, salt, 2) ||
635 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
636 pthread_mutex_unlock(&lock);
641 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
644 for (i = 0; i < 16; i++)
647 for (offset = 16; offset < len; offset += 16) {
649 printf("text + offset - 16 c(%d): ", offset / 16);
650 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
652 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
653 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
654 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
655 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
657 pthread_mutex_unlock(&lock);
661 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
664 for (i = 0; i < 16; i++)
665 text[offset + i] ^= hash[i];
669 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
672 pthread_mutex_unlock(&lock);
676 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
677 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
678 static unsigned char first = 1;
679 static EVP_MD_CTX mdctx;
680 unsigned char hash[EVP_MAX_MD_SIZE];
685 pthread_mutex_lock(&lock);
687 EVP_MD_CTX_init(&mdctx);
692 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
693 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
694 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
697 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
698 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
699 !EVP_DigestUpdate(&mdctx, auth, 16) ||
700 !EVP_DigestUpdate(&mdctx, salt, 2) ||
701 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
702 pthread_mutex_unlock(&lock);
707 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
710 for (i = 0; i < 16; i++)
711 plain[i] = text[i] ^ hash[i];
713 for (offset = 16; offset < len; offset += 16) {
715 printf("text + offset - 16 c(%d): ", offset / 16);
716 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
718 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
719 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
720 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
721 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
723 pthread_mutex_unlock(&lock);
727 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
730 for (i = 0; i < 16; i++)
731 plain[offset + i] = text[offset + i] ^ hash[i];
734 memcpy(text, plain, len);
736 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
739 pthread_mutex_unlock(&lock);
743 struct realm *newrealmref(struct realm *r) {
749 /* returns with lock on realm */
750 struct realm *id2realm(struct list *realmlist, char *id) {
751 struct list_node *entry;
752 struct realm *realm, *subrealm;
754 /* need to do locking for subrealms and check subrealm timers */
755 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
756 realm = (struct realm *)entry->data;
757 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
758 pthread_mutex_lock(&realm->mutex);
759 if (realm->subrealms) {
760 subrealm = id2realm(realm->subrealms, id);
762 pthread_mutex_unlock(&realm->mutex);
766 return newrealmref(realm);
772 int hasdynamicserver(struct list *srvconfs) {
773 struct list_node *entry;
775 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
776 #if defined ENABLE_EXPERIMENTAL_DYNDISC
777 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand
778 || ((struct clsrvconf *)entry->data)->servers->in_use)
780 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
786 /* helper function, only used by removeserversubrealms() */
787 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
788 struct list_node *entry, *entry2;
791 for (entry = list_first(realmlist); entry;) {
792 realm = newrealmref((struct realm *)entry->data);
793 pthread_mutex_lock(&realm->mutex);
794 entry = list_next(entry);
796 if (realm->srvconfs) {
797 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
798 if (entry2->data == srv)
800 list_removedata(realm->srvconfs, srv);
802 if (realm->accsrvconfs) {
803 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
804 if (entry2->data == srv)
806 list_removedata(realm->accsrvconfs, srv);
809 /* remove subrealm if no dynamic servers left */
810 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
811 while (list_shift(realm->srvconfs))
813 list_destroy(realm->srvconfs);
814 realm->srvconfs = NULL;
815 while (list_shift(realm->accsrvconfs))
817 list_destroy(realm->accsrvconfs);
818 realm->accsrvconfs = NULL;
819 list_removedata(realmlist, realm);
821 pthread_mutex_unlock(&realm->mutex);
826 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
827 struct list_node *entry;
830 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
831 realm = (struct realm *)entry->data;
832 pthread_mutex_lock(&realm->mutex);
833 if (realm->subrealms) {
834 _internal_removeserversubrealms(realm->subrealms, srv);
835 if (!list_first(realm->subrealms)) {
836 list_destroy(realm->subrealms);
837 realm->subrealms = NULL;
840 pthread_mutex_unlock(&realm->mutex);
844 int attrvalidate(unsigned char *attrs, int length) {
846 if (ATTRLEN(attrs) < 2) {
847 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
850 length -= ATTRLEN(attrs);
852 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
855 attrs += ATTRLEN(attrs);
858 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
862 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
863 if (len < 16 || len > 128 || len % 16) {
864 debug(DBG_WARN, "pwdrecrypt: invalid password length");
868 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
869 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
873 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
875 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
876 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
882 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
885 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
886 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
889 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
890 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
896 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
897 char *oldsecret, char *newsecret) {
900 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
901 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
902 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
908 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
912 for (; attrs[0]; attrs += 2)
913 if (attrs[0] == vendor && attrs[1] == subattr)
918 /* returns 1 if entire element is to be removed, else 0 */
919 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
920 uint8_t alen, sublen;
924 if (!removevendorattrs)
927 memcpy(&vendor, attr->v, 4);
928 vendor = ntohl(vendor);
929 while (*removevendorattrs && *removevendorattrs != vendor)
930 removevendorattrs += 2;
931 if (!*removevendorattrs)
934 if (findvendorsubattr(removevendorattrs, vendor, 256))
935 return 1; /* remove entire vendor attribute */
937 sublen = attr->l - 4;
938 subattrs = attr->v + 4;
940 if (!attrvalidate(subattrs, sublen)) {
941 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
946 alen = ATTRLEN(subattrs);
948 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
949 memmove(subattrs, subattrs + alen, sublen);
957 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
958 struct list_node *n, *p;
962 n = list_first(msg->attrs);
964 attr = (struct tlv *)n->data;
965 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
966 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
967 list_removedata(msg->attrs, attr);
969 n = p ? list_next(p) : list_first(msg->attrs);
977 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
981 for (n = list_first(addattrs); n; n = list_next(n)) {
982 a = copytlv((struct tlv *)n->data);
985 if (!radmsg_add(msg, a)) {
993 int resizeattr(struct tlv *attr, uint8_t newlen) {
996 if (newlen != attr->l) {
997 newv = realloc(attr->v, newlen);
1006 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1007 size_t nmatch = 10, reslen = 0, start = 0;
1008 regmatch_t pmatch[10], *pfield;
1012 in = stringcopy((char *)attr->v, attr->l);
1016 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1021 out = modattr->replacement;
1023 for (i = start; out[i]; i++) {
1024 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1025 pfield = &pmatch[out[i + 1] - '0'];
1026 if (pfield->rm_so >= 0) {
1027 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1033 reslen += i - start;
1035 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1040 if (!resizeattr(attr, reslen)) {
1047 for (i = start; out[i]; i++) {
1048 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1049 pfield = &pmatch[out[i + 1] - '0'];
1050 if (pfield->rm_so >= 0) {
1051 memcpy(attr->v + reslen, out + start, i - start);
1052 reslen += i - start;
1053 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1054 reslen += pfield->rm_eo - pfield->rm_so;
1061 memcpy(attr->v + reslen, out + start, i - start);
1065 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1066 struct list_node *n, *m;
1068 for (n = list_first(msg->attrs); n; n = list_next(n))
1069 for (m = list_first(modattrs); m; m = list_next(m))
1070 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1071 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1076 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1077 int rv = 1; /* Success. */
1080 if (rewrite->removeattrs || rewrite->removevendorattrs)
1081 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1082 if (rewrite->modattrs)
1083 if (!dorewritemod(msg, rewrite->modattrs))
1085 if (rewrite->addattrs)
1086 if (!dorewriteadd(msg, rewrite->addattrs))
1092 int rewriteusername(struct request *rq, struct tlv *attr) {
1093 char *orig = (char *)tlv2str(attr);
1094 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1098 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1099 rq->origusername = (char *)orig;
1105 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1106 * all is well with the new tlv, i.e. if the function returns
1109 makevendortlv(uint32_t vendor, struct tlv *attr)
1111 struct tlv *newtlv = NULL;
1119 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1120 memcpy(v, &vendor, 4);
1121 tlv2buf(v + 4, attr);
1122 v[5] += 2; /* Vendor length increased for type and length fields. */
1123 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1132 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1134 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1137 vattr = makevendortlv(vendor, attr);
1142 if (!radmsg_add(msg, vattr)) {
1149 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1156 if (attrtype[1] == 256) { /* not vendor */
1157 attr = maketlv(attrtype[0], 4, ttl);
1158 if (attr && !radmsg_add(msg, attr))
1161 attr = maketlv(attrtype[1], 4, ttl);
1163 addvendorattr(msg, attrtype[0], attr);
1167 int decttl(uint8_t l, uint8_t *v) {
1174 while (i >= 0 && !v[i])
1178 for (i--; i >= 0 && !v[i]; i--);
1187 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1188 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1189 uint8_t alen, *subattrs;
1191 struct list_node *node;
1195 if (attrtype[1] == 256) { /* not vendor */
1196 attr = radmsg_gettype(msg, attrtype[0]);
1198 return decttl(attr->l, attr->v);
1200 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1201 attr = (struct tlv *)node->data;
1202 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1204 memcpy(&vendor, attr->v, 4);
1205 if (ntohl(vendor) != attrtype[0])
1207 sublen = attr->l - 4;
1208 subattrs = attr->v + 4;
1209 if (!attrvalidate(subattrs, sublen))
1211 while (sublen > 1) {
1212 if (ATTRTYPE(subattrs) == attrtype[1])
1213 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1214 alen = ATTRLEN(subattrs);
1222 const char *radmsgtype2string(uint8_t code) {
1223 static const char *rad_msg_names[] = {
1224 "", "Access-Request", "Access-Accept", "Access-Reject",
1225 "Accounting-Request", "Accounting-Response", "", "",
1226 "", "", "", "Access-Challenge",
1227 "Status-Server", "Status-Client"
1229 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1232 void char2hex(char *h, unsigned char c) {
1233 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1234 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1235 h[0] = hexdigits[c / 16];
1236 h[1] = hexdigits[c % 16];
1240 uint8_t *radattr2ascii(struct tlv *attr) {
1248 for (i = 0; i < attr->l; i++)
1249 if (attr->v[i] < 32 || attr->v[i] > 126)
1252 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1259 for (i = 0; i < attr->l; i++)
1260 if (attr->v[i] < 32 || attr->v[i] > 126) {
1262 char2hex((char *)d, attr->v[i]);
1270 void acclog(struct radmsg *msg, struct client *from) {
1274 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1276 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1279 username = radattr2ascii(attr);
1281 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1287 void respond(struct request *rq, uint8_t code, char *message) {
1291 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1293 debug(DBG_ERR, "respond: malloc failed");
1296 if (message && *message) {
1297 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1298 if (!attr || !radmsg_add(msg, attr)) {
1301 debug(DBG_ERR, "respond: malloc failed");
1306 radmsg_free(rq->msg);
1308 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1309 sendreply(newrqref(rq));
1312 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1313 struct list_node *entry;
1314 struct clsrvconf *server, *best = NULL, *first = NULL;
1316 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1317 server = (struct clsrvconf *)entry->data;
1318 if (!server->servers)
1320 if (server->servers->dynfailing)
1324 if (!server->servers->connectionok && !server->servers->dynstartup)
1326 if (!server->servers->lostrqs)
1332 if (server->servers->lostrqs < best->servers->lostrqs)
1335 return best ? best : first;
1338 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1339 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1340 struct clsrvconf *srvconf;
1341 struct realm *subrealm;
1342 struct server *server = NULL;
1343 char *id = (char *)tlv2str(username);
1347 /* returns with lock on realm */
1348 *realm = id2realm(realms, id);
1351 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1352 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1353 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1354 subrealm = adddynamicrealmserver(*realm, id);
1356 pthread_mutex_lock(&subrealm->mutex);
1357 pthread_mutex_unlock(&(*realm)->mutex);
1360 debug(DBG_DBG, "added realm: %s", (*realm)->name);
1361 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1362 debug(DBG_DBG, "found conf for new realm: %s", srvconf->name);
1366 debug(DBG_DBG, "found matching conf: %s", srvconf->name);
1367 server = srvconf->servers;
1376 struct request *newrequest() {
1379 rq = malloc(sizeof(struct request));
1381 debug(DBG_ERR, "newrequest: malloc failed");
1384 memset(rq, 0, sizeof(struct request));
1386 gettimeofday(&rq->created, NULL);
1390 int addclientrq(struct request *rq) {
1394 r = rq->from->rqs[rq->rqid];
1396 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1397 gettimeofday(&now, NULL);
1398 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1400 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1401 sendreply(newrqref(r));
1403 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1409 rq->from->rqs[rq->rqid] = newrqref(rq);
1413 void rmclientrq(struct request *rq, uint8_t id) {
1416 r = rq->from->rqs[id];
1419 rq->from->rqs[id] = NULL;
1423 /* returns 0 if validation/authentication fails, else 1 */
1424 int radsrv(struct request *rq) {
1425 struct radmsg *msg = NULL;
1427 uint8_t *userascii = NULL;
1428 struct realm *realm = NULL;
1429 struct server *to = NULL;
1430 struct client *from = rq->from;
1433 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1438 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1445 memcpy(rq->rqauth, msg->auth, 16);
1447 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1448 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1449 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1453 if (!addclientrq(rq))
1456 if (msg->code == RAD_Status_Server) {
1457 respond(rq, RAD_Access_Accept, NULL);
1461 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1463 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1466 ttlres = checkttl(msg, options.ttlattrtype);
1468 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1472 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1474 if (msg->code == RAD_Accounting_Request) {
1476 respond(rq, RAD_Accounting_Response, NULL);
1478 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1482 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1483 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1487 userascii = radattr2ascii(attr);
1490 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1492 /* will return with lock on the realm */
1493 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1495 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1500 if (realm->message && msg->code == RAD_Access_Request) {
1501 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1502 respond(rq, RAD_Access_Reject, realm->message);
1503 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1505 respond(rq, RAD_Accounting_Response, NULL);
1510 if ((to->conf->loopprevention == 1
1511 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1512 && !strcmp(from->conf->name, to->conf->name)) {
1513 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1514 from->conf->name, addr2string(from->addr), to->conf->name);
1518 if (msg->code == RAD_Accounting_Request)
1519 memset(msg->auth, 0, 16);
1520 else if (!RAND_bytes(msg->auth, 16)) {
1521 debug(DBG_WARN, "radsrv: failed to generate random auth");
1526 printfchars(NULL, "auth", "%02x ", auth, 16);
1529 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1531 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1532 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1536 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1538 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1539 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1543 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1546 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1547 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1552 pthread_mutex_unlock(&realm->mutex);
1557 rmclientrq(rq, msg->id);
1562 pthread_mutex_unlock(&realm->mutex);
1568 void replyh(struct server *server, unsigned char *buf) {
1569 struct client *from;
1570 struct rqout *rqout;
1572 unsigned char *subattrs;
1573 uint8_t *username, *stationid, *replymsg;
1574 struct radmsg *msg = NULL;
1576 struct list_node *node;
1578 server->connectionok = 1;
1579 server->lostrqs = 0;
1581 rqout = server->requests + buf[1];
1582 pthread_mutex_lock(rqout->lock);
1583 if (!rqout->tries) {
1586 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1590 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1594 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1597 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1598 && msg->code != RAD_Accounting_Response) {
1599 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1602 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1604 gettimeofday(&server->lastrcv, NULL);
1606 if (rqout->rq->msg->code == RAD_Status_Server) {
1607 freerqoutdata(rqout);
1608 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1612 gettimeofday(&server->lastreply, NULL);
1613 from = rqout->rq->from;
1615 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1616 debug(DBG_INFO, "replyh: rewritein failed");
1620 ttlres = checkttl(msg, options.ttlattrtype);
1622 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1627 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1628 attr = (struct tlv *)node->data;
1629 if (attr->t != RAD_Attr_Vendor_Specific)
1633 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1636 sublen = attr->l - 4;
1637 subattrs = attr->v + 4;
1638 if (!attrvalidate(subattrs, sublen) ||
1639 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1640 rqout->rq, server->conf->secret, from->conf->secret) ||
1641 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1642 rqout->rq, server->conf->secret, from->conf->secret))
1646 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1650 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1651 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1653 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1654 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1658 "%s for user %s stationid %s from %s (%s) to %s (%s)",
1659 radmsgtype2string(msg->code), username, stationid,
1660 server->conf->name, replymsg, from->conf->name,
1661 addr2string(from->addr));
1665 "%s for user %s stationid %s from %s to %s (%s)",
1666 radmsgtype2string(msg->code), username, stationid,
1667 server->conf->name, from->conf->name,
1668 addr2string(from->addr));
1672 debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1673 radmsgtype2string(msg->code), username,
1674 server->conf->name, replymsg, from->conf->name,
1675 addr2string(from->addr));
1678 debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1679 radmsgtype2string(msg->code), username,
1680 server->conf->name, from->conf->name,
1681 addr2string(from->addr));
1687 #if defined(WANT_FTICKS)
1688 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject)
1689 if (options.fticks_reporting && from->conf->fticks_viscountry != NULL)
1690 fticks_log(&options, from, msg, rqout);
1693 msg->id = (char)rqout->rq->rqid;
1694 memcpy(msg->auth, rqout->rq->rqauth, 16);
1697 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1700 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1701 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1702 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1705 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1708 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1709 debug(DBG_WARN, "replyh: rewriteout failed");
1713 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1714 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1716 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1717 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1719 radmsg_free(rqout->rq->msg);
1720 rqout->rq->msg = msg;
1721 sendreply(newrqref(rqout->rq));
1722 freerqoutdata(rqout);
1723 pthread_mutex_unlock(rqout->lock);
1728 pthread_mutex_unlock(rqout->lock);
1732 struct request *createstatsrvrq() {
1739 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1742 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1745 if (!radmsg_add(rq->msg, attr)) {
1756 /* code for removing state not finished */
1757 void *clientwr(void *arg) {
1758 struct server *server = (struct server *)arg;
1759 struct rqout *rqout = NULL;
1760 pthread_t clientrdth;
1761 int i, dynconffail = 0;
1764 struct timeval now, laststatsrv;
1765 struct timespec timeout;
1766 struct request *statsrvrq;
1767 struct clsrvconf *conf;
1769 conf = server->conf;
1773 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1775 server->dynstartup = 0;
1776 server->dynfailing = 1;
1777 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1778 pthread_mutex_unlock(&server->lock);
1780 debug(DBG_WARN, "%s: dynamicconfig(%s) failed, sleeping %ds",
1781 __func__, server->conf->name, ZZZ);
1785 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1786 pthread_mutex_unlock(&server->lock);
1788 /* FIXME: Is resolving not always done by compileserverconfig(),
1789 * either as part of static configuration setup or by
1790 * dynamicconfig() above? */
1791 if (!resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype)) {
1792 debug(DBG_WARN, "%s: resolve failed, sleeping %ds", __func__, ZZZ);
1797 memset(&timeout, 0, sizeof(struct timespec));
1799 if (conf->statusserver) {
1800 gettimeofday(&server->lastrcv, NULL);
1801 gettimeofday(&laststatsrv, NULL);
1804 if (conf->pdef->connecter) {
1805 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1806 if (server->dynamiclookuparg) {
1807 server->dynstartup = 0;
1808 server->dynfailing = 1;
1809 debug(DBG_WARN, "%s: connect failed, sleeping %ds",
1815 server->connectionok = 1;
1816 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1819 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1820 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1824 server->connectionok = 1;
1825 server->dynstartup = 0;
1828 pthread_mutex_lock(&server->newrq_mutex);
1829 if (!server->newrq) {
1830 gettimeofday(&now, NULL);
1831 /* random 0-7 seconds */
1832 RAND_bytes(&rnd, 1);
1834 if (conf->statusserver) {
1835 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1836 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1838 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1839 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1841 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1842 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1845 if (timeout.tv_sec > now.tv_sec)
1846 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1848 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1851 if (server->newrq) {
1852 debug(DBG_DBG, "clientwr: got new request");
1857 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1859 pthread_mutex_unlock(&server->newrq_mutex);
1861 for (i = 0; i < MAX_REQUESTS; i++) {
1862 if (server->clientrdgone) {
1863 pthread_join(clientrdth, NULL);
1867 for (; i < MAX_REQUESTS; i++) {
1868 rqout = server->requests + i;
1870 pthread_mutex_lock(rqout->lock);
1873 pthread_mutex_unlock(rqout->lock);
1877 if (i == MAX_REQUESTS)
1880 gettimeofday(&now, NULL);
1881 if (now.tv_sec < rqout->expiry.tv_sec) {
1882 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1883 timeout.tv_sec = rqout->expiry.tv_sec;
1884 pthread_mutex_unlock(rqout->lock);
1888 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1889 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1890 if (conf->statusserver) {
1891 if (*rqout->rq->buf == RAD_Status_Server) {
1892 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1893 if (server->lostrqs < 255)
1897 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1898 if (server->lostrqs < 255)
1901 freerqoutdata(rqout);
1902 pthread_mutex_unlock(rqout->lock);
1906 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1907 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1908 timeout.tv_sec = rqout->expiry.tv_sec;
1910 conf->pdef->clientradput(server, rqout->rq->buf);
1911 pthread_mutex_unlock(rqout->lock);
1913 if (conf->statusserver && server->connectionok) {
1914 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1915 gettimeofday(&now, NULL);
1916 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1918 statsrvrq = createstatsrvrq();
1920 statsrvrq->to = server;
1921 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1928 #if defined ENABLE_EXPERIMENTAL_DYNDISC
1931 conf->servers = NULL;
1932 if (server->dynamiclookuparg) {
1933 removeserversubrealms(realms, conf);
1937 freeclsrvconf(conf);
1939 freeserver(server, 1);
1940 ERR_remove_state(0);
1944 void createlistener(uint8_t type, char *arg) {
1946 struct addrinfo *res;
1947 int s = -1, on = 1, *sp = NULL;
1948 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1950 if (!hp || !resolvehostport(hp, AF_UNSPEC, protodefs[type]->socktype, 1))
1951 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1953 for (res = hp->addrinfo; res; res = res->ai_next) {
1954 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1956 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1959 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1961 disable_DF_bit(s, res);
1964 if (res->ai_family == AF_INET6)
1965 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1967 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1968 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1974 sp = malloc(sizeof(int));
1976 debugx(1, DBG_ERR, "malloc failed");
1978 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1979 debugerrnox(errno, DBG_ERR, "pthread_create failed");
1983 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1985 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1989 void createlisteners(uint8_t type) {
1993 args = protodefs[type]->getlistenerargs();
1995 for (i = 0; args[i]; i++)
1996 createlistener(type, args[i]);
1998 createlistener(type, NULL);
2006 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2007 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2008 for (i = 0; i < CRYPTO_num_locks(); i++) {
2009 ssl_lock_count[i] = 0;
2010 pthread_mutex_init(&ssl_locks[i], NULL);
2012 CRYPTO_set_id_callback(ssl_thread_id);
2013 CRYPTO_set_locking_callback(ssl_locking_callback);
2015 SSL_load_error_strings();
2018 while (!RAND_status()) {
2021 RAND_seed((unsigned char *)&t, sizeof(time_t));
2022 RAND_seed((unsigned char *)&pid, sizeof(pid));
2026 struct list *addsrvconfs(char *value, char **names) {
2027 struct list *conflist;
2029 struct list_node *entry;
2030 struct clsrvconf *conf = NULL;
2032 if (!names || !*names)
2035 conflist = list_create();
2037 debug(DBG_ERR, "malloc failed");
2041 for (n = 0; names[n]; n++) {
2042 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2043 conf = (struct clsrvconf *)entry->data;
2044 if (!strcasecmp(names[n], conf->name))
2048 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2049 list_destroy(conflist);
2052 if (!list_push(conflist, conf)) {
2053 debug(DBG_ERR, "malloc failed");
2054 list_destroy(conflist);
2057 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2062 void freerealm(struct realm *realm) {
2065 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2066 if (--realm->refcount)
2070 free(realm->message);
2071 regfree(&realm->regex);
2072 pthread_mutex_destroy(&realm->mutex);
2073 /* if refcount == 0, all subrealms gone */
2074 list_destroy(realm->subrealms);
2075 /* if refcount == 0, all srvconfs gone */
2076 list_destroy(realm->srvconfs);
2077 /* if refcount == 0, all accsrvconfs gone */
2078 list_destroy(realm->accsrvconfs);
2079 freerealm(realm->parent);
2083 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2085 struct realm *realm;
2086 char *s, *regex = NULL;
2088 if (*value == '/') {
2089 /* regexp, remove optional trailing / if present */
2090 if (value[strlen(value) - 1] == '/')
2091 value[strlen(value) - 1] = '\0';
2093 /* not a regexp, let us make it one */
2094 if (*value == '*' && !value[1])
2095 regex = stringcopy(".*", 0);
2097 for (n = 0, s = value; *s;)
2100 regex = malloc(strlen(value) + n + 3);
2103 for (n = 1, s = value; *s; s++) {
2113 debug(DBG_ERR, "malloc failed");
2117 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2120 realm = malloc(sizeof(struct realm));
2122 debug(DBG_ERR, "malloc failed");
2125 memset(realm, 0, sizeof(struct realm));
2127 if (pthread_mutex_init(&realm->mutex, NULL)) {
2128 debugerrno(errno, DBG_ERR, "mutex init failed");
2134 realm->name = stringcopy(value, 0);
2136 debug(DBG_ERR, "malloc failed");
2139 if (message && strlen(message) > 253) {
2140 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2143 realm->message = message;
2144 realm->accresp = accresp;
2146 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2147 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2151 if (servers && *servers) {
2152 realm->srvconfs = addsrvconfs(value, servers);
2153 if (!realm->srvconfs)
2157 if (accservers && *accservers) {
2158 realm->accsrvconfs = addsrvconfs(value, accservers);
2159 if (!realm->accsrvconfs)
2163 if (!list_push(realmlist, realm)) {
2164 debug(DBG_ERR, "malloc failed");
2165 pthread_mutex_destroy(&realm->mutex);
2169 debug(DBG_DBG, "addrealm: added realm %s", value);
2173 while (list_shift(realm->srvconfs));
2174 while (list_shift(realm->accsrvconfs));
2181 for (n = 0; servers[n]; n++)
2183 freegconfmstr(servers);
2187 for (n = 0; accservers[n]; n++)
2189 freegconfmstr(accservers);
2191 return newrealmref(realm);
2194 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2195 struct list_node *entry;
2196 struct clsrvconf *conf, *srvconf;
2197 struct list *subrealmservers = NULL;
2200 if (list_first(srvconfs)) {
2201 subrealmservers = list_create();
2202 if (!subrealmservers)
2206 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2207 conf = (struct clsrvconf *)entry->data;
2208 if (!conf->servers && conf->dynamiclookupcommand) {
2209 srvconf = malloc(sizeof(struct clsrvconf));
2211 debug(DBG_ERR, "malloc failed");
2214 debug(DBG_DBG, "%s: copying config %s", __func__, conf->name);
2216 /* Shallow copy -- sharing all the pointers. addserver()
2217 * will take care of servers (which btw has to be NUL) but
2218 * the rest of them are shared with the config found in
2219 * the srvconfs list. */
2220 if (addserver(srvconf)) {
2221 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2222 srvconf->servers->dynstartup = 1;
2223 debug(DBG_DBG, "%s: new client writer for %s",
2224 __func__, srvconf->servers->conf->name);
2225 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2226 pthread_mutex_lock(&srvconf->servers->lock);
2228 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2229 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2230 pthread_mutex_unlock(&srvconf->servers->lock);
2232 debugerrno(errno, DBG_ERR, "pthread_create failed");
2233 freeserver(srvconf->servers, 1);
2234 srvconf->servers = NULL;
2235 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2240 pthread_detach(clientth);
2242 #if defined ENABLE_EXPERIMENTAL_DYNDISC
2243 /* If clientwr() could not find a NAPTR we have to
2244 * wait for dynfailing=1 what is set in clientwr(). */
2245 pthread_mutex_lock(&srvconf->servers->lock);
2246 pthread_mutex_unlock(&srvconf->servers->lock);
2251 if (conf->servers) {
2252 if (list_push(subrealmservers, conf))
2255 debug(DBG_ERR, "malloc failed");
2258 return subrealmservers;
2261 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2262 struct realm *newrealm = NULL;
2263 char *realmname, *s;
2265 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2266 realmname = strrchr(id, '@');
2272 for (s = realmname; *s; s++)
2273 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2276 if (!realm->subrealms)
2277 realm->subrealms = list_create();
2278 if (!realm->subrealms)
2281 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2283 list_destroy(realm->subrealms);
2284 realm->subrealms = NULL;
2288 newrealm->parent = newrealmref(realm);
2289 /* add server and accserver to newrealm */
2290 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2291 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2295 int dynamicconfig(struct server *server) {
2296 int ok, fd[2], status;
2298 struct clsrvconf *conf = server->conf;
2299 struct gconffile *cf = NULL;
2301 /* for now we only learn hostname/address */
2302 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2305 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2310 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2314 } else if (pid == 0) {
2317 if (fd[1] != STDOUT_FILENO) {
2318 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2319 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2322 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2323 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2327 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2328 ok = getgenericconfig(&cf, NULL, "Server", CONF_CBK, confserver_cb,
2329 (void *) conf, NULL);
2332 if (waitpid(pid, &status, 0) < 0) {
2333 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2338 debug(DBG_INFO, "dynamicconfig: command exited with status %d",
2339 WEXITSTATUS(status));
2347 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2351 /* should accept both names and numeric values, only numeric right now */
2352 uint8_t attrname2val(char *attrname) {
2355 val = atoi(attrname);
2356 return val > 0 && val < 256 ? val : 0;
2359 /* ATTRNAME is on the form vendor[:type].
2360 If only vendor is found, TYPE is set to 256 and 1 is returned.
2361 If type is >= 256, 1 is returned.
2362 Otherwise, 0 is returned.
2364 /* should accept both names and numeric values, only numeric right now */
2365 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2368 *vendor = atoi(attrname);
2369 s = strchr(attrname, ':');
2370 if (!s) { /* Only vendor was found. */
2374 *type = atoi(s + 1);
2378 /** Extract attributes from string NAMEVAL, create a struct tlv and
2379 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2380 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2381 * NULL if fields are missing or if conversion fails.
2383 * FIXME: Should accept both names and numeric values, only numeric
2385 struct tlv *extractattr(char *nameval, char vendor_flag) {
2387 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2391 s = strchr(nameval, ':');
2394 name = atoi(nameval);
2397 s2 = strchr(s + 1, ':');
2404 len = strlen(s + 1);
2408 if (name < 1 || name > 255)
2410 a = malloc(sizeof(struct tlv));
2414 a->v = (uint8_t *)stringcopy(s + 1, 0);
2423 a = makevendortlv(vendor, a);
2428 /* should accept both names and numeric values, only numeric right now */
2429 struct modattr *extractmodattr(char *nameval) {
2434 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2438 s = strchr(nameval, ':');
2439 name = atoi(nameval);
2440 if (!s || name < 1 || name > 255 || s[1] != '/')
2444 /* regexp, remove optional trailing / if present */
2445 if (s[strlen(s) - 1] == '/')
2446 s[strlen(s) - 1] = '\0';
2454 m = malloc(sizeof(struct modattr));
2456 debug(DBG_ERR, "malloc failed");
2461 m->replacement = stringcopy(t, 0);
2462 if (!m->replacement) {
2464 debug(DBG_ERR, "malloc failed");
2468 m->regex = malloc(sizeof(regex_t));
2470 free(m->replacement);
2472 debug(DBG_ERR, "malloc failed");
2476 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2478 free(m->replacement);
2480 debug(DBG_ERR, "failed to compile regular expression %s", s);
2487 struct rewrite *getrewrite(char *alt1, char *alt2) {
2491 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2494 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2499 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2501 struct rewrite *rewrite = NULL;
2503 uint8_t *rma = NULL;
2504 uint32_t *p, *rmva = NULL;
2505 struct list *adda = NULL, *moda = NULL;
2510 for (n = 0; rmattrs[n]; n++);
2511 rma = calloc(n + 1, sizeof(uint8_t));
2513 debugx(1, DBG_ERR, "malloc failed");
2515 for (i = 0; i < n; i++)
2516 if (!(rma[i] = attrname2val(rmattrs[i])))
2517 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2518 freegconfmstr(rmattrs);
2523 for (n = 0; rmvattrs[n]; n++);
2524 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2526 debugx(1, DBG_ERR, "malloc failed");
2528 for (p = rmva, i = 0; i < n; i++, p += 2)
2529 if (!vattrname2val(rmvattrs[i], p, p + 1))
2530 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2531 freegconfmstr(rmvattrs);
2536 adda = list_create();
2538 debugx(1, DBG_ERR, "malloc failed");
2539 for (i = 0; addattrs[i]; i++) {
2540 a = extractattr(addattrs[i], 0);
2542 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2543 if (!list_push(adda, a))
2544 debugx(1, DBG_ERR, "malloc failed");
2546 freegconfmstr(addattrs);
2551 adda = list_create();
2553 debugx(1, DBG_ERR, "malloc failed");
2554 for (i = 0; addvattrs[i]; i++) {
2555 a = extractattr(addvattrs[i], 1);
2557 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2558 if (!list_push(adda, a))
2559 debugx(1, DBG_ERR, "malloc failed");
2561 freegconfmstr(addvattrs);
2565 moda = list_create();
2567 debugx(1, DBG_ERR, "malloc failed");
2568 for (i = 0; modattrs[i]; i++) {
2569 m = extractmodattr(modattrs[i]);
2571 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2572 if (!list_push(moda, m))
2573 debugx(1, DBG_ERR, "malloc failed");
2575 freegconfmstr(modattrs);
2578 if (rma || rmva || adda || moda) {
2579 rewrite = malloc(sizeof(struct rewrite));
2581 debugx(1, DBG_ERR, "malloc failed");
2582 rewrite->removeattrs = rma;
2583 rewrite->removevendorattrs = rmva;
2584 rewrite->addattrs = adda;
2585 rewrite->modattrs = moda;
2588 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2589 debugx(1, DBG_ERR, "malloc failed");
2590 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2593 int setttlattr(struct options *opts, char *defaultattr) {
2594 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2596 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2597 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2599 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2603 void freeclsrvconf(struct clsrvconf *conf) {
2606 debug(DBG_DBG, "%s: freeing %p (%s)", __func__, conf, conf->name);
2609 freegconfmstr(conf->hostsrc);
2610 free(conf->portsrc);
2613 free(conf->matchcertattr);
2614 if (conf->certcnregex)
2615 regfree(conf->certcnregex);
2616 if (conf->certuriregex)
2617 regfree(conf->certuriregex);
2618 free(conf->confrewritein);
2619 free(conf->confrewriteout);
2620 if (conf->rewriteusername) {
2621 if (conf->rewriteusername->regex)
2622 regfree(conf->rewriteusername->regex);
2623 free(conf->rewriteusername->replacement);
2624 free(conf->rewriteusername);
2626 free(conf->dynamiclookupcommand);
2627 free(conf->rewritein);
2628 free(conf->rewriteout);
2629 if (conf->hostports)
2630 freehostports(conf->hostports);
2632 pthread_mutex_destroy(conf->lock);
2635 /* not touching ssl_ctx, clients and servers */
2639 int mergeconfstring(char **dst, char **src) {
2648 t = stringcopy(*dst, 0);
2650 debug(DBG_ERR, "malloc failed");
2658 char **mstringcopy(char **in) {
2665 for (n = 0; in[n]; n++);
2666 out = malloc((n + 1) * sizeof(char *));
2669 for (n = 0; in[n]; n++) {
2670 out[n] = stringcopy(in[n], 0);
2680 int mergeconfmstring(char ***dst, char ***src) {
2689 t = mstringcopy(*dst);
2691 debug(DBG_ERR, "malloc failed");
2699 /* assumes dst is a shallow copy */
2700 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2701 if (!mergeconfstring(&dst->name, &src->name) ||
2702 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2703 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2704 !mergeconfstring(&dst->secret, &src->secret) ||
2705 !mergeconfstring(&dst->tls, &src->tls) ||
2706 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2707 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2708 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2709 !mergeconfstring(&dst->confrewriteusername, &src->confrewriteusername) ||
2710 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand) ||
2711 !mergeconfstring(&dst->fticks_viscountry, &src->fticks_viscountry) ||
2712 !mergeconfstring(&dst->fticks_visinst, &src->fticks_visinst))
2715 dst->pdef = src->pdef;
2716 dst->statusserver = src->statusserver;
2717 dst->certnamecheck = src->certnamecheck;
2718 if (src->retryinterval != 255)
2719 dst->retryinterval = src->retryinterval;
2720 if (src->retrycount != 255)
2721 dst->retrycount = src->retrycount;
2725 /** Set *AF according to IPV4ONLY and IPV6ONLY:
2726 - If both are set, the function fails.
2727 - If exactly one is set, *AF is set accordingly.
2728 - If none is set, *AF is not affected.
2729 Return 0 on success and !0 on failure.
2730 In the case of an error, *AF is not affected. */
2731 int config_hostaf(const char *desc, int ipv4only, int ipv6only, int *af) {
2733 if (ipv4only && ipv6only) {
2734 debug(DBG_ERR, "error in block %s, at most one of IPv4Only and "
2735 "IPv6Only can be enabled", desc);
2745 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2746 struct clsrvconf *conf;
2747 char *conftype = NULL, *rewriteinalias = NULL;
2748 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2749 uint8_t ipv4only = 0, ipv6only = 0;
2751 debug(DBG_DBG, "confclient_cb called for %s", block);
2753 conf = malloc(sizeof(struct clsrvconf));
2755 debugx(1, DBG_ERR, "malloc failed");
2756 memset(conf, 0, sizeof(struct clsrvconf));
2757 conf->certnamecheck = 1;
2759 if (!getgenericconfig(
2761 "type", CONF_STR, &conftype,
2762 "host", CONF_MSTR, &conf->hostsrc,
2763 "IPv4Only", CONF_BLN, &ipv4only,
2764 "IPv6Only", CONF_BLN, &ipv6only,
2765 "secret", CONF_STR, &conf->secret,
2766 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2767 "tls", CONF_STR, &conf->tls,
2768 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2769 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2771 "DuplicateInterval", CONF_LINT, &dupinterval,
2772 "addTTL", CONF_LINT, &addttl,
2773 "rewrite", CONF_STR, &rewriteinalias,
2774 "rewriteIn", CONF_STR, &conf->confrewritein,
2775 "rewriteOut", CONF_STR, &conf->confrewriteout,
2776 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2777 #if defined(WANT_FTICKS)
2778 "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2779 "fticksVISINST", CONF_STR, &conf->fticks_visinst,
2783 debugx(1, DBG_ERR, "configuration error");
2785 conf->name = stringcopy(val, 0);
2786 if (conf->name && !conf->hostsrc) {
2787 conf->hostsrc = malloc(2 * sizeof(char *));
2788 if (conf->hostsrc) {
2789 conf->hostsrc[0] = stringcopy(val, 0);
2790 conf->hostsrc[1] = NULL;
2793 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2794 debugx(1, DBG_ERR, "malloc failed");
2797 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2798 conf->type = protoname2int(conftype);
2799 if (conf->type == 255)
2800 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2802 conf->pdef = protodefs[conf->type];
2804 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2805 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2806 conf->tlsconf = conf->tls
2807 ? tlsgettls(conf->tls, NULL)
2808 : tlsgettls("defaultClient", "default");
2810 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2811 if (conf->matchcertattr && !addmatchcertattr(conf))
2812 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2816 conf->hostaf = AF_UNSPEC;
2817 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
2818 debugx(1, DBG_ERR, "config error: ^");
2819 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
2820 debugx(1, DBG_ERR, "error in block %s: ^", block);
2822 if (dupinterval != LONG_MIN) {
2823 if (dupinterval < 0 || dupinterval > 255)
2824 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2825 conf->dupinterval = (uint8_t)dupinterval;
2827 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2829 if (addttl != LONG_MIN) {
2830 if (addttl < 1 || addttl > 255)
2831 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2832 conf->addttl = (uint8_t)addttl;
2835 if (!conf->confrewritein)
2836 conf->confrewritein = rewriteinalias;
2838 free(rewriteinalias);
2839 conf->rewritein = conf->confrewritein
2840 ? getrewrite(conf->confrewritein, NULL)
2841 : getrewrite("defaultClient", "default");
2842 if (conf->confrewriteout)
2843 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2845 if (conf->confrewriteusername) {
2846 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2847 if (!conf->rewriteusername)
2848 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2851 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2852 !resolvehostports(conf->hostports, conf->hostaf, conf->pdef->socktype))
2853 debugx(1, DBG_ERR, "%s: resolve failed, exiting", __func__);
2855 if (!conf->secret) {
2856 if (!conf->pdef->secretdefault)
2857 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2858 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2860 debugx(1, DBG_ERR, "malloc failed");
2863 conf->lock = malloc(sizeof(pthread_mutex_t));
2865 debugx(1, DBG_ERR, "malloc failed");
2867 pthread_mutex_init(conf->lock, NULL);
2868 if (!list_push(clconfs, conf))
2869 debugx(1, DBG_ERR, "malloc failed");
2873 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2874 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2875 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2876 conf->tlsconf = conf->tls
2877 ? tlsgettls(conf->tls, NULL)
2878 : tlsgettls("defaultServer", "default");
2879 if (!conf->tlsconf) {
2880 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2883 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2884 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2890 if (!conf->portsrc) {
2891 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2892 if (!conf->portsrc) {
2893 debug(DBG_ERR, "malloc failed");
2898 if (conf->retryinterval == 255)
2899 conf->retryinterval = conf->pdef->retryintervaldefault;
2900 if (conf->retrycount == 255)
2901 conf->retrycount = conf->pdef->retrycountdefault;
2903 conf->rewritein = conf->confrewritein
2904 ? getrewrite(conf->confrewritein, NULL)
2905 : getrewrite("defaultServer", "default");
2906 if (conf->confrewriteout)
2907 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2909 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2910 debug(DBG_ERR, "error in block %s, failed to parse %s", block, *conf->hostsrc);
2914 if (!conf->dynamiclookupcommand &&
2915 !resolvehostports(conf->hostports, conf->hostaf,
2916 conf->pdef->socktype)) {
2917 debug(DBG_ERR, "%s: resolve failed", __func__);
2923 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2924 struct clsrvconf *conf, *resconf;
2925 char *conftype = NULL, *rewriteinalias = NULL;
2926 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2927 uint8_t ipv4only = 0, ipv6only = 0;
2929 debug(DBG_DBG, "confserver_cb called for %s", block);
2931 conf = malloc(sizeof(struct clsrvconf));
2933 debug(DBG_ERR, "malloc failed");
2936 memset(conf, 0, sizeof(struct clsrvconf));
2937 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2938 resconf = (struct clsrvconf *)arg;
2940 conf->statusserver = resconf->statusserver;
2941 conf->certnamecheck = resconf->certnamecheck;
2943 conf->certnamecheck = 1;
2945 if (!getgenericconfig(cf, block,
2946 "type", CONF_STR, &conftype,
2947 "host", CONF_MSTR, &conf->hostsrc,
2948 "IPv4Only", CONF_BLN, &ipv4only,
2949 "IPv6Only", CONF_BLN, &ipv6only,
2950 "port", CONF_STR, &conf->portsrc,
2951 "secret", CONF_STR, &conf->secret,
2952 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2953 "tls", CONF_STR, &conf->tls,
2954 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2955 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2957 "addTTL", CONF_LINT, &addttl,
2958 "rewrite", CONF_STR, &rewriteinalias,
2959 "rewriteIn", CONF_STR, &conf->confrewritein,
2960 "rewriteOut", CONF_STR, &conf->confrewriteout,
2961 "StatusServer", CONF_BLN, &conf->statusserver,
2962 "RetryInterval", CONF_LINT, &retryinterval,
2963 "RetryCount", CONF_LINT, &retrycount,
2964 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2965 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2968 debug(DBG_ERR, "configuration error");
2972 conf->name = stringcopy(val, 0);
2973 if (conf->name && !conf->hostsrc) {
2974 conf->hostsrc = malloc(2 * sizeof(char *));
2975 if (conf->hostsrc) {
2976 conf->hostsrc[0] = stringcopy(val, 0);
2977 conf->hostsrc[1] = NULL;
2980 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2981 debug(DBG_ERR, "malloc failed");
2986 debug(DBG_ERR, "error in block %s, option type missing", block);
2989 conf->type = protoname2int(conftype);
2990 if (conf->type == 255) {
2991 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2997 conf->hostaf = AF_UNSPEC;
2998 if (config_hostaf("top level", options.ipv4only, options.ipv6only, &conf->hostaf))
2999 debugx(1, DBG_ERR, "config error: ^");
3000 if (config_hostaf(block, ipv4only, ipv6only, &conf->hostaf))
3003 conf->pdef = protodefs[conf->type];
3005 if (!conf->confrewritein)
3006 conf->confrewritein = rewriteinalias;
3008 free(rewriteinalias);
3009 rewriteinalias = NULL;
3011 if (retryinterval != LONG_MIN) {
3012 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3013 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3016 conf->retryinterval = (uint8_t)retryinterval;
3018 conf->retryinterval = 255;
3020 if (retrycount != LONG_MIN) {
3021 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3022 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3025 conf->retrycount = (uint8_t)retrycount;
3027 conf->retrycount = 255;
3029 if (addttl != LONG_MIN) {
3030 if (addttl < 1 || addttl > 255) {
3031 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3034 conf->addttl = (uint8_t)addttl;
3038 if (!mergesrvconf(resconf, conf))
3042 if (conf->dynamiclookupcommand) {
3043 free(conf->dynamiclookupcommand);
3044 conf->dynamiclookupcommand = NULL;
3048 if (resconf || !conf->dynamiclookupcommand) {
3049 if (!compileserverconfig(conf, block))
3050 return 0; /* Don't goto errexit and free resconf -- it's
3051 * not ours to free. */
3054 if (!conf->secret) {
3055 if (!conf->pdef->secretdefault) {
3056 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3059 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3060 if (!conf->secret) {
3061 debug(DBG_ERR, "malloc failed");
3069 if (!list_push(srvconfs, conf)) {
3070 debug(DBG_ERR, "malloc failed");
3077 free(rewriteinalias);
3078 freeclsrvconf(conf);
3082 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3083 char **servers = NULL, **accservers = NULL, *msg = NULL;
3084 uint8_t accresp = 0;
3086 debug(DBG_DBG, "confrealm_cb called for %s", block);
3088 if (!getgenericconfig(cf, block,
3089 "server", CONF_MSTR, &servers,
3090 "accountingServer", CONF_MSTR, &accservers,
3091 "ReplyMessage", CONF_STR, &msg,
3092 "AccountingResponse", CONF_BLN, &accresp,
3095 debugx(1, DBG_ERR, "configuration error");
3097 addrealm(realms, val, servers, accservers, msg, accresp);
3101 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3102 char **rmattrs = NULL, **rmvattrs = NULL;
3103 char **addattrs = NULL, **addvattrs = NULL;
3104 char **modattrs = NULL;
3106 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3108 if (!getgenericconfig(cf, block,
3109 "removeAttribute", CONF_MSTR, &rmattrs,
3110 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3111 "addAttribute", CONF_MSTR, &addattrs,
3112 "addVendorAttribute", CONF_MSTR, &addvattrs,
3113 "modifyAttribute", CONF_MSTR, &modattrs,
3116 debugx(1, DBG_ERR, "configuration error");
3117 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
3121 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3122 struct commonprotoopts *protoopts;
3124 protoopts = malloc(sizeof(struct commonprotoopts));
3127 memset(protoopts, 0, sizeof(struct commonprotoopts));
3128 protoopts->listenargs = listenargs;
3129 protoopts->sourcearg = sourcearg;
3130 protodefs[type]->setprotoopts(protoopts);
3134 void getmainconfig(const char *configfile) {
3135 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3136 struct gconffile *cfs;
3137 char **listenargs[RAD_PROTOCOUNT];
3138 char *sourcearg[RAD_PROTOCOUNT];
3139 #if defined(WANT_FTICKS)
3140 uint8_t *fticks_reporting_str = NULL;
3141 uint8_t *fticks_mac_str = NULL;
3142 uint8_t *fticks_key_str = NULL;
3146 cfs = openconfigfile(configfile);
3147 memset(&options, 0, sizeof(options));
3148 memset(&listenargs, 0, sizeof(listenargs));
3149 memset(&sourcearg, 0, sizeof(sourcearg));
3151 clconfs = list_create();
3153 debugx(1, DBG_ERR, "malloc failed");
3155 srvconfs = list_create();
3157 debugx(1, DBG_ERR, "malloc failed");
3159 realms = list_create();
3161 debugx(1, DBG_ERR, "malloc failed");
3163 rewriteconfs = hash_create();
3165 debugx(1, DBG_ERR, "malloc failed");
3167 if (!getgenericconfig(
3170 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3171 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3174 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3175 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3178 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3179 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3182 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3183 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3185 "PidFile", CONF_STR, &options.pidfile,
3186 "TTLAttribute", CONF_STR, &options.ttlattr,
3187 "addTTL", CONF_LINT, &addttl,
3188 "LogLevel", CONF_LINT, &loglevel,
3189 "LogDestination", CONF_STR, &options.logdestination,
3190 "LoopPrevention", CONF_BLN, &options.loopprevention,
3191 "Client", CONF_CBK, confclient_cb, NULL,
3192 "Server", CONF_CBK, confserver_cb, NULL,
3193 "Realm", CONF_CBK, confrealm_cb, NULL,
3194 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3195 "TLS", CONF_CBK, conftls_cb, NULL,
3197 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3198 #if defined(WANT_FTICKS)
3199 "FTicksReporting", CONF_STR, &fticks_reporting_str,
3200 "FTicksMAC", CONF_STR, &fticks_mac_str,
3201 "FTicksKey", CONF_STR, &fticks_key_str,
3202 "FTicksSyslogFacility", CONF_STR, &options.ftickssyslogfacility,
3204 "IPv4Only", CONF_BLN, &options.ipv4only,
3205 "IPv6Only", CONF_BLN, &options.ipv6only,
3208 debugx(1, DBG_ERR, "configuration error");
3210 if (loglevel != LONG_MIN) {
3211 if (loglevel < 1 || loglevel > 5)
3212 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3213 options.loglevel = (uint8_t)loglevel;
3215 if (addttl != LONG_MIN) {
3216 if (addttl < 1 || addttl > 255)
3217 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3218 options.addttl = (uint8_t)addttl;
3220 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3221 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3223 #if defined(WANT_FTICKS)
3224 fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3228 for (i = 0; i < RAD_PROTOCOUNT; i++)
3229 if (listenargs[i] || sourcearg[i])
3230 setprotoopts(i, listenargs[i], sourcearg[i]);
3233 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3236 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3239 *configfile = optarg;
3242 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3243 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3244 *loglevel = *optarg - '0';
3256 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3257 debug(DBG_ERR, "This binary was built with support for the following transports:");
3259 debug(DBG_ERR, " UDP");
3262 debug(DBG_ERR, " TCP");
3265 debug(DBG_ERR, " TLS");
3268 debug(DBG_ERR, " DTLS");
3275 if (!(argc - optind))
3279 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3283 int daemon(int a, int b) {
3291 for (i = 0; i < 3; i++) {
3293 open("/dev/null", O_RDWR);
3299 void *sighandler(void *arg) {
3304 sigemptyset(&sigset);
3305 sigaddset(&sigset, SIGHUP);
3306 sigaddset(&sigset, SIGPIPE);
3307 sigwait(&sigset, &sig);
3310 /* completely ignoring this */
3313 debug(DBG_INFO, "sighandler: got SIGHUP");
3317 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3320 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3325 int createpidfile(const char *pidfile) {
3327 FILE *f = fopen(pidfile, "w");
3329 r = fprintf(f, "%ld\n", (long) getpid());
3330 return f && !fclose(f) && r >= 0;
3333 int radsecproxy_main(int argc, char **argv) {
3336 struct list_node *entry;
3337 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3338 char *configfile = NULL, *pidfile = NULL;
3339 struct clsrvconf *srvconf;
3342 debug_init("radsecproxy");
3343 debug_set_level(DEBUG_LEVEL);
3345 for (i = 0; i < RAD_PROTOCOUNT; i++)
3346 protodefs[i] = protoinits[i](i);
3348 /* needed even if no TLS/DTLS transport */
3351 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3353 debug_set_level(loglevel);
3354 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3356 options.loglevel = loglevel;
3357 else if (options.loglevel)
3358 debug_set_level(options.loglevel);
3360 debug_set_destination(options.logdestination
3361 ? options.logdestination
3362 : "x-syslog:///", LOG_TYPE_DEBUG);
3363 #if defined(WANT_FTICKS)
3364 if (options.ftickssyslogfacility) {
3365 debug_set_destination(options.ftickssyslogfacility,
3367 free(options.ftickssyslogfacility);
3371 free(options.logdestination);
3373 if (!list_first(clconfs))
3374 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3375 if (!list_first(realms))
3376 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3379 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3381 if (!foreground && (daemon(0, 0) < 0))
3382 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3384 debug_timestamp_on();
3385 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3387 pidfile = options.pidfile;
3388 if (pidfile && !createpidfile(pidfile))
3389 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3391 sigemptyset(&sigset);
3392 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3393 sigaddset(&sigset, SIGHUP);
3394 sigaddset(&sigset, SIGPIPE);
3395 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3396 pthread_create(&sigth, NULL, sighandler, NULL);
3398 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3399 srvconf = (struct clsrvconf *)entry->data;
3400 if (srvconf->dynamiclookupcommand)
3402 if (!addserver(srvconf))
3403 debugx(1, DBG_ERR, "failed to add server");
3404 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3405 (void *)(srvconf->servers)))
3406 debugx(1, DBG_ERR, "pthread_create failed");
3409 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3412 if (protodefs[i]->initextra)
3413 protodefs[i]->initextra();
3414 if (find_clconf_type(i, NULL))
3418 /* just hang around doing nothing, anything to do here? */
3423 /* Local Variables: */
3424 /* c-file-style: "stroustrup" */