2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* Code contributions from:
11 * Arne Schwabe <schwabe at uni-paderborn.de>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 * May segfault when dtls connections go down? More testing needed
39 * Remove expired stuff from clients request list?
40 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
41 * Useful for TCP accounting? Now we require separate server config for alt port
45 #include <sys/socket.h>
46 #include <netinet/in.h>
55 #include <sys/types.h>
56 #include <sys/select.h>
59 #include <arpa/inet.h>
63 #include <openssl/ssl.h>
64 #include <openssl/rand.h>
65 #include <openssl/err.h>
66 #include <openssl/md5.h>
67 #include <openssl/hmac.h>
68 #include <openssl/x509v3.h>
74 #include "radsecproxy.h"
79 #include "tlscommon.h"
81 static struct options options;
82 static struct list *clconfs, *srvconfs;
83 static struct list *realms;
84 static struct hash *rewriteconfs;
86 static pthread_mutex_t *ssl_locks = NULL;
87 static long *ssl_lock_count;
90 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
92 /* minimum required declarations to avoid reordering code */
93 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
94 int dynamicconfig(struct server *server);
95 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
96 void freerealm(struct realm *realm);
97 void freeclsrvconf(struct clsrvconf *conf);
98 void freerq(struct request *rq);
99 void freerqoutdata(struct rqout *rqout);
100 void rmclientrq(struct request *rq, uint8_t id);
102 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
104 uint8_t protoname2int(const char *name) {
107 for (i = 0; i < RAD_PROTOCOUNT; i++)
108 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
113 /* callbacks for making OpenSSL thread safe */
114 unsigned long ssl_thread_id() {
115 return (unsigned long)pthread_self();
118 void ssl_locking_callback(int mode, int type, const char *file, int line) {
119 if (mode & CRYPTO_LOCK) {
120 pthread_mutex_lock(&ssl_locks[type]);
121 ssl_lock_count[type]++;
123 pthread_mutex_unlock(&ssl_locks[type]);
126 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
127 struct addrinfo hints, *addrinfo, *res;
131 slash = conf->host ? strchr(conf->host, '/') : NULL;
135 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
139 if (*s < '0' || *s > '9') {
140 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
143 plen = atoi(slash + 1);
144 if (plen < 0 || plen > 128) {
145 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
150 memset(&hints, 0, sizeof(hints));
151 hints.ai_socktype = conf->pdef->socktype;
152 hints.ai_family = AF_UNSPEC;
153 hints.ai_flags = ai_flags;
154 if (!conf->host && !conf->port) {
155 /* getaddrinfo() doesn't like host and port to be NULL */
156 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
157 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
160 for (res = addrinfo; res; res = res->ai_next)
161 port_set(res->ai_addr, 0);
164 hints.ai_flags |= AI_NUMERICHOST;
165 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
166 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
171 switch (addrinfo->ai_family) {
174 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
175 freeaddrinfo(addrinfo);
182 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
183 freeaddrinfo(addrinfo);
186 conf->prefixlen = (uint8_t)plen;
188 conf->prefixlen = 255;
191 freeaddrinfo(conf->addrinfo);
192 conf->addrinfo = addrinfo;
196 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
201 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
205 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
207 debugx(1, DBG_ERR, "no ] matching initial [");
211 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
214 debugx(1, DBG_ERR, "missing host/address");
216 conf->host = stringcopy(field, p - field);
219 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
220 debugx(1, DBG_ERR, "unexpected character after ]");
223 /* port number or service name is specified */;
225 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
227 debugx(1, DBG_ERR, "syntax error, : but no following port");
228 conf->port = stringcopy(field, p - field);
230 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
234 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
235 struct clsrvconf *conf;
237 conf = malloc(sizeof(struct clsrvconf));
239 debugx(1, DBG_ERR, "malloc failed");
240 memset(conf, 0, sizeof(struct clsrvconf));
242 conf->pdef = protodefs[conf->type];
244 parsehostport(lconf, conf, default_port);
245 if (!strcmp(conf->host, "*")) {
250 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
251 if (!resolvepeer(conf, AI_PASSIVE))
252 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
256 void freeclsrvres(struct clsrvconf *res) {
260 freeaddrinfo(res->addrinfo);
264 struct addrinfo *resolve_hostport_addrinfo(uint8_t type, char *hostport) {
266 struct clsrvconf *res;
268 res = resolve_hostport(type, hostport, NULL);
270 res->addrinfo = NULL;
275 /* returns 1 if the len first bits are equal, else 0 */
276 int prefixmatch(void *a1, void *a2, uint8_t len) {
277 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
278 uint8_t r, l = len / 8;
279 if (l && memcmp(a1, a2, l))
284 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
287 /* returns next config with matching address, or NULL */
288 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
289 struct sockaddr_in6 *sa6 = NULL;
290 struct in_addr *a4 = NULL;
291 struct addrinfo *res;
292 struct list_node *entry;
293 struct clsrvconf *conf;
295 if (addr->sa_family == AF_INET6) {
296 sa6 = (struct sockaddr_in6 *)addr;
297 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
298 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
302 a4 = &((struct sockaddr_in *)addr)->sin_addr;
304 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
305 conf = (struct clsrvconf *)entry->data;
306 if (conf->type == type) {
307 if (conf->prefixlen == 255) {
308 for (res = conf->addrinfo; res; res = res->ai_next)
309 if ((a4 && res->ai_family == AF_INET &&
310 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
311 (sa6 && res->ai_family == AF_INET6 &&
312 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
318 res = conf->addrinfo;
320 ((a4 && res->ai_family == AF_INET &&
321 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
322 (sa6 && res->ai_family == AF_INET6 &&
323 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
334 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
335 return find_conf(type, addr, clconfs, cur);
338 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
339 return find_conf(type, addr, srvconfs, cur);
342 /* returns next config of given type, or NULL */
343 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
344 struct list_node *entry;
345 struct clsrvconf *conf;
347 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
348 conf = (struct clsrvconf *)entry->data;
349 if (conf->type == type) {
358 struct queue *newqueue() {
361 q = malloc(sizeof(struct queue));
363 debugx(1, DBG_ERR, "malloc failed");
364 q->entries = list_create();
366 debugx(1, DBG_ERR, "malloc failed");
367 pthread_mutex_init(&q->mutex, NULL);
368 pthread_cond_init(&q->cond, NULL);
372 void removequeue(struct queue *q) {
373 struct list_node *entry;
377 pthread_mutex_lock(&q->mutex);
378 for (entry = list_first(q->entries); entry; entry = list_next(entry))
379 freerq((struct request *)entry);
380 list_destroy(q->entries);
381 pthread_cond_destroy(&q->cond);
382 pthread_mutex_unlock(&q->mutex);
383 pthread_mutex_destroy(&q->mutex);
387 void freebios(struct queue *q) {
390 pthread_mutex_lock(&q->mutex);
391 while ((bio = (BIO *)list_shift(q->entries)))
393 pthread_mutex_unlock(&q->mutex);
397 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
398 struct client *new = malloc(sizeof(struct client));
401 debug(DBG_ERR, "malloc failed");
406 pthread_mutex_lock(conf->lock);
407 if (!conf->clients) {
408 conf->clients = list_create();
409 if (!conf->clients) {
411 pthread_mutex_unlock(conf->lock);
412 debug(DBG_ERR, "malloc failed");
417 memset(new, 0, sizeof(struct client));
419 if (conf->pdef->addclient)
420 conf->pdef->addclient(new);
422 new->replyq = newqueue();
423 list_push(conf->clients, new);
425 pthread_mutex_unlock(conf->lock);
429 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
430 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
433 pthread_mutex_lock(&lock);
435 pthread_mutex_unlock(&lock);
438 void removeclientrqs(struct client *client) {
443 removeclientrqs_sendrq_freeserver_lock(1);
444 for (i = 0; i < MAX_REQUESTS; i++) {
449 rqout = rq->to->requests + rq->newid;
450 pthread_mutex_lock(rqout->lock);
451 if (rqout->rq == rq) /* still pointing to our request */
452 freerqoutdata(rqout);
453 pthread_mutex_unlock(rqout->lock);
457 removeclientrqs_sendrq_freeserver_lock(0);
460 void removelockedclient(struct client *client) {
461 struct clsrvconf *conf;
465 removeclientrqs(client);
466 removequeue(client->replyq);
467 list_removedata(conf->clients, client);
473 void removeclient(struct client *client) {
474 struct clsrvconf *conf;
480 pthread_mutex_lock(conf->lock);
481 removelockedclient(client);
482 pthread_mutex_unlock(conf->lock);
485 void freeserver(struct server *server, uint8_t destroymutex) {
486 struct rqout *rqout, *end;
491 removeclientrqs_sendrq_freeserver_lock(1);
492 if (server->requests) {
493 rqout = server->requests;
494 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
496 rqout->rq->to = NULL;
497 freerqoutdata(rqout);
498 pthread_mutex_destroy(rqout->lock);
501 free(server->requests);
504 freebios(server->rbios);
505 free(server->dynamiclookuparg);
507 SSL_free(server->ssl);
509 pthread_mutex_destroy(&server->lock);
510 pthread_cond_destroy(&server->newrq_cond);
511 pthread_mutex_destroy(&server->newrq_mutex);
513 removeclientrqs_sendrq_freeserver_lock(0);
517 int addserver(struct clsrvconf *conf) {
522 debug(DBG_ERR, "addserver: currently works with just one server per conf");
525 conf->servers = malloc(sizeof(struct server));
526 if (!conf->servers) {
527 debug(DBG_ERR, "malloc failed");
530 memset(conf->servers, 0, sizeof(struct server));
531 conf->servers->conf = conf;
536 if (type == RAD_DTLS)
537 conf->servers->rbios = newqueue();
539 conf->pdef->setsrcres();
541 conf->servers->sock = -1;
542 if (conf->pdef->addserverextra)
543 conf->pdef->addserverextra(conf);
545 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
546 if (!conf->servers->requests) {
547 debug(DBG_ERR, "malloc failed");
550 for (i = 0; i < MAX_REQUESTS; i++) {
551 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
552 if (!conf->servers->requests[i].lock) {
553 debug(DBG_ERR, "malloc failed");
556 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
557 debug(DBG_ERR, "mutex init failed");
558 free(conf->servers->requests[i].lock);
559 conf->servers->requests[i].lock = NULL;
563 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
564 debug(DBG_ERR, "mutex init failed");
567 conf->servers->newrq = 0;
568 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
569 debug(DBG_ERR, "mutex init failed");
570 pthread_mutex_destroy(&conf->servers->lock);
573 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
574 debug(DBG_ERR, "mutex init failed");
575 pthread_mutex_destroy(&conf->servers->newrq_mutex);
576 pthread_mutex_destroy(&conf->servers->lock);
583 freeserver(conf->servers, 0);
584 conf->servers = NULL;
588 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
589 int loc, i, l, n, r = 0;
592 STACK_OF(GENERAL_NAME) *alt;
595 debug(DBG_DBG, "subjectaltnameaddr");
597 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
601 ex = X509_get_ext(cert, loc);
602 alt = X509V3_EXT_d2i(ex);
606 n = sk_GENERAL_NAME_num(alt);
607 for (i = 0; i < n; i++) {
608 gn = sk_GENERAL_NAME_value(alt, i);
609 if (gn->type != GEN_IPADD)
612 v = (char *)ASN1_STRING_data(gn->d.ia5);
613 l = ASN1_STRING_length(gn->d.ia5);
614 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
615 && !memcmp(v, &addr, l)) {
620 GENERAL_NAMES_free(alt);
624 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
631 nm = X509_get_subject_name(cert);
634 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
637 e = X509_NAME_get_entry(nm, loc);
638 t = X509_NAME_ENTRY_get_data(e);
639 v = (char *) ASN1_STRING_data(t);
640 l = ASN1_STRING_length(t);
644 if (l == strlen(exact) && !strncasecmp(exact, v, l))
647 s = stringcopy((char *)v, l);
649 debug(DBG_ERR, "malloc failed");
652 if (regexec(regex, s, 0, NULL, 0)) {
663 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
664 int loc, i, l, n, r = 0;
667 STACK_OF(GENERAL_NAME) *alt;
670 debug(DBG_DBG, "subjectaltnameregexp");
672 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
676 ex = X509_get_ext(cert, loc);
677 alt = X509V3_EXT_d2i(ex);
681 n = sk_GENERAL_NAME_num(alt);
682 for (i = 0; i < n; i++) {
683 gn = sk_GENERAL_NAME_value(alt, i);
684 if (gn->type != type)
687 v = (char *)ASN1_STRING_data(gn->d.ia5);
688 l = ASN1_STRING_length(gn->d.ia5);
692 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
695 if (memcmp(v, exact, l))
698 s = stringcopy((char *)v, l);
700 debug(DBG_ERR, "malloc failed");
703 if (regexec(regex, s, 0, NULL, 0)) {
712 GENERAL_NAMES_free(alt);
716 X509 *verifytlscert(SSL *ssl) {
720 if (SSL_get_verify_result(ssl) != X509_V_OK) {
721 debug(DBG_ERR, "verifytlscert: basic validation failed");
722 while ((error = ERR_get_error()))
723 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
727 cert = SSL_get_peer_certificate(ssl);
729 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
733 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
735 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
736 struct in6_addr addr;
738 if (conf->certnamecheck && conf->prefixlen == 255) {
739 if (inet_pton(AF_INET, conf->host, &addr))
741 else if (inet_pton(AF_INET6, conf->host, &addr))
744 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
747 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
750 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
752 if (!cnregexp(cert, conf->host, NULL)) {
753 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
756 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
759 if (conf->certcnregex) {
760 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
761 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
764 debug(DBG_DBG, "verifyconfcert: CN matching regex");
766 if (conf->certuriregex) {
767 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
768 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
771 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
776 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
778 if (ATTRTYPE(attrs) == type)
780 length -= ATTRLEN(attrs);
781 attrs += ATTRLEN(attrs);
786 struct request *newrqref(struct request *rq) {
792 void freerq(struct request *rq) {
795 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
798 if (rq->origusername)
799 free(rq->origusername);
805 radmsg_free(rq->msg);
809 void freerqoutdata(struct rqout *rqout) {
813 if (rqout->rq->buf) {
814 free(rqout->rq->buf);
815 rqout->rq->buf = NULL;
821 memset(&rqout->expiry, 0, sizeof(struct timeval));
824 void sendrq(struct request *rq) {
828 removeclientrqs_sendrq_freeserver_lock(1);
833 start = to->conf->statusserver ? 1 : 0;
834 pthread_mutex_lock(&to->newrq_mutex);
835 if (start && rq->msg->code == RAD_Status_Server) {
836 pthread_mutex_lock(to->requests[0].lock);
837 if (to->requests[0].rq) {
838 pthread_mutex_unlock(to->requests[0].lock);
839 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
846 /* might simplify if only try nextid, might be ok */
847 for (i = to->nextid; i < MAX_REQUESTS; i++) {
848 if (!to->requests[i].rq) {
849 pthread_mutex_lock(to->requests[i].lock);
850 if (!to->requests[i].rq)
852 pthread_mutex_unlock(to->requests[i].lock);
855 if (i == MAX_REQUESTS) {
856 for (i = start; i < to->nextid; i++) {
857 if (!to->requests[i].rq) {
858 pthread_mutex_lock(to->requests[i].lock);
859 if (!to->requests[i].rq)
861 pthread_mutex_unlock(to->requests[i].lock);
864 if (i == to->nextid) {
865 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
870 rq->newid = (uint8_t)i;
871 rq->msg->id = (uint8_t)i;
872 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
874 pthread_mutex_unlock(to->requests[i].lock);
875 debug(DBG_ERR, "sendrq: radmsg2buf failed");
879 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
880 to->requests[i].rq = rq;
881 pthread_mutex_unlock(to->requests[i].lock);
882 if (i >= start) /* i is not reserved for statusserver */
887 debug(DBG_DBG, "sendrq: signalling client writer");
888 pthread_cond_signal(&to->newrq_cond);
891 pthread_mutex_unlock(&to->newrq_mutex);
892 removeclientrqs_sendrq_freeserver_lock(0);
897 rmclientrq(rq, rq->msg->id);
899 pthread_mutex_unlock(&to->newrq_mutex);
900 removeclientrqs_sendrq_freeserver_lock(0);
903 void sendreply(struct request *rq) {
905 struct client *to = rq->from;
908 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
909 radmsg_free(rq->msg);
913 debug(DBG_ERR, "sendreply: radmsg2buf failed");
917 pthread_mutex_lock(&to->replyq->mutex);
918 first = list_first(to->replyq->entries) == NULL;
920 if (!list_push(to->replyq->entries, rq)) {
921 pthread_mutex_unlock(&to->replyq->mutex);
923 debug(DBG_ERR, "sendreply: malloc failed");
928 debug(DBG_DBG, "signalling server writer");
929 pthread_cond_signal(&to->replyq->cond);
931 pthread_mutex_unlock(&to->replyq->mutex);
934 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
935 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
936 static unsigned char first = 1;
937 static EVP_MD_CTX mdctx;
938 unsigned char hash[EVP_MAX_MD_SIZE], *input;
940 uint8_t i, offset = 0, out[128];
942 pthread_mutex_lock(&lock);
944 EVP_MD_CTX_init(&mdctx);
950 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
951 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
952 !EVP_DigestUpdate(&mdctx, input, 16) ||
953 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
955 pthread_mutex_unlock(&lock);
958 for (i = 0; i < 16; i++)
959 out[offset + i] = hash[i] ^ in[offset + i];
960 input = out + offset - 16;
965 memcpy(in, out, len);
966 pthread_mutex_unlock(&lock);
970 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
971 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
972 static unsigned char first = 1;
973 static EVP_MD_CTX mdctx;
974 unsigned char hash[EVP_MAX_MD_SIZE], *input;
976 uint8_t i, offset = 0, out[128];
978 pthread_mutex_lock(&lock);
980 EVP_MD_CTX_init(&mdctx);
986 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
987 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
988 !EVP_DigestUpdate(&mdctx, input, 16) ||
989 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
991 pthread_mutex_unlock(&lock);
994 for (i = 0; i < 16; i++)
995 out[offset + i] = hash[i] ^ in[offset + i];
1001 memcpy(in, out, len);
1002 pthread_mutex_unlock(&lock);
1006 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1007 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1008 static unsigned char first = 1;
1009 static EVP_MD_CTX mdctx;
1010 unsigned char hash[EVP_MAX_MD_SIZE];
1011 unsigned int md_len;
1014 pthread_mutex_lock(&lock);
1016 EVP_MD_CTX_init(&mdctx);
1021 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1022 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1023 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1026 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1027 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1028 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1029 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1030 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1031 pthread_mutex_unlock(&lock);
1036 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1039 for (i = 0; i < 16; i++)
1042 for (offset = 16; offset < len; offset += 16) {
1044 printf("text + offset - 16 c(%d): ", offset / 16);
1045 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1047 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1048 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1049 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1050 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1052 pthread_mutex_unlock(&lock);
1056 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1059 for (i = 0; i < 16; i++)
1060 text[offset + i] ^= hash[i];
1064 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1067 pthread_mutex_unlock(&lock);
1071 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1072 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1073 static unsigned char first = 1;
1074 static EVP_MD_CTX mdctx;
1075 unsigned char hash[EVP_MAX_MD_SIZE];
1076 unsigned int md_len;
1080 pthread_mutex_lock(&lock);
1082 EVP_MD_CTX_init(&mdctx);
1087 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1088 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1089 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1092 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1093 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1094 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1095 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1096 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1097 pthread_mutex_unlock(&lock);
1102 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1105 for (i = 0; i < 16; i++)
1106 plain[i] = text[i] ^ hash[i];
1108 for (offset = 16; offset < len; offset += 16) {
1110 printf("text + offset - 16 c(%d): ", offset / 16);
1111 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1113 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1114 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1115 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1116 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1118 pthread_mutex_unlock(&lock);
1122 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1125 for (i = 0; i < 16; i++)
1126 plain[offset + i] = text[offset + i] ^ hash[i];
1129 memcpy(text, plain, len);
1131 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1134 pthread_mutex_unlock(&lock);
1138 struct realm *newrealmref(struct realm *r) {
1144 /* returns with lock on realm */
1145 struct realm *id2realm(struct list *realmlist, char *id) {
1146 struct list_node *entry;
1147 struct realm *realm, *subrealm;
1149 /* need to do locking for subrealms and check subrealm timers */
1150 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1151 realm = (struct realm *)entry->data;
1152 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1153 pthread_mutex_lock(&realm->mutex);
1154 if (realm->subrealms) {
1155 subrealm = id2realm(realm->subrealms, id);
1157 pthread_mutex_unlock(&realm->mutex);
1161 return newrealmref(realm);
1167 /* helper function, only used by removeserversubrealms() */
1168 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1169 struct list_node *entry, *entry2;
1170 struct realm *realm;
1172 for (entry = list_first(realmlist); entry;) {
1173 realm = newrealmref((struct realm *)entry->data);
1174 pthread_mutex_lock(&realm->mutex);
1175 entry = list_next(entry);
1177 if (realm->srvconfs) {
1178 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1179 if (entry2->data == srv)
1181 list_removedata(realm->srvconfs, srv);
1182 if (!list_first(realm->srvconfs)) {
1183 list_destroy(realm->srvconfs);
1184 realm->srvconfs = NULL;
1187 if (realm->accsrvconfs) {
1188 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1189 if (entry2->data == srv)
1191 list_removedata(realm->accsrvconfs, srv);
1192 if (!list_first(realm->accsrvconfs)) {
1193 list_destroy(realm->accsrvconfs);
1194 realm->accsrvconfs = NULL;
1198 /* remove subrealm if no servers */
1199 if (!realm->srvconfs && !realm->accsrvconfs)
1200 list_removedata(realmlist, realm);
1202 pthread_mutex_unlock(&realm->mutex);
1207 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1208 struct list_node *entry;
1209 struct realm *realm;
1211 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1212 realm = (struct realm *)entry->data;
1213 pthread_mutex_lock(&realm->mutex);
1214 if (realm->subrealms) {
1215 _internal_removeserversubrealms(realm->subrealms, srv);
1216 if (!list_first(realm->subrealms)) {
1217 list_destroy(realm->subrealms);
1218 realm->subrealms = NULL;
1221 pthread_mutex_unlock(&realm->mutex);
1225 int attrvalidate(unsigned char *attrs, int length) {
1226 while (length > 1) {
1227 if (ATTRLEN(attrs) < 2) {
1228 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1231 length -= ATTRLEN(attrs);
1233 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1236 attrs += ATTRLEN(attrs);
1239 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1243 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1244 if (len < 16 || len > 128 || len % 16) {
1245 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1249 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1250 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1254 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1256 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1257 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1263 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1266 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1267 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1270 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1271 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1277 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1278 char *oldsecret, char *newsecret) {
1279 unsigned char *attr;
1281 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1282 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1283 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1289 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1293 for (; attrs[0]; attrs += 2)
1294 if (attrs[0] == vendor && attrs[1] == subattr)
1299 /* returns 1 if entire element is to be removed, else 0 */
1300 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1301 uint8_t alen, sublen;
1305 if (!removevendorattrs)
1308 memcpy(&vendor, attr->v, 4);
1309 vendor = ntohl(vendor);
1310 while (*removevendorattrs && *removevendorattrs != vendor)
1311 removevendorattrs += 2;
1312 if (!*removevendorattrs)
1315 if (findvendorsubattr(removevendorattrs, vendor, -1))
1316 return 1; /* remove entire vendor attribute */
1318 sublen = attr->l - 4;
1319 subattrs = attr->v + 4;
1321 if (!attrvalidate(subattrs, sublen)) {
1322 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1326 while (sublen > 1) {
1327 alen = ATTRLEN(subattrs);
1329 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1330 memmove(subattrs, subattrs + alen, sublen);
1338 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1339 struct list_node *n, *p;
1343 n = list_first(msg->attrs);
1345 attr = (struct tlv *)n->data;
1346 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1347 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1348 list_removedata(msg->attrs, attr);
1350 n = p ? list_next(p) : list_first(msg->attrs);
1357 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1358 struct list_node *n;
1361 for (n = list_first(addattrs); n; n = list_next(n)) {
1362 a = copytlv((struct tlv *)n->data);
1365 if (!radmsg_add(msg, a)) {
1373 int resizeattr(struct tlv *attr, uint8_t newlen) {
1376 if (newlen != attr->l) {
1377 newv = realloc(attr->v, newlen);
1386 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1387 size_t nmatch = 10, reslen = 0, start = 0;
1388 regmatch_t pmatch[10], *pfield;
1392 in = stringcopy((char *)attr->v, attr->l);
1396 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1401 out = modattr->replacement;
1403 for (i = start; out[i]; i++) {
1404 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1405 pfield = &pmatch[out[i + 1] - '0'];
1406 if (pfield->rm_so >= 0) {
1407 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1413 reslen += i - start;
1415 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1420 if (!resizeattr(attr, reslen)) {
1427 for (i = start; out[i]; i++) {
1428 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1429 pfield = &pmatch[out[i + 1] - '0'];
1430 if (pfield->rm_so >= 0) {
1431 memcpy(attr->v + reslen, out + start, i - start);
1432 reslen += i - start;
1433 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1434 reslen += pfield->rm_eo - pfield->rm_so;
1441 memcpy(attr->v + reslen, out + start, i - start);
1445 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1446 struct list_node *n, *m;
1448 for (n = list_first(msg->attrs); n; n = list_next(n))
1449 for (m = list_first(modattrs); m; m = list_next(m))
1450 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1451 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1456 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1459 if (rewrite->removeattrs || rewrite->removevendorattrs)
1460 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1461 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1463 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1468 int rewriteusername(struct request *rq, struct tlv *attr) {
1469 char *orig = (char *)tlv2str(attr);
1470 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1474 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1475 rq->origusername = (char *)orig;
1481 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1488 vendor = htonl(vendor);
1489 memcpy(v, &vendor, 4);
1490 tlv2buf(v + 4, attr);
1492 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1493 if (vattr && radmsg_add(msg, vattr))
1500 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1507 if (attrtype[1] == -1) { /* not vendor */
1508 attr = maketlv(attrtype[0], 4, ttl);
1509 if (attr && !radmsg_add(msg, attr))
1512 attr = maketlv(attrtype[1], 4, ttl);
1514 addvendorattr(msg, attrtype[0], attr);
1520 int decttl(uint8_t l, uint8_t *v) {
1527 while (i >= 0 && !v[i])
1531 for (i--; i >= 0 && !v[i]; i--);
1540 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1541 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1542 uint8_t alen, *subattrs;
1544 struct list_node *node;
1548 if (attrtype[1] == -1) { /* not vendor */
1549 attr = radmsg_gettype(msg, attrtype[0]);
1551 return decttl(attr->l, attr->v);
1553 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1554 attr = (struct tlv *)node->data;
1555 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1557 memcpy(&vendor, attr->v, 4);
1558 if (ntohl(vendor) != attrtype[0])
1560 sublen = attr->l - 4;
1561 subattrs = attr->v + 4;
1562 if (!attrvalidate(subattrs, sublen))
1564 while (sublen > 1) {
1565 if (ATTRTYPE(subattrs) == attrtype[1])
1566 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1567 alen = ATTRLEN(subattrs);
1575 const char *radmsgtype2string(uint8_t code) {
1576 static const char *rad_msg_names[] = {
1577 "", "Access-Request", "Access-Accept", "Access-Reject",
1578 "Accounting-Request", "Accounting-Response", "", "",
1579 "", "", "", "Access-Challenge",
1580 "Status-Server", "Status-Client"
1582 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1585 void char2hex(char *h, unsigned char c) {
1586 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1587 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1588 h[0] = hexdigits[c / 16];
1589 h[1] = hexdigits[c % 16];
1593 uint8_t *radattr2ascii(struct tlv *attr) {
1601 for (i = 0; i < attr->l; i++)
1602 if (attr->v[i] < 32 || attr->v[i] > 126)
1605 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1612 for (i = 0; i < attr->l; i++)
1613 if (attr->v[i] < 32 || attr->v[i] > 126) {
1615 char2hex((char *)d, attr->v[i]);
1623 void acclog(struct radmsg *msg, char *host) {
1627 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1629 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1632 username = radattr2ascii(attr);
1634 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1639 void respond(struct request *rq, uint8_t code, char *message) {
1643 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1645 debug(DBG_ERR, "respond: malloc failed");
1648 if (message && *message) {
1649 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1650 if (!attr || !radmsg_add(msg, attr)) {
1653 debug(DBG_ERR, "respond: malloc failed");
1658 radmsg_free(rq->msg);
1660 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1661 sendreply(newrqref(rq));
1664 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1665 struct list_node *entry;
1666 struct clsrvconf *server, *best = NULL, *first = NULL;
1668 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1669 server = (struct clsrvconf *)entry->data;
1670 if (!server->servers)
1674 if (!server->servers->connectionok)
1676 if (!server->servers->lostrqs)
1682 if (server->servers->lostrqs < best->servers->lostrqs)
1685 return best ? best : first;
1688 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1689 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1690 struct clsrvconf *srvconf;
1691 struct realm *subrealm;
1692 struct server *server = NULL;
1693 char *id = (char *)tlv2str(username);
1697 /* returns with lock on realm */
1698 *realm = id2realm(realms, id);
1701 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1702 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1705 server = srvconf->servers;
1706 if (!acc && !(*realm)->parent && !srvconf->servers) {
1707 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1709 pthread_mutex_lock(&subrealm->mutex);
1710 pthread_mutex_unlock(&(*realm)->mutex);
1713 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1722 struct request *newrequest() {
1725 rq = malloc(sizeof(struct request));
1727 debug(DBG_ERR, "newrequest: malloc failed");
1730 memset(rq, 0, sizeof(struct request));
1732 gettimeofday(&rq->created, NULL);
1736 int addclientrq(struct request *rq) {
1740 r = rq->from->rqs[rq->rqid];
1742 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1743 gettimeofday(&now, NULL);
1744 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1746 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1747 sendreply(newrqref(r));
1749 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1755 rq->from->rqs[rq->rqid] = newrqref(rq);
1759 void rmclientrq(struct request *rq, uint8_t id) {
1762 r = rq->from->rqs[id];
1765 rq->from->rqs[id] = NULL;
1769 /* returns 0 if validation/authentication fails, else 1 */
1770 int radsrv(struct request *rq) {
1771 struct radmsg *msg = NULL;
1773 uint8_t *userascii = NULL;
1774 struct realm *realm = NULL;
1775 struct server *to = NULL;
1776 struct client *from = rq->from;
1779 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1784 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1791 memcpy(rq->rqauth, msg->auth, 16);
1793 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1794 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1795 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1799 if (!addclientrq(rq))
1802 if (msg->code == RAD_Status_Server) {
1803 respond(rq, RAD_Access_Accept, NULL);
1807 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1809 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1812 ttlres = checkttl(msg, options.ttlattrtype);
1814 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1818 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1820 if (msg->code == RAD_Accounting_Request) {
1821 acclog(msg, from->conf->host);
1822 respond(rq, RAD_Accounting_Response, NULL);
1824 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1828 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1829 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1833 userascii = radattr2ascii(attr);
1836 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1838 /* will return with lock on the realm */
1839 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1841 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1846 if (realm->message && msg->code == RAD_Access_Request) {
1847 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1848 respond(rq, RAD_Access_Reject, realm->message);
1849 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1850 acclog(msg, from->conf->host);
1851 respond(rq, RAD_Accounting_Response, NULL);
1856 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1857 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1858 from->conf->name, addr2string(from->addr), to->conf->name);
1862 if (msg->code == RAD_Accounting_Request)
1863 memset(msg->auth, 0, 16);
1864 else if (!RAND_bytes(msg->auth, 16)) {
1865 debug(DBG_WARN, "radsrv: failed to generate random auth");
1870 printfchars(NULL, "auth", "%02x ", auth, 16);
1873 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1875 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1876 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1880 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1882 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1883 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1887 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1890 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1891 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1896 pthread_mutex_unlock(&realm->mutex);
1901 rmclientrq(rq, msg->id);
1906 pthread_mutex_unlock(&realm->mutex);
1912 void replyh(struct server *server, unsigned char *buf) {
1913 struct client *from;
1914 struct rqout *rqout;
1916 unsigned char *subattrs;
1917 uint8_t *username, *stationid, *replymsg;
1918 struct radmsg *msg = NULL;
1920 struct list_node *node;
1922 server->connectionok = 1;
1923 server->lostrqs = 0;
1925 rqout = server->requests + buf[1];
1926 pthread_mutex_lock(rqout->lock);
1927 if (!rqout->tries) {
1930 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1934 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1938 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1941 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1942 && msg->code != RAD_Accounting_Response) {
1943 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1946 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1948 gettimeofday(&server->lastrcv, NULL);
1950 if (rqout->rq->msg->code == RAD_Status_Server) {
1951 freerqoutdata(rqout);
1952 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1956 gettimeofday(&server->lastreply, NULL);
1957 from = rqout->rq->from;
1959 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1960 debug(DBG_WARN, "replyh: rewritein failed");
1964 ttlres = checkttl(msg, options.ttlattrtype);
1966 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
1971 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1972 attr = (struct tlv *)node->data;
1973 if (attr->t != RAD_Attr_Vendor_Specific)
1977 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1980 sublen = attr->l - 4;
1981 subattrs = attr->v + 4;
1982 if (!attrvalidate(subattrs, sublen) ||
1983 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1984 rqout->rq, server->conf->secret, from->conf->secret) ||
1985 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1986 rqout->rq, server->conf->secret, from->conf->secret))
1990 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1994 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1995 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1997 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1998 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2001 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2002 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2005 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2006 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2010 debug(DBG_INFO, "%s for user %s from %s (%s)",
2011 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2014 debug(DBG_INFO, "%s for user %s from %s",
2015 radmsgtype2string(msg->code), username, server->conf->host);
2021 msg->id = (char)rqout->rq->rqid;
2022 memcpy(msg->auth, rqout->rq->rqauth, 16);
2025 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2028 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2029 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2030 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2033 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2036 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2037 debug(DBG_WARN, "replyh: rewriteout failed");
2041 if (ttlres == -1 && (options.addttl || from->conf->addttl))
2042 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
2044 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2045 radmsg_free(rqout->rq->msg);
2046 rqout->rq->msg = msg;
2047 sendreply(newrqref(rqout->rq));
2048 freerqoutdata(rqout);
2049 pthread_mutex_unlock(rqout->lock);
2054 pthread_mutex_unlock(rqout->lock);
2058 struct request *createstatsrvrq() {
2065 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2068 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2071 if (!radmsg_add(rq->msg, attr)) {
2082 /* code for removing state not finished */
2083 void *clientwr(void *arg) {
2084 struct server *server = (struct server *)arg;
2085 struct rqout *rqout = NULL;
2086 pthread_t clientrdth;
2087 int i, dynconffail = 0;
2090 struct timeval now, laststatsrv;
2091 struct timespec timeout;
2092 struct request *statsrvrq;
2093 struct clsrvconf *conf;
2095 conf = server->conf;
2097 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2102 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2103 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2107 memset(&timeout, 0, sizeof(struct timespec));
2109 if (conf->statusserver) {
2110 gettimeofday(&server->lastrcv, NULL);
2111 gettimeofday(&laststatsrv, NULL);
2114 if (conf->pdef->connecter) {
2115 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2117 server->connectionok = 1;
2118 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2119 debug(DBG_ERR, "clientwr: pthread_create failed");
2123 server->connectionok = 1;
2126 pthread_mutex_lock(&server->newrq_mutex);
2127 if (!server->newrq) {
2128 gettimeofday(&now, NULL);
2129 /* random 0-7 seconds */
2130 RAND_bytes(&rnd, 1);
2132 if (conf->statusserver) {
2133 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2134 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2136 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2137 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2139 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2140 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2143 if (timeout.tv_sec > now.tv_sec)
2144 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2146 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2149 if (server->newrq) {
2150 debug(DBG_DBG, "clientwr: got new request");
2155 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2157 pthread_mutex_unlock(&server->newrq_mutex);
2159 for (i = 0; i < MAX_REQUESTS; i++) {
2160 if (server->clientrdgone) {
2161 pthread_join(clientrdth, NULL);
2165 for (; i < MAX_REQUESTS; i++) {
2166 rqout = server->requests + i;
2168 pthread_mutex_lock(rqout->lock);
2171 pthread_mutex_unlock(rqout->lock);
2175 if (i == MAX_REQUESTS)
2178 gettimeofday(&now, NULL);
2179 if (now.tv_sec < rqout->expiry.tv_sec) {
2180 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2181 timeout.tv_sec = rqout->expiry.tv_sec;
2182 pthread_mutex_unlock(rqout->lock);
2186 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2187 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2188 if (conf->statusserver) {
2189 if (*rqout->rq->buf == RAD_Status_Server) {
2190 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2191 if (server->lostrqs < 255)
2195 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2196 if (server->lostrqs < 255)
2199 freerqoutdata(rqout);
2200 pthread_mutex_unlock(rqout->lock);
2204 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2205 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2206 timeout.tv_sec = rqout->expiry.tv_sec;
2208 conf->pdef->clientradput(server, rqout->rq->buf);
2209 pthread_mutex_unlock(rqout->lock);
2211 if (conf->statusserver && server->connectionok) {
2212 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2213 gettimeofday(&now, NULL);
2214 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2216 statsrvrq = createstatsrvrq();
2218 statsrvrq->to = server;
2219 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2226 conf->servers = NULL;
2227 if (server->dynamiclookuparg) {
2228 removeserversubrealms(realms, conf);
2232 freeclsrvconf(conf);
2234 freeserver(server, 1);
2235 ERR_remove_state(0);
2239 void createlistener(uint8_t type, char *arg) {
2241 struct clsrvconf *listenres;
2242 struct addrinfo *res;
2243 int s = -1, on = 1, *sp = NULL;
2245 listenres = resolve_hostport(type, arg, protodefs[type]->portdefault);
2247 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2249 for (res = listenres->addrinfo; res; res = res->ai_next) {
2250 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2252 debug(DBG_WARN, "createlistener: socket failed");
2255 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2257 if (res->ai_family == AF_INET6)
2258 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2260 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2261 debug(DBG_WARN, "createlistener: bind failed");
2267 sp = malloc(sizeof(int));
2269 debugx(1, DBG_ERR, "malloc failed");
2271 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
2272 debugx(1, DBG_ERR, "pthread_create failed");
2276 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2278 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name,
2279 listenres->host ? listenres->host : "*", listenres->port);
2280 freeclsrvres(listenres);
2283 void createlisteners(uint8_t type) {
2287 args = protodefs[type]->getlistenerargs();
2289 for (i = 0; args[i]; i++)
2290 createlistener(type, args[i]);
2292 createlistener(type, NULL);
2300 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2301 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2302 for (i = 0; i < CRYPTO_num_locks(); i++) {
2303 ssl_lock_count[i] = 0;
2304 pthread_mutex_init(&ssl_locks[i], NULL);
2306 CRYPTO_set_id_callback(ssl_thread_id);
2307 CRYPTO_set_locking_callback(ssl_locking_callback);
2309 SSL_load_error_strings();
2312 while (!RAND_status()) {
2315 RAND_seed((unsigned char *)&t, sizeof(time_t));
2316 RAND_seed((unsigned char *)&pid, sizeof(pid));
2320 struct list *addsrvconfs(char *value, char **names) {
2321 struct list *conflist;
2323 struct list_node *entry;
2324 struct clsrvconf *conf = NULL;
2326 if (!names || !*names)
2329 conflist = list_create();
2331 debug(DBG_ERR, "malloc failed");
2335 for (n = 0; names[n]; n++) {
2336 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2337 conf = (struct clsrvconf *)entry->data;
2338 if (!strcasecmp(names[n], conf->name))
2342 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2343 list_destroy(conflist);
2346 if (!list_push(conflist, conf)) {
2347 debug(DBG_ERR, "malloc failed");
2348 list_destroy(conflist);
2351 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2356 void freerealm(struct realm *realm) {
2359 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2360 if (--realm->refcount)
2364 free(realm->message);
2365 regfree(&realm->regex);
2366 pthread_mutex_destroy(&realm->mutex);
2367 /* if refcount == 0, all subrealms gone */
2368 list_destroy(realm->subrealms);
2369 /* if refcount == 0, all srvconfs gone */
2370 list_destroy(realm->srvconfs);
2371 /* if refcount == 0, all accsrvconfs gone */
2372 list_destroy(realm->accsrvconfs);
2373 freerealm(realm->parent);
2377 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2379 struct realm *realm;
2380 char *s, *regex = NULL;
2382 if (*value == '/') {
2383 /* regexp, remove optional trailing / if present */
2384 if (value[strlen(value) - 1] == '/')
2385 value[strlen(value) - 1] = '\0';
2387 /* not a regexp, let us make it one */
2388 if (*value == '*' && !value[1])
2389 regex = stringcopy(".*", 0);
2391 for (n = 0, s = value; *s;)
2394 regex = malloc(strlen(value) + n + 3);
2397 for (n = 1, s = value; *s; s++) {
2407 debug(DBG_ERR, "malloc failed");
2411 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2414 realm = malloc(sizeof(struct realm));
2416 debug(DBG_ERR, "malloc failed");
2419 memset(realm, 0, sizeof(struct realm));
2421 if (pthread_mutex_init(&realm->mutex, NULL)) {
2422 debug(DBG_ERR, "mutex init failed");
2428 realm->name = stringcopy(value, 0);
2430 debug(DBG_ERR, "malloc failed");
2433 if (message && strlen(message) > 253) {
2434 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2437 realm->message = message;
2438 realm->accresp = accresp;
2440 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2441 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2445 if (servers && *servers) {
2446 realm->srvconfs = addsrvconfs(value, servers);
2447 if (!realm->srvconfs)
2451 if (accservers && *accservers) {
2452 realm->accsrvconfs = addsrvconfs(value, accservers);
2453 if (!realm->accsrvconfs)
2457 if (!list_push(realmlist, realm)) {
2458 debug(DBG_ERR, "malloc failed");
2459 pthread_mutex_destroy(&realm->mutex);
2463 debug(DBG_DBG, "addrealm: added realm %s", value);
2467 while (list_shift(realm->srvconfs));
2468 while (list_shift(realm->accsrvconfs));
2475 for (n = 0; servers[n]; n++)
2477 freegconfmstr(servers);
2481 for (n = 0; accservers[n]; n++)
2483 freegconfmstr(accservers);
2485 return newrealmref(realm);
2488 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2489 struct clsrvconf *srvconf;
2490 struct realm *newrealm = NULL;
2491 char *realmname, *s;
2494 if (!conf->dynamiclookupcommand)
2497 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2498 realmname = strrchr(id, '@');
2504 for (s = realmname; *s; s++)
2505 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2508 srvconf = malloc(sizeof(struct clsrvconf));
2510 debug(DBG_ERR, "malloc failed");
2514 if (!addserver(srvconf))
2517 if (!realm->subrealms)
2518 realm->subrealms = list_create();
2519 if (!realm->subrealms)
2521 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2524 newrealm->parent = newrealmref(realm);
2526 /* add server and accserver to newrealm */
2527 newrealm->srvconfs = list_create();
2528 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2529 debug(DBG_ERR, "malloc failed");
2532 newrealmref(newrealm);
2533 newrealm->accsrvconfs = list_create();
2534 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2535 debug(DBG_ERR, "malloc failed");
2536 list_shift(realm->srvconfs);
2537 freerealm(newrealm);
2540 newrealmref(newrealm);
2542 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2543 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2544 debug(DBG_ERR, "pthread_create failed");
2545 list_shift(realm->srvconfs);
2546 freerealm(newrealm);
2547 list_shift(realm->accsrvconfs);
2548 freerealm(newrealm);
2551 pthread_detach(clientth);
2556 list_removedata(realm->subrealms, newrealm);
2557 freerealm(newrealm);
2558 if (!list_first(realm->subrealms)) {
2559 list_destroy(realm->subrealms);
2560 realm->subrealms = NULL;
2563 freeserver(srvconf->servers, 1);
2565 debug(DBG_ERR, "failed to create dynamic server");
2569 int dynamicconfig(struct server *server) {
2570 int ok, fd[2], status;
2572 struct clsrvconf *conf = server->conf;
2573 struct gconffile *cf = NULL;
2575 /* for now we only learn hostname/address */
2576 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2579 debug(DBG_ERR, "dynamicconfig: pipe error");
2584 debug(DBG_ERR, "dynamicconfig: fork error");
2588 } else if (pid == 0) {
2591 if (fd[1] != STDOUT_FILENO) {
2592 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2593 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2596 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2597 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2601 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2602 ok = getgenericconfig(&cf, NULL,
2603 "Server", CONF_CBK, confserver_cb, (void *)conf,
2608 if (waitpid(pid, &status, 0) < 0) {
2609 debug(DBG_ERR, "dynamicconfig: wait error");
2614 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2622 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2626 int addmatchcertattr(struct clsrvconf *conf) {
2630 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2631 r = &conf->certcnregex;
2632 v = conf->matchcertattr + 4;
2633 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2634 r = &conf->certuriregex;
2635 v = conf->matchcertattr + 20;
2640 /* regexp, remove optional trailing / if present */
2641 if (v[strlen(v) - 1] == '/')
2642 v[strlen(v) - 1] = '\0';
2646 *r = malloc(sizeof(regex_t));
2648 debug(DBG_ERR, "malloc failed");
2651 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2654 debug(DBG_ERR, "failed to compile regular expression %s", v);
2660 /* should accept both names and numeric values, only numeric right now */
2661 uint8_t attrname2val(char *attrname) {
2664 val = atoi(attrname);
2665 return val > 0 && val < 256 ? val : 0;
2668 /* should accept both names and numeric values, only numeric right now */
2669 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2672 *vendor = atoi(attrname);
2673 s = strchr(attrname, ':');
2678 *type = atoi(s + 1);
2679 return *type >= 0 && *type < 256;
2682 /* should accept both names and numeric values, only numeric right now */
2683 struct tlv *extractattr(char *nameval) {
2688 s = strchr(nameval, ':');
2689 name = atoi(nameval);
2690 if (!s || name < 1 || name > 255)
2692 len = strlen(s + 1);
2695 a = malloc(sizeof(struct tlv));
2698 a->v = (uint8_t *)stringcopy(s + 1, 0);
2708 /* should accept both names and numeric values, only numeric right now */
2709 struct modattr *extractmodattr(char *nameval) {
2714 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2718 s = strchr(nameval, ':');
2719 name = atoi(nameval);
2720 if (!s || name < 1 || name > 255 || s[1] != '/')
2724 /* regexp, remove optional trailing / if present */
2725 if (s[strlen(s) - 1] == '/')
2726 s[strlen(s) - 1] = '\0';
2734 m = malloc(sizeof(struct modattr));
2736 debug(DBG_ERR, "malloc failed");
2741 m->replacement = stringcopy(t, 0);
2742 if (!m->replacement) {
2744 debug(DBG_ERR, "malloc failed");
2748 m->regex = malloc(sizeof(regex_t));
2750 free(m->replacement);
2752 debug(DBG_ERR, "malloc failed");
2756 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2758 free(m->replacement);
2760 debug(DBG_ERR, "failed to compile regular expression %s", s);
2767 struct rewrite *getrewrite(char *alt1, char *alt2) {
2770 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2772 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2777 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2778 struct rewrite *rewrite = NULL;
2780 uint8_t *rma = NULL;
2781 uint32_t *p, *rmva = NULL;
2782 struct list *adda = NULL, *moda = NULL;
2787 for (n = 0; rmattrs[n]; n++);
2788 rma = calloc(n + 1, sizeof(uint8_t));
2790 debugx(1, DBG_ERR, "malloc failed");
2792 for (i = 0; i < n; i++)
2793 if (!(rma[i] = attrname2val(rmattrs[i])))
2794 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2795 freegconfmstr(rmattrs);
2800 for (n = 0; rmvattrs[n]; n++);
2801 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2803 debugx(1, DBG_ERR, "malloc failed");
2805 for (p = rmva, i = 0; i < n; i++, p += 2)
2806 if (!vattrname2val(rmvattrs[i], p, p + 1))
2807 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2808 freegconfmstr(rmvattrs);
2813 adda = list_create();
2815 debugx(1, DBG_ERR, "malloc failed");
2816 for (i = 0; addattrs[i]; i++) {
2817 a = extractattr(addattrs[i]);
2819 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2820 if (!list_push(adda, a))
2821 debugx(1, DBG_ERR, "malloc failed");
2823 freegconfmstr(addattrs);
2827 moda = list_create();
2829 debugx(1, DBG_ERR, "malloc failed");
2830 for (i = 0; modattrs[i]; i++) {
2831 m = extractmodattr(modattrs[i]);
2833 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2834 if (!list_push(moda, m))
2835 debugx(1, DBG_ERR, "malloc failed");
2837 freegconfmstr(modattrs);
2840 if (rma || rmva || adda || moda) {
2841 rewrite = malloc(sizeof(struct rewrite));
2843 debugx(1, DBG_ERR, "malloc failed");
2844 rewrite->removeattrs = rma;
2845 rewrite->removevendorattrs = rmva;
2846 rewrite->addattrs = adda;
2847 rewrite->modattrs = moda;
2850 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2851 debugx(1, DBG_ERR, "malloc failed");
2852 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2855 int setttlattr(struct options *opts, char *defaultattr) {
2856 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2858 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2859 (opts->ttlattrtype[1] != -1 || opts->ttlattrtype[0] < 256))
2861 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2865 void freeclsrvconf(struct clsrvconf *conf) {
2871 free(conf->matchcertattr);
2872 if (conf->certcnregex)
2873 regfree(conf->certcnregex);
2874 if (conf->certuriregex)
2875 regfree(conf->certuriregex);
2876 free(conf->confrewritein);
2877 free(conf->confrewriteout);
2878 if (conf->rewriteusername) {
2879 if (conf->rewriteusername->regex)
2880 regfree(conf->rewriteusername->regex);
2881 free(conf->rewriteusername->replacement);
2882 free(conf->rewriteusername);
2884 free(conf->dynamiclookupcommand);
2885 free(conf->rewritein);
2886 free(conf->rewriteout);
2888 freeaddrinfo(conf->addrinfo);
2890 pthread_mutex_destroy(conf->lock);
2893 /* not touching ssl_ctx, clients and servers */
2897 int mergeconfstring(char **dst, char **src) {
2906 t = stringcopy(*dst, 0);
2908 debug(DBG_ERR, "malloc failed");
2916 /* assumes dst is a shallow copy */
2917 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2918 if (!mergeconfstring(&dst->name, &src->name) ||
2919 !mergeconfstring(&dst->host, &src->host) ||
2920 !mergeconfstring(&dst->port, &src->port) ||
2921 !mergeconfstring(&dst->secret, &src->secret) ||
2922 !mergeconfstring(&dst->tls, &src->tls) ||
2923 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2924 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2925 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2926 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2929 dst->pdef = src->pdef;
2930 dst->statusserver = src->statusserver;
2931 dst->certnamecheck = src->certnamecheck;
2932 if (src->retryinterval != 255)
2933 dst->retryinterval = src->retryinterval;
2934 if (src->retrycount != 255)
2935 dst->retrycount = src->retrycount;
2939 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2940 struct clsrvconf *conf;
2941 char *conftype = NULL, *rewriteinalias = NULL;
2942 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2944 debug(DBG_DBG, "confclient_cb called for %s", block);
2946 conf = malloc(sizeof(struct clsrvconf));
2948 debugx(1, DBG_ERR, "malloc failed");
2949 memset(conf, 0, sizeof(struct clsrvconf));
2950 conf->certnamecheck = 1;
2952 if (!getgenericconfig(cf, block,
2953 "type", CONF_STR, &conftype,
2954 "host", CONF_STR, &conf->host,
2955 "secret", CONF_STR, &conf->secret,
2956 "tls", CONF_STR, &conf->tls,
2957 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2958 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2959 "DuplicateInterval", CONF_LINT, &dupinterval,
2960 "addTTL", CONF_LINT, &addttl,
2961 "rewrite", CONF_STR, &rewriteinalias,
2962 "rewriteIn", CONF_STR, &conf->confrewritein,
2963 "rewriteOut", CONF_STR, &conf->confrewriteout,
2964 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2967 debugx(1, DBG_ERR, "configuration error");
2969 conf->name = stringcopy(val, 0);
2971 conf->host = stringcopy(val, 0);
2972 if (!conf->name || !conf->host)
2973 debugx(1, DBG_ERR, "malloc failed");
2976 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2977 conf->type = protoname2int(conftype);
2978 if (conf->type == 255)
2979 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2981 conf->pdef = protodefs[conf->type];
2983 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2984 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2985 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2987 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2988 if (conf->matchcertattr && !addmatchcertattr(conf))
2989 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2993 if (dupinterval != LONG_MIN) {
2994 if (dupinterval < 0 || dupinterval > 255)
2995 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2996 conf->dupinterval = (uint8_t)dupinterval;
2998 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3000 if (addttl != LONG_MIN) {
3001 if (addttl < 1 || addttl > 255)
3002 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3003 conf->addttl = (uint8_t)addttl;
3006 if (!conf->confrewritein)
3007 conf->confrewritein = rewriteinalias;
3009 free(rewriteinalias);
3010 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3011 if (conf->confrewriteout)
3012 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3014 if (conf->confrewriteusername) {
3015 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3016 if (!conf->rewriteusername)
3017 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3020 if (!resolvepeer(conf, 0))
3021 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3023 if (!conf->secret) {
3024 if (!conf->pdef->secretdefault)
3025 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3026 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3028 debugx(1, DBG_ERR, "malloc failed");
3031 conf->lock = malloc(sizeof(pthread_mutex_t));
3033 debugx(1, DBG_ERR, "malloc failed");
3035 pthread_mutex_init(conf->lock, NULL);
3036 if (!list_push(clconfs, conf))
3037 debugx(1, DBG_ERR, "malloc failed");
3041 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3042 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3043 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3044 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3045 if (!conf->tlsconf) {
3046 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3049 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3050 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3057 conf->port = stringcopy(conf->pdef->portdefault, 0);
3059 debug(DBG_ERR, "malloc failed");
3064 if (conf->retryinterval == 255)
3065 conf->retryinterval = conf->pdef->retryintervaldefault;
3066 if (conf->retrycount == 255)
3067 conf->retrycount = conf->pdef->retrycountdefault;
3069 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3070 if (conf->confrewriteout)
3071 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3073 if (!conf->secret) {
3074 if (!conf->pdef->secretdefault) {
3075 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3078 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3079 if (!conf->secret) {
3080 debug(DBG_ERR, "malloc failed");
3085 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3086 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3092 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3093 struct clsrvconf *conf, *resconf;
3094 char *conftype = NULL, *rewriteinalias = NULL;
3095 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
3097 debug(DBG_DBG, "confserver_cb called for %s", block);
3099 conf = malloc(sizeof(struct clsrvconf));
3101 debug(DBG_ERR, "malloc failed");
3104 memset(conf, 0, sizeof(struct clsrvconf));
3105 resconf = (struct clsrvconf *)arg;
3107 conf->statusserver = resconf->statusserver;
3108 conf->certnamecheck = resconf->certnamecheck;
3110 conf->certnamecheck = 1;
3112 if (!getgenericconfig(cf, block,
3113 "type", CONF_STR, &conftype,
3114 "host", CONF_STR, &conf->host,
3115 "port", CONF_STR, &conf->port,
3116 "secret", CONF_STR, &conf->secret,
3117 "tls", CONF_STR, &conf->tls,
3118 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3119 "addTTL", CONF_LINT, &addttl,
3120 "rewrite", CONF_STR, &rewriteinalias,
3121 "rewriteIn", CONF_STR, &conf->confrewritein,
3122 "rewriteOut", CONF_STR, &conf->confrewriteout,
3123 "StatusServer", CONF_BLN, &conf->statusserver,
3124 "RetryInterval", CONF_LINT, &retryinterval,
3125 "RetryCount", CONF_LINT, &retrycount,
3126 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3127 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3130 debug(DBG_ERR, "configuration error");
3134 conf->name = stringcopy(val, 0);
3136 debug(DBG_ERR, "malloc failed");
3140 conf->host = stringcopy(val, 0);
3142 debug(DBG_ERR, "malloc failed");
3148 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3149 conf->type = protoname2int(conftype);
3150 if (conf->type == 255) {
3151 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3157 conf->pdef = protodefs[conf->type];
3159 if (!conf->confrewritein)
3160 conf->confrewritein = rewriteinalias;
3162 free(rewriteinalias);
3163 rewriteinalias = NULL;
3165 if (retryinterval != LONG_MIN) {
3166 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3167 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3170 conf->retryinterval = (uint8_t)retryinterval;
3172 conf->retryinterval = 255;
3174 if (retrycount != LONG_MIN) {
3175 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3176 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3179 conf->retrycount = (uint8_t)retrycount;
3181 conf->retrycount = 255;
3183 if (addttl != LONG_MIN) {
3184 if (addttl < 1 || addttl > 255) {
3185 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3188 conf->addttl = (uint8_t)addttl;
3192 if (!mergesrvconf(resconf, conf))
3196 if (conf->dynamiclookupcommand) {
3197 free(conf->dynamiclookupcommand);
3198 conf->dynamiclookupcommand = NULL;
3202 if (resconf || !conf->dynamiclookupcommand) {
3203 if (!compileserverconfig(conf, block))
3210 if (!list_push(srvconfs, conf)) {
3211 debug(DBG_ERR, "malloc failed");
3218 free(rewriteinalias);
3219 freeclsrvconf(conf);
3223 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3224 char **servers = NULL, **accservers = NULL, *msg = NULL;
3225 uint8_t accresp = 0;
3227 debug(DBG_DBG, "confrealm_cb called for %s", block);
3229 if (!getgenericconfig(cf, block,
3230 "server", CONF_MSTR, &servers,
3231 "accountingServer", CONF_MSTR, &accservers,
3232 "ReplyMessage", CONF_STR, &msg,
3233 "AccountingResponse", CONF_BLN, &accresp,
3236 debugx(1, DBG_ERR, "configuration error");
3238 addrealm(realms, val, servers, accservers, msg, accresp);
3242 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3243 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3245 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3247 if (!getgenericconfig(cf, block,
3248 "removeAttribute", CONF_MSTR, &rmattrs,
3249 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3250 "addAttribute", CONF_MSTR, &addattrs,
3251 "modifyAttribute", CONF_MSTR, &modattrs,
3254 debugx(1, DBG_ERR, "configuration error");
3255 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3259 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3260 struct commonprotoopts *protoopts;
3262 protoopts = malloc(sizeof(struct commonprotoopts));
3265 memset(protoopts, 0, sizeof(struct commonprotoopts));
3266 protoopts->listenargs = listenargs;
3267 protoopts->sourcearg = sourcearg;
3268 protodefs[type]->setprotoopts(protoopts);
3272 void getmainconfig(const char *configfile) {
3273 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3274 struct gconffile *cfs;
3275 char **listenargs[RAD_PROTOCOUNT];
3276 char *sourcearg[RAD_PROTOCOUNT];
3279 cfs = openconfigfile(configfile);
3280 memset(&options, 0, sizeof(options));
3281 memset(&listenargs, 0, sizeof(listenargs));
3282 memset(&sourcearg, 0, sizeof(sourcearg));
3284 clconfs = list_create();
3286 debugx(1, DBG_ERR, "malloc failed");
3288 srvconfs = list_create();
3290 debugx(1, DBG_ERR, "malloc failed");
3292 realms = list_create();
3294 debugx(1, DBG_ERR, "malloc failed");
3296 rewriteconfs = hash_create();
3298 debugx(1, DBG_ERR, "malloc failed");
3300 if (!getgenericconfig(&cfs, NULL,
3302 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3303 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3306 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3307 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3310 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3311 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3314 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3315 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3317 "TTLAttribute", CONF_STR, &options.ttlattr,
3318 "addTTL", CONF_LINT, &addttl,
3319 "LogLevel", CONF_LINT, &loglevel,
3320 "LogDestination", CONF_STR, &options.logdestination,
3321 "LoopPrevention", CONF_BLN, &options.loopprevention,
3322 "Client", CONF_CBK, confclient_cb, NULL,
3323 "Server", CONF_CBK, confserver_cb, NULL,
3324 "Realm", CONF_CBK, confrealm_cb, NULL,
3325 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3326 "TLS", CONF_CBK, conftls_cb, NULL,
3328 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3331 debugx(1, DBG_ERR, "configuration error");
3333 if (loglevel != LONG_MIN) {
3334 if (loglevel < 1 || loglevel > 4)
3335 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3336 options.loglevel = (uint8_t)loglevel;
3338 if (addttl != LONG_MIN) {
3339 if (addttl < 1 || addttl > 255)
3340 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3341 options.addttl = (uint8_t)addttl;
3343 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3344 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3346 for (i = 0; i < RAD_PROTOCOUNT; i++)
3347 if (listenargs[i] || sourcearg[i])
3348 setprotoopts(i, listenargs[i], sourcearg[i]);
3351 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3354 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3357 *configfile = optarg;
3360 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3361 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3362 *loglevel = *optarg - '0';
3371 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3376 if (!(argc - optind))
3380 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3384 int daemon(int a, int b) {
3392 for (i = 0; i < 3; i++) {
3394 open("/dev/null", O_RDWR);
3400 void *sighandler(void *arg) {
3405 sigemptyset(&sigset);
3406 sigaddset(&sigset, SIGPIPE);
3407 sigwait(&sigset, &sig);
3408 /* only get SIGPIPE right now, so could simplify below code */
3411 /* completely ignoring this */
3414 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3417 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3422 int main(int argc, char **argv) {
3425 struct list_node *entry;
3426 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3427 char *configfile = NULL;
3428 struct clsrvconf *srvconf;
3431 debug_init("radsecproxy");
3432 debug_set_level(DEBUG_LEVEL);
3434 for (i = 0; i < RAD_PROTOCOUNT; i++)
3435 protodefs[i] = protoinits[i](i);
3437 /* needed even if no TLS/DTLS transport */
3440 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3442 debug_set_level(loglevel);
3443 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3445 options.loglevel = loglevel;
3446 else if (options.loglevel)
3447 debug_set_level(options.loglevel);
3449 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3450 free(options.logdestination);
3452 if (!list_first(clconfs))
3453 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3454 if (!list_first(realms))
3455 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3458 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3460 if (!foreground && (daemon(0, 0) < 0))
3461 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3463 debug_timestamp_on();
3464 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3466 sigemptyset(&sigset);
3467 /* exit on all but SIGPIPE, ignore more? */
3468 sigaddset(&sigset, SIGPIPE);
3469 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3470 pthread_create(&sigth, NULL, sighandler, NULL);
3472 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3473 srvconf = (struct clsrvconf *)entry->data;
3474 if (srvconf->dynamiclookupcommand)
3476 if (!addserver(srvconf))
3477 debugx(1, DBG_ERR, "failed to add server");
3478 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3479 (void *)(srvconf->servers)))
3480 debugx(1, DBG_ERR, "pthread_create failed");
3483 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3486 if (protodefs[i]->initextra)
3487 protodefs[i]->initextra();
3488 if (find_clconf_type(i, NULL))
3492 /* just hang around doing nothing, anything to do here? */