summaryrefslogtreecommitdiff
path: root/controller
diff options
context:
space:
mode:
authorGrant Limberg <grant.limberg@zerotier.com>2016-11-16 16:23:56 -0800
committerGrant Limberg <grant.limberg@zerotier.com>2016-11-16 16:23:56 -0800
commitb4bacd50a1ae70d53d16aef6880aa1fc6870bd8c (patch)
tree21fd07022eff4a5debd4cc37da02f22660348237 /controller
parent6445337a32f5470e84bb9b139c25697e22d492f6 (diff)
parent3c248ec61a732f539dcf0c9ea3d92ae8f42b62fe (diff)
downloadinfinitytier-b4bacd50a1ae70d53d16aef6880aa1fc6870bd8c.tar.gz
infinitytier-b4bacd50a1ae70d53d16aef6880aa1fc6870bd8c.zip
Merge branch 'dev' into systemtray
Diffstat (limited to 'controller')
-rw-r--r--controller/EmbeddedNetworkController.cpp1140
-rw-r--r--controller/EmbeddedNetworkController.hpp50
-rw-r--r--controller/JSONDB.hpp2
3 files changed, 680 insertions, 512 deletions
diff --git a/controller/EmbeddedNetworkController.cpp b/controller/EmbeddedNetworkController.cpp
index 9c7611a4..b78f847e 100644
--- a/controller/EmbeddedNetworkController.cpp
+++ b/controller/EmbeddedNetworkController.cpp
@@ -459,6 +459,7 @@ static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
}
EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPath) :
+ _threadsStarted(false),
_db(dbPath),
_node(node)
{
@@ -468,461 +469,47 @@ EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPa
EmbeddedNetworkController::~EmbeddedNetworkController()
{
+ Mutex::Lock _l(_threads_m);
+ if (_threadsStarted) {
+ for(int i=0;i<(ZT_EMBEDDEDNETWORKCONTROLLER_BACKGROUND_THREAD_COUNT*2);++i)
+ _queue.post((_RQEntry *)0);
+ for(int i=0;i<ZT_EMBEDDEDNETWORKCONTROLLER_BACKGROUND_THREAD_COUNT;++i)
+ Thread::join(_threads[i]);
+ }
}
-NetworkController::ResultCode EmbeddedNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData,NetworkConfig &nc)
+void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
{
- if (((!signingId)||(!signingId.hasPrivate()))||(signingId.address().toInt() != (nwid >> 24))) {
- return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
- }
-
- const uint64_t now = OSUtils::now();
-
- // Check rate limit circuit breaker to prevent flooding
- {
- Mutex::Lock _l(_lastRequestTime_m);
- uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
- if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
- return NetworkController::NETCONF_QUERY_IGNORE;
- lrt = now;
- }
-
- char nwids[24];
- Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
- json network;
- json member;
- {
- Mutex::Lock _l(_db_m);
- network = _db.get("network",nwids,0);
- member = _db.get("network",nwids,"member",identity.address().toString(),0);
- }
- if (!network.size())
- return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
- _initMember(member);
-
- {
- std::string haveIdStr(_jS(member["identity"],""));
- if (haveIdStr.length() > 0) {
- // If we already know this member's identity perform a full compare. This prevents
- // a "collision" from being able to auth onto our network in place of an already
- // known member.
- try {
- if (Identity(haveIdStr.c_str()) != identity)
- return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
- } catch ( ... ) {
- return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
- }
- } else {
- // If we do not yet know this member's identity, learn it.
- member["identity"] = identity.toString(false);
- }
- }
-
- // These are always the same, but make sure they are set
- member["id"] = identity.address().toString();
- member["address"] = member["id"];
- member["nwid"] = network["id"];
-
- // Determine whether and how member is authorized
- const char *authorizedBy = (const char *)0;
- if (_jB(member["authorized"],false)) {
- authorizedBy = "memberIsAuthorized";
- } else if (!_jB(network["private"],true)) {
- authorizedBy = "networkIsPublic";
- if (!member.count("authorized")) {
- member["authorized"] = true;
- json ah;
- ah["a"] = true;
- ah["by"] = authorizedBy;
- ah["ts"] = now;
- ah["ct"] = json();
- ah["c"] = json();
- member["authHistory"].push_back(ah);
- member["lastModified"] = now;
- json &revj = member["revision"];
- member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
- }
- } else {
- char presentedAuth[512];
- if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
- presentedAuth[511] = (char)0; // sanity check
-
- // Check for bearer token presented by member
- if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
- const char *const presentedToken = presentedAuth + 6;
-
- json &authTokens = network["authTokens"];
- if (authTokens.is_array()) {
- for(unsigned long i=0;i<authTokens.size();++i) {
- json &token = authTokens[i];
- if (token.is_object()) {
- const uint64_t expires = _jI(token["expires"],0ULL);
- const uint64_t maxUses = _jI(token["maxUsesPerMember"],0ULL);
- std::string tstr = _jS(token["token"],"");
+ this->_sender = sender;
+ this->_signingId = signingId;
+}
- if (((expires == 0ULL)||(expires > now))&&(tstr == presentedToken)) {
- bool usable = (maxUses == 0);
- if (!usable) {
- uint64_t useCount = 0;
- json &ahist = member["authHistory"];
- if (ahist.is_array()) {
- for(unsigned long j=0;j<ahist.size();++j) {
- json &ah = ahist[j];
- if ((_jS(ah["ct"],"") == "token")&&(_jS(ah["c"],"") == tstr)&&(_jB(ah["a"],false)))
- ++useCount;
- }
- }
- usable = (useCount < maxUses);
- }
- if (usable) {
- authorizedBy = "token";
- member["authorized"] = true;
- json ah;
- ah["a"] = true;
- ah["by"] = authorizedBy;
- ah["ts"] = now;
- ah["ct"] = "token";
- ah["c"] = tstr;
- member["authHistory"].push_back(ah);
- member["lastModified"] = now;
- json &revj = member["revision"];
- member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
- }
- }
- }
- }
- }
- }
- }
- }
+void EmbeddedNetworkController::request(
+ uint64_t nwid,
+ const InetAddress &fromAddr,
+ uint64_t requestPacketId,
+ const Identity &identity,
+ const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
+{
+ if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
+ return;
- // Log this request
{
- json rlEntry = json::object();
- rlEntry["ts"] = now;
- rlEntry["authorized"] = (authorizedBy) ? true : false;
- rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
- rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
- rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
- rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
- rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
- if (fromAddr)
- rlEntry["fromAddr"] = fromAddr.toString();
-
- json recentLog = json::array();
- recentLog.push_back(rlEntry);
- json &oldLog = member["recentLog"];
- if (oldLog.is_array()) {
- for(unsigned long i=0;i<oldLog.size();++i) {
- recentLog.push_back(oldLog[i]);
- if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
- break;
- }
- }
- member["recentLog"] = recentLog;
- }
-
- // If they are not authorized, STOP!
- if (!authorizedBy) {
- Mutex::Lock _l(_db_m);
- _db.put("network",nwids,"member",identity.address().toString(),member);
- return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
- }
-
- // -------------------------------------------------------------------------
- // If we made it this far, they are authorized.
- // -------------------------------------------------------------------------
-
- _NetworkMemberInfo nmi;
- _getNetworkMemberInfo(now,nwid,nmi);
-
- // Compute credential TTL. This is the "moving window" for COM agreement and
- // the global TTL for Capability and Tag objects. (The same value is used
- // for both.) This is computed by reference to the last time we deauthorized
- // a member, since within the time period since this event any temporal
- // differences are not particularly relevant.
- uint64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
- if (now > nmi.mostRecentDeauthTime)
- credentialtmd += (now - nmi.mostRecentDeauthTime);
- if (credentialtmd > ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA)
- credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
-
- nc.networkId = nwid;
- nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
- nc.timestamp = now;
- nc.credentialTimeMaxDelta = credentialtmd;
- nc.revision = _jI(network["revision"],0ULL);
- nc.issuedTo = identity.address();
- if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
- if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
- Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
- nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
-
- for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab)
- nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
-
- json &v4AssignMode = network["v4AssignMode"];
- json &v6AssignMode = network["v6AssignMode"];
- json &ipAssignmentPools = network["ipAssignmentPools"];
- json &routes = network["routes"];
- json &rules = network["rules"];
- json &capabilities = network["capabilities"];
- json &memberCapabilities = member["capabilities"];
- json &memberTags = member["tags"];
-
- if (rules.is_array()) {
- for(unsigned long i=0;i<rules.size();++i) {
- if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
- break;
- if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
- ++nc.ruleCount;
- }
- }
-
- if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
- std::map< uint64_t,json * > capsById;
- for(unsigned long i=0;i<capabilities.size();++i) {
- json &cap = capabilities[i];
- if (cap.is_object())
- capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = &cap;
- }
-
- for(unsigned long i=0;i<memberCapabilities.size();++i) {
- const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
- json *cap = capsById[capId];
- if ((cap->is_object())&&(cap->size() > 0)) {
- ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
- unsigned int caprc = 0;
- json &caprj = (*cap)["rules"];
- if ((caprj.is_array())&&(caprj.size() > 0)) {
- for(unsigned long j=0;j<caprj.size();++j) {
- if (caprc >= ZT_MAX_CAPABILITY_RULES)
- break;
- if (_parseRule(caprj[j],capr[caprc]))
- ++caprc;
- }
- }
- nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
- if (nc.capabilities[nc.capabilityCount].sign(signingId,identity.address()))
- ++nc.capabilityCount;
- if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
- break;
- }
- }
- }
-
- if (memberTags.is_array()) {
- std::map< uint32_t,uint32_t > tagsById;
- for(unsigned long i=0;i<memberTags.size();++i) {
- json &t = memberTags[i];
- if ((t.is_array())&&(t.size() == 2))
- tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
- }
- for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
- if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
- break;
- nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
- if (nc.tags[nc.tagCount].sign(signingId))
- ++nc.tagCount;
- }
- }
-
- if (routes.is_array()) {
- for(unsigned long i=0;i<routes.size();++i) {
- if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
- break;
- json &route = routes[i];
- json &target = route["target"];
- json &via = route["via"];
- if (target.is_string()) {
- const InetAddress t(target.get<std::string>());
- InetAddress v;
- if (via.is_string()) v.fromString(via.get<std::string>());
- if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
- ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
- *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
- if (v.ss_family == t.ss_family)
- *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
- ++nc.routeCount;
- }
- }
- }
- }
-
- const bool noAutoAssignIps = _jB(member["noAutoAssignIps"],false);
-
- if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
- if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
- nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
- nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
- }
- if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
- nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
- nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
+ Mutex::Lock _l(_threads_m);
+ if (!_threadsStarted) {
+ for(int i=0;i<ZT_EMBEDDEDNETWORKCONTROLLER_BACKGROUND_THREAD_COUNT;++i)
+ _threads[i] = Thread::start(this);
}
+ _threadsStarted = true;
}
- bool haveManagedIpv4AutoAssignment = false;
- bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
- json ipAssignments = member["ipAssignments"]; // we want to make a copy
- if (ipAssignments.is_array()) {
- for(unsigned long i=0;i<ipAssignments.size();++i) {
- if (!ipAssignments[i].is_string())
- continue;
- std::string ips = ipAssignments[i];
- InetAddress ip(ips);
-
- // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
- // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
- // of user error / poor UX.
- int routedNetmaskBits = 0;
- for(unsigned int rk=0;rk<nc.routeCount;++rk) {
- if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
- routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
- }
-
- if (routedNetmaskBits > 0) {
- if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
- ip.setPort(routedNetmaskBits);
- nc.staticIps[nc.staticIpCount++] = ip;
- }
- if (ip.ss_family == AF_INET)
- haveManagedIpv4AutoAssignment = true;
- else if (ip.ss_family == AF_INET6)
- haveManagedIpv6AutoAssignment = true;
- }
- }
- } else {
- ipAssignments = json::array();
- }
-
- if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
- for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
- json &pool = ipAssignmentPools[p];
- if (pool.is_object()) {
- InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
- InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
- if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
- uint64_t s[2],e[2],x[2],xx[2];
- memcpy(s,ipRangeStart.rawIpData(),16);
- memcpy(e,ipRangeEnd.rawIpData(),16);
- s[0] = Utils::ntoh(s[0]);
- s[1] = Utils::ntoh(s[1]);
- e[0] = Utils::ntoh(e[0]);
- e[1] = Utils::ntoh(e[1]);
- x[0] = s[0];
- x[1] = s[1];
-
- for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
- if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
- // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
- xx[0] = Utils::hton(x[0]);
- xx[1] = Utils::hton(x[1] + identity.address().toInt());
- } else {
- // Otherwise pick random addresses -- this technically doesn't explore the whole range if the lower 64 bit range is >= 1 but that won't matter since that would be huge anyway
- Utils::getSecureRandom((void *)xx,16);
- if ((e[0] > s[0]))
- xx[0] %= (e[0] - s[0]);
- else xx[0] = 0;
- if ((e[1] > s[1]))
- xx[1] %= (e[1] - s[1]);
- else xx[1] = 0;
- xx[0] = Utils::hton(x[0] + xx[0]);
- xx[1] = Utils::hton(x[1] + xx[1]);
- }
-
- InetAddress ip6((const void *)xx,16,0);
-
- // Check if this IP is within a local-to-Ethernet routed network
- int routedNetmaskBits = 0;
- for(unsigned int rk=0;rk<nc.routeCount;++rk) {
- if ( (!nc.routes[rk].via.ss_family) && (nc.routes[rk].target.ss_family == AF_INET6) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip6)) )
- routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
- }
-
- // If it's routed, then try to claim and assign it and if successful end loop
- if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
- ipAssignments.push_back(ip6.toIpString());
- member["ipAssignments"] = ipAssignments;
- ip6.setPort((unsigned int)routedNetmaskBits);
- if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
- nc.staticIps[nc.staticIpCount++] = ip6;
- haveManagedIpv6AutoAssignment = true;
- break;
- }
- }
- }
- }
- }
- }
-
- if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
- for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
- json &pool = ipAssignmentPools[p];
- if (pool.is_object()) {
- InetAddress ipRangeStartIA(_jS(pool["ipRangeStart"],""));
- InetAddress ipRangeEndIA(_jS(pool["ipRangeEnd"],""));
- if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
- uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
- uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
- if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
- continue;
- uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
-
- // Start with the LSB of the member's address
- uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
-
- for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
- uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
- ++ipTrialCounter;
- if ((ip & 0x000000ff) == 0x000000ff)
- continue; // don't allow addresses that end in .255
-
- // Check if this IP is within a local-to-Ethernet routed network
- int routedNetmaskBits = -1;
- for(unsigned int rk=0;rk<nc.routeCount;++rk) {
- if (nc.routes[rk].target.ss_family == AF_INET) {
- uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
- int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
- if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
- routedNetmaskBits = targetBits;
- break;
- }
- }
- }
-
- // If it's routed, then try to claim and assign it and if successful end loop
- const InetAddress ip4(Utils::hton(ip),0);
- if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
- ipAssignments.push_back(ip4.toIpString());
- member["ipAssignments"] = ipAssignments;
- if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
- struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
- v4ip->sin_family = AF_INET;
- v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
- v4ip->sin_addr.s_addr = Utils::hton(ip);
- }
- haveManagedIpv4AutoAssignment = true;
- break;
- }
- }
- }
- }
- }
- }
-
- CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
- if (com.sign(signingId)) {
- nc.com = com;
- } else {
- return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
- }
-
- {
- Mutex::Lock _l(_db_m);
- _db.put("network",nwids,"member",identity.address().toString(),member);
- }
- return NetworkController::NETCONF_QUERY_OK;
+ _RQEntry *qe = new _RQEntry;
+ qe->nwid = nwid;
+ qe->requestPacketId = requestPacketId;
+ qe->fromAddr = fromAddr;
+ qe->identity = identity;
+ qe->metaData = metaData;
+ _queue.post(qe);
}
unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
@@ -1073,10 +660,6 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
responseContentType = "application/json";
return 400;
}
- } catch (std::exception &exc) {
- responseBody = std::string("{ \"message\": \"body JSON is invalid: ") + exc.what() + "\" }";
- responseContentType = "application/json";
- return 400;
} catch ( ... ) {
responseBody = "{ \"message\": \"body JSON is invalid\" }";
responseContentType = "application/json";
@@ -1092,13 +675,6 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
if (path.size() >= 3) {
- json network;
- {
- Mutex::Lock _l(_db_m);
- network = _db.get("network",nwids,0);
- }
- if (!network.size())
- return 404;
if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
uint64_t address = Utils::hexStrToU64(path[3].c_str());
@@ -1110,19 +686,19 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
Mutex::Lock _l(_db_m);
member = _db.get("network",nwids,"member",Address(address).toString(),0);
}
- if (!member.size())
- return 404;
+ json origMember(member); // for detecting changes
_initMember(member);
try {
if (b.count("activeBridge")) member["activeBridge"] = _jB(b["activeBridge"],false);
if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = _jB(b["noAutoAssignIps"],false);
- if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
if (b.count("authorized")) {
const bool newAuth = _jB(b["authorized"],false);
if (newAuth != _jB(member["authorized"],false)) {
member["authorized"] = newAuth;
+ member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = now;
+
json ah;
ah["a"] = newAuth;
ah["by"] = "api";
@@ -1189,13 +765,16 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
member["id"] = addrs;
member["address"] = addrs; // legacy
member["nwid"] = nwids;
- member["lastModified"] = now;
- json &revj = member["revision"];
- member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
- {
- Mutex::Lock _l(_db_m);
- _db.put("network",nwids,"member",Address(address).toString(),member);
+ if (member != origMember) {
+ member["lastModified"] = now;
+ json &revj = member["revision"];
+ member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
+ {
+ Mutex::Lock _l(_db_m);
+ _db.put("network",nwids,"member",Address(address).toString(),member);
+ }
+ _pushMemberUpdate(now,nwid,member);
}
// Add non-persisted fields
@@ -1283,9 +862,8 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
}
network = _db.get("network",nwids,0);
- if (!network.size())
- return 404;
}
+ json origNetwork(network); // for detecting changes
_initNetwork(network);
try {
@@ -1466,13 +1044,20 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
network["id"] = nwids;
network["nwid"] = nwids; // legacy
- json &rev = network["revision"];
- network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
- network["lastModified"] = now;
- {
- Mutex::Lock _l(_db_m);
- _db.put("network",nwids,network);
+ if (network != origNetwork) {
+ json &revj = network["revision"];
+ network["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
+ network["lastModified"] = now;
+ {
+ Mutex::Lock _l(_db_m);
+ _db.put("network",nwids,network);
+ }
+ std::string pfx("network/"); pfx.append(nwids); pfx.append("/member/");
+ _db.filter(pfx,120000,[this,&now,&nwid](const std::string &n,const json &obj) {
+ _pushMemberUpdate(now,nwid,obj);
+ return true; // do not delete
+ });
}
_NetworkMemberInfo nmi;
@@ -1523,20 +1108,25 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
Mutex::Lock _l(_db_m);
json member = _db.get("network",nwids,"member",Address(address).toString(),0);
- if (!member.size())
- return 404;
_db.erase("network",nwids,"member",Address(address).toString());
+ if (!member.size())
+ return 404;
responseBody = member.dump(2);
responseContentType = "application/json";
return 200;
}
} else {
Mutex::Lock _l(_db_m);
+
std::string pfx("network/"); pfx.append(nwids);
_db.filter(pfx,120000,[](const std::string &n,const json &obj) {
return false; // delete
});
+
+ Mutex::Lock _l2(_nmiCache_m);
+ _nmiCache.erase(nwid);
+
responseBody = network.dump(2);
responseContentType = "application/json";
return 200;
@@ -1548,6 +1138,19 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
return 404;
}
+void EmbeddedNetworkController::threadMain()
+ throw()
+{
+ for(;;) {
+ _RQEntry *const qe = _queue.get();
+ if (!qe) break; // enqueue a NULL to terminate threads
+ try {
+ _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
+ } catch ( ... ) {}
+ delete qe;
+ }
+}
+
void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
{
char tmp[65535];
@@ -1611,48 +1214,575 @@ void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTes
cte->second.jsonResults.append(tmp);
}
+void EmbeddedNetworkController::_request(
+ uint64_t nwid,
+ const InetAddress &fromAddr,
+ uint64_t requestPacketId,
+ const Identity &identity,
+ const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
+{
+ if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
+ return;
+
+ const uint64_t now = OSUtils::now();
+
+ if (requestPacketId) {
+ Mutex::Lock _l(_lastRequestTime_m);
+ uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
+ if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
+ return;
+ lrt = now;
+ }
+
+ char nwids[24];
+ Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
+ json network;
+ json member;
+ {
+ Mutex::Lock _l(_db_m);
+ network = _db.get("network",nwids,0);
+ member = _db.get("network",nwids,"member",identity.address().toString(),0);
+ }
+
+ if (!network.size()) {
+ _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND);
+ return;
+ }
+
+ json origMember(member); // for detecting modification later
+ _initMember(member);
+
+ {
+ std::string haveIdStr(_jS(member["identity"],""));
+ if (haveIdStr.length() > 0) {
+ // If we already know this member's identity perform a full compare. This prevents
+ // a "collision" from being able to auth onto our network in place of an already
+ // known member.
+ try {
+ if (Identity(haveIdStr.c_str()) != identity) {
+ _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
+ return;
+ }
+ } catch ( ... ) {
+ _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
+ return;
+ }
+ } else {
+ // If we do not yet know this member's identity, learn it.
+ member["identity"] = identity.toString(false);
+ }
+ }
+
+ // These are always the same, but make sure they are set
+ member["id"] = identity.address().toString();
+ member["address"] = member["id"];
+ member["nwid"] = nwids;
+
+ // Determine whether and how member is authorized
+ const char *authorizedBy = (const char *)0;
+ bool autoAuthorized = false;
+ json autoAuthCredentialType,autoAuthCredential;
+ if (_jB(member["authorized"],false)) {
+ authorizedBy = "memberIsAuthorized";
+ } else if (!_jB(network["private"],true)) {
+ authorizedBy = "networkIsPublic";
+ if (!member.count("authorized"))
+ autoAuthorized = true;
+ } else {
+ char presentedAuth[512];
+ if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
+ presentedAuth[511] = (char)0; // sanity check
+
+ // Check for bearer token presented by member
+ if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
+ const char *const presentedToken = presentedAuth + 6;
+
+ json &authTokens = network["authTokens"];
+ if (authTokens.is_array()) {
+ for(unsigned long i=0;i<authTokens.size();++i) {
+ json &token = authTokens[i];
+ if (token.is_object()) {
+ const uint64_t expires = _jI(token["expires"],0ULL);
+ const uint64_t maxUses = _jI(token["maxUsesPerMember"],0ULL);
+ std::string tstr = _jS(token["token"],"");
+
+ if (((expires == 0ULL)||(expires > now))&&(tstr == presentedToken)) {
+ bool usable = (maxUses == 0);
+ if (!usable) {
+ uint64_t useCount = 0;
+ json &ahist = member["authHistory"];
+ if (ahist.is_array()) {
+ for(unsigned long j=0;j<ahist.size();++j) {
+ json &ah = ahist[j];
+ if ((_jS(ah["ct"],"") == "token")&&(_jS(ah["c"],"") == tstr)&&(_jB(ah["a"],false)))
+ ++useCount;
+ }
+ }
+ usable = (useCount < maxUses);
+ }
+ if (usable) {
+ authorizedBy = "token";
+ autoAuthorized = true;
+ autoAuthCredentialType = "token";
+ autoAuthCredential = tstr;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // If we auto-authorized, update member record
+ if ((autoAuthorized)&&(authorizedBy)) {
+ member["authorized"] = true;
+ member["lastAuthorizedTime"] = now;
+
+ json ah;
+ ah["a"] = true;
+ ah["by"] = authorizedBy;
+ ah["ts"] = now;
+ ah["ct"] = autoAuthCredentialType;
+ ah["c"] = autoAuthCredential;
+ member["authHistory"].push_back(ah);
+
+ json &revj = member["revision"];
+ member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
+ }
+
+ // Log this request
+ if (requestPacketId) { // only log if this is a request, not for generated pushes
+ json rlEntry = json::object();
+ rlEntry["ts"] = now;
+ rlEntry["authorized"] = (authorizedBy) ? true : false;
+ rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
+ rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
+ rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
+ rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
+ rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
+ if (fromAddr)
+ rlEntry["fromAddr"] = fromAddr.toString();
+
+ json recentLog = json::array();
+ recentLog.push_back(rlEntry);
+ json &oldLog = member["recentLog"];
+ if (oldLog.is_array()) {
+ for(unsigned long i=0;i<oldLog.size();++i) {
+ recentLog.push_back(oldLog[i]);
+ if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
+ break;
+ }
+ }
+ member["recentLog"] = recentLog;
+
+ // Also only do this on real requests
+ member["lastRequestMetaData"] = metaData.data();
+ }
+
+ // If they are not authorized, STOP!
+ if (!authorizedBy) {
+ if (origMember != member) {
+ member["lastModified"] = now;
+ Mutex::Lock _l(_db_m);
+ _db.put("network",nwids,"member",identity.address().toString(),member);
+ }
+ _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
+ return;
+ }
+
+ // -------------------------------------------------------------------------
+ // If we made it this far, they are authorized.
+ // -------------------------------------------------------------------------
+
+ NetworkConfig nc;
+ _NetworkMemberInfo nmi;
+ _getNetworkMemberInfo(now,nwid,nmi);
+
+ uint64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
+ if (now > nmi.mostRecentDeauthTime) {
+ // If we recently de-authorized a member, shrink credential TTL/max delta to
+ // be below the threshold required to exclude it. Cap this to a min/max to
+ // prevent jitter or absurdly large values.
+ const uint64_t deauthWindow = now - nmi.mostRecentDeauthTime;
+ if (deauthWindow < ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA) {
+ credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
+ } else if (deauthWindow < (ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA + 5000ULL)) {
+ credentialtmd = deauthWindow - 5000ULL;
+ }
+ }
+
+ nc.networkId = nwid;
+ nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
+ nc.timestamp = now;
+ nc.credentialTimeMaxDelta = credentialtmd;
+ nc.revision = _jI(network["revision"],0ULL);
+ nc.issuedTo = identity.address();
+ if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
+ if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
+ Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
+ nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
+
+ for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab) {
+ nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
+ }
+
+ json &v4AssignMode = network["v4AssignMode"];
+ json &v6AssignMode = network["v6AssignMode"];
+ json &ipAssignmentPools = network["ipAssignmentPools"];
+ json &routes = network["routes"];
+ json &rules = network["rules"];
+ json &capabilities = network["capabilities"];
+ json &memberCapabilities = member["capabilities"];
+ json &memberTags = member["tags"];
+
+ if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
+ // Old versions with no rules engine support get an allow everything rule.
+ // Since rules are enforced bidirectionally, newer versions *will* still
+ // enforce rules on the inbound side.
+ nc.ruleCount = 1;
+ nc.rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
+ } else {
+ if (rules.is_array()) {
+ for(unsigned long i=0;i<rules.size();++i) {
+ if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
+ break;
+ if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
+ ++nc.ruleCount;
+ }
+ }
+
+ if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
+ std::map< uint64_t,json * > capsById;
+ for(unsigned long i=0;i<capabilities.size();++i) {
+ json &cap = capabilities[i];
+ if (cap.is_object())
+ capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = &cap;
+ }
+
+ for(unsigned long i=0;i<memberCapabilities.size();++i) {
+ const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
+ json *cap = capsById[capId];
+ if ((cap->is_object())&&(cap->size() > 0)) {
+ ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
+ unsigned int caprc = 0;
+ json &caprj = (*cap)["rules"];
+ if ((caprj.is_array())&&(caprj.size() > 0)) {
+ for(unsigned long j=0;j<caprj.size();++j) {
+ if (caprc >= ZT_MAX_CAPABILITY_RULES)
+ break;
+ if (_parseRule(caprj[j],capr[caprc]))
+ ++caprc;
+ }
+ }
+ nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
+ if (nc.capabilities[nc.capabilityCount].sign(_signingId,identity.address()))
+ ++nc.capabilityCount;
+ if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
+ break;
+ }
+ }
+ }
+
+ if (memberTags.is_array()) {
+ std::map< uint32_t,uint32_t > tagsById;
+ for(unsigned long i=0;i<memberTags.size();++i) {
+ json &t = memberTags[i];
+ if ((t.is_array())&&(t.size() == 2))
+ tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
+ }
+ for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
+ if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
+ break;
+ nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
+ if (nc.tags[nc.tagCount].sign(_signingId))
+ ++nc.tagCount;
+ }
+ }
+ }
+
+ if (routes.is_array()) {
+ for(unsigned long i=0;i<routes.size();++i) {
+ if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
+ break;
+ json &route = routes[i];
+ json &target = route["target"];
+ json &via = route["via"];
+ if (target.is_string()) {
+ const InetAddress t(target.get<std::string>());
+ InetAddress v;
+ if (via.is_string()) v.fromString(via.get<std::string>());
+ if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
+ ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
+ *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
+ if (v.ss_family == t.ss_family)
+ *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
+ ++nc.routeCount;
+ }
+ }
+ }
+ }
+
+ const bool noAutoAssignIps = _jB(member["noAutoAssignIps"],false);
+
+ if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
+ if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
+ nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
+ nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
+ }
+ if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
+ nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
+ nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
+ }
+ }
+
+ bool haveManagedIpv4AutoAssignment = false;
+ bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
+ json ipAssignments = member["ipAssignments"]; // we want to make a copy
+ if (ipAssignments.is_array()) {
+ for(unsigned long i=0;i<ipAssignments.size();++i) {
+ if (!ipAssignments[i].is_string())
+ continue;
+ std::string ips = ipAssignments[i];
+ InetAddress ip(ips);
+
+ // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
+ // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
+ // of user error / poor UX.
+ int routedNetmaskBits = 0;
+ for(unsigned int rk=0;rk<nc.routeCount;++rk) {
+ if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
+ routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
+ }
+
+ if (routedNetmaskBits > 0) {
+ if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
+ ip.setPort(routedNetmaskBits);
+ nc.staticIps[nc.staticIpCount++] = ip;
+ }
+ if (ip.ss_family == AF_INET)
+ haveManagedIpv4AutoAssignment = true;
+ else if (ip.ss_family == AF_INET6)
+ haveManagedIpv6AutoAssignment = true;
+ }
+ }
+ } else {
+ ipAssignments = json::array();
+ }
+
+ if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
+ for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
+ json &pool = ipAssignmentPools[p];
+ if (pool.is_object()) {
+ InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
+ InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
+ if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
+ uint64_t s[2],e[2],x[2],xx[2];
+ memcpy(s,ipRangeStart.rawIpData(),16);
+ memcpy(e,ipRangeEnd.rawIpData(),16);
+ s[0] = Utils::ntoh(s[0]);
+ s[1] = Utils::ntoh(s[1]);
+ e[0] = Utils::ntoh(e[0]);
+ e[1] = Utils::ntoh(e[1]);
+ x[0] = s[0];
+ x[1] = s[1];
+
+ for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
+ if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
+ // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
+ xx[0] = Utils::hton(x[0]);
+ xx[1] = Utils::hton(x[1] + identity.address().toInt());
+ } else {
+ // Otherwise pick random addresses -- this technically doesn't explore the whole range if the lower 64 bit range is >= 1 but that won't matter since that would be huge anyway
+ Utils::getSecureRandom((void *)xx,16);
+ if ((e[0] > s[0]))
+ xx[0] %= (e[0] - s[0]);
+ else xx[0] = 0;
+ if ((e[1] > s[1]))
+ xx[1] %= (e[1] - s[1]);
+ else xx[1] = 0;
+ xx[0] = Utils::hton(x[0] + xx[0]);
+ xx[1] = Utils::hton(x[1] + xx[1]);
+ }
+
+ InetAddress ip6((const void *)xx,16,0);
+
+ // Check if this IP is within a local-to-Ethernet routed network
+ int routedNetmaskBits = 0;
+ for(unsigned int rk=0;rk<nc.routeCount;++rk) {
+ if ( (!nc.routes[rk].via.ss_family) && (nc.routes[rk].target.ss_family == AF_INET6) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip6)) )
+ routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
+ }
+
+ // If it's routed, then try to claim and assign it and if successful end loop
+ if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
+ ipAssignments.push_back(ip6.toIpString());
+ member["ipAssignments"] = ipAssignments;
+ ip6.setPort((unsigned int)routedNetmaskBits);
+ if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
+ nc.staticIps[nc.staticIpCount++] = ip6;
+ haveManagedIpv6AutoAssignment = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
+ for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
+ json &pool = ipAssignmentPools[p];
+ if (pool.is_object()) {
+ InetAddress ipRangeStartIA(_jS(pool["ipRangeStart"],""));
+ InetAddress ipRangeEndIA(_jS(pool["ipRangeEnd"],""));
+ if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
+ uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
+ uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
+ if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
+ continue;
+ uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
+
+ // Start with the LSB of the member's address
+ uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
+
+ for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
+ uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
+ ++ipTrialCounter;
+ if ((ip & 0x000000ff) == 0x000000ff)
+ continue; // don't allow addresses that end in .255
+
+ // Check if this IP is within a local-to-Ethernet routed network
+ int routedNetmaskBits = -1;
+ for(unsigned int rk=0;rk<nc.routeCount;++rk) {
+ if (nc.routes[rk].target.ss_family == AF_INET) {
+ uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
+ int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
+ if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
+ routedNetmaskBits = targetBits;
+ break;
+ }
+ }
+ }
+
+ // If it's routed, then try to claim and assign it and if successful end loop
+ const InetAddress ip4(Utils::hton(ip),0);
+ if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
+ ipAssignments.push_back(ip4.toIpString());
+ member["ipAssignments"] = ipAssignments;
+ if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
+ struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
+ v4ip->sin_family = AF_INET;
+ v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
+ v4ip->sin_addr.s_addr = Utils::hton(ip);
+ }
+ haveManagedIpv4AutoAssignment = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
+ if (com.sign(_signingId)) {
+ nc.com = com;
+ } else {
+ _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR);
+ return;
+ }
+
+ if (member != origMember) {
+ member["lastModified"] = now;
+ Mutex::Lock _l(_db_m);
+ _db.put("network",nwids,"member",identity.address().toString(),member);
+ }
+
+ _sender->ncSendConfig(nwid,requestPacketId,identity.address(),nc,metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
+}
+
void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
{
char pfx[256];
Utils::snprintf(pfx,sizeof(pfx),"network/%.16llx/member",nwid);
- Mutex::Lock _l(_db_m);
- _db.filter(pfx,120000,[&nmi,&now](const std::string &n,const json &member) {
- try {
- if (_jB(member["authorized"],false)) {
- ++nmi.authorizedMemberCount;
-
- if (member.count("recentLog")) {
- const json &mlog = member["recentLog"];
- if ((mlog.is_array())&&(mlog.size() > 0)) {
- const json &mlog1 = mlog[0];
- if (mlog1.is_object()) {
- if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
- ++nmi.activeMemberCount;
+ {
+ Mutex::Lock _l(_nmiCache_m);
+ std::map<uint64_t,_NetworkMemberInfo>::iterator c(_nmiCache.find(nwid));
+ if ((c != _nmiCache.end())&&((now - c->second.nmiTimestamp) < 1000)) { // a short duration cache but limits CPU use on big networks
+ nmi = c->second;
+ return;
+ }
+ }
+
+ {
+ Mutex::Lock _l(_db_m);
+ _db.filter(pfx,120000,[&nmi,&now](const std::string &n,const json &member) {
+ try {
+ if (_jB(member["authorized"],false)) {
+ ++nmi.authorizedMemberCount;
+
+ if (member.count("recentLog")) {
+ const json &mlog = member["recentLog"];
+ if ((mlog.is_array())&&(mlog.size() > 0)) {
+ const json &mlog1 = mlog[0];
+ if (mlog1.is_object()) {
+ if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
+ ++nmi.activeMemberCount;
+ }
}
}
- }
- if (_jB(member["activeBridge"],false)) {
- nmi.activeBridges.insert(_jS(member["id"],"0000000000"));
- }
+ if (_jB(member["activeBridge"],false)) {
+ nmi.activeBridges.insert(_jS(member["id"],"0000000000"));
+ }
- if (member.count("ipAssignments")) {
- const json &mips = member["ipAssignments"];
- if (mips.is_array()) {
- for(unsigned long i=0;i<mips.size();++i) {
- InetAddress mip(_jS(mips[i],""));
- if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
- nmi.allocatedIps.insert(mip);
+ if (member.count("ipAssignments")) {
+ const json &mips = member["ipAssignments"];
+ if (mips.is_array()) {
+ for(unsigned long i=0;i<mips.size();++i) {
+ InetAddress mip(_jS(mips[i],""));
+ if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
+ nmi.allocatedIps.insert(mip);
+ }
}
}
+ } else {
+ nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(member["lastDeauthorizedTime"],0ULL));
}
- } else {
- nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(member["lastDeauthorizedTime"],0ULL));
+ } catch ( ... ) {}
+ return true;
+ });
+ }
+ nmi.nmiTimestamp = now;
+
+ {
+ Mutex::Lock _l(_nmiCache_m);
+ _nmiCache[nwid] = nmi;
+ }
+}
+
+void EmbeddedNetworkController::_pushMemberUpdate(uint64_t now,uint64_t nwid,const nlohmann::json &member)
+{
+ try {
+ const std::string idstr = member["identity"];
+ const std::string mdstr = member["lastRequestMetaData"];
+ if ((idstr.length() > 0)&&(mdstr.length() > 0)) {
+ const Identity id(idstr);
+ bool online;
+ {
+ Mutex::Lock _l(_lastRequestTime_m);
+ std::map<std::pair<uint64_t,uint64_t>,uint64_t>::iterator lrt(_lastRequestTime.find(std::pair<uint64_t,uint64_t>(id.address().toInt(),nwid)));
+ online = ( (lrt != _lastRequestTime.end()) && ((now - lrt->second) < ZT_NETWORK_AUTOCONF_DELAY) );
}
- } catch ( ... ) {}
- return true;
- });
+ Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> *metaData = new Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY>(mdstr.c_str());
+ try {
+ this->request(nwid,InetAddress(),0,id,*metaData);
+ } catch ( ... ) {}
+ delete metaData;
+ }
+ } catch ( ... ) {}
}
} // namespace ZeroTier
diff --git a/controller/EmbeddedNetworkController.hpp b/controller/EmbeddedNetworkController.hpp
index 59404f06..cde6522d 100644
--- a/controller/EmbeddedNetworkController.hpp
+++ b/controller/EmbeddedNetworkController.hpp
@@ -37,11 +37,15 @@
#include "../osdep/OSUtils.hpp"
#include "../osdep/Thread.hpp"
+#include "../osdep/BlockingQueue.hpp"
#include "../ext/json/json.hpp"
#include "JSONDB.hpp"
+// Number of background threads to start -- not actually started until needed
+#define ZT_EMBEDDEDNETWORKCONTROLLER_BACKGROUND_THREAD_COUNT 2
+
namespace ZeroTier {
class Node;
@@ -52,13 +56,14 @@ public:
EmbeddedNetworkController(Node *node,const char *dbPath);
virtual ~EmbeddedNetworkController();
- virtual NetworkController::ResultCode doNetworkConfigRequest(
+ virtual void init(const Identity &signingId,Sender *sender);
+
+ virtual void request(
+ uint64_t nwid,
const InetAddress &fromAddr,
- const Identity &signingId,
+ uint64_t requestPacketId,
const Identity &identity,
- uint64_t nwid,
- const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData,
- NetworkConfig &nc);
+ const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
unsigned int handleControlPlaneHttpGET(
const std::vector<std::string> &path,
@@ -82,8 +87,31 @@ public:
std::string &responseBody,
std::string &responseContentType);
+ void threadMain()
+ throw();
+
private:
static void _circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report);
+ void _request(
+ uint64_t nwid,
+ const InetAddress &fromAddr,
+ uint64_t requestPacketId,
+ const Identity &identity,
+ const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
+
+ struct _RQEntry
+ {
+ uint64_t nwid;
+ uint64_t requestPacketId;
+ InetAddress fromAddr;
+ Identity identity;
+ Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData;
+ };
+ BlockingQueue<_RQEntry *> _queue;
+
+ Thread _threads[ZT_EMBEDDEDNETWORKCONTROLLER_BACKGROUND_THREAD_COUNT];
+ bool _threadsStarted;
+ Mutex _threads_m;
// Gathers a bunch of statistics about members of a network, IP assignments, etc. that we need in various places
// This does lock _networkMemberCache_m
@@ -96,9 +124,14 @@ private:
unsigned long activeMemberCount;
unsigned long totalMemberCount;
uint64_t mostRecentDeauthTime;
+ uint64_t nmiTimestamp; // time this NMI structure was computed
};
+ std::map<uint64_t,_NetworkMemberInfo> _nmiCache;
+ Mutex _nmiCache_m;
void _getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi);
+ void _pushMemberUpdate(uint64_t now,uint64_t nwid,const nlohmann::json &member);
+
// These init objects with default and static/informational fields
inline void _initMember(nlohmann::json &member)
{
@@ -112,7 +145,8 @@ private:
if (!member.count("creationTime")) member["creationTime"] = OSUtils::now();
if (!member.count("noAutoAssignIps")) member["noAutoAssignIps"] = false;
if (!member.count("revision")) member["revision"] = 0ULL;
- if (!member.count("enableBroadcast")) member["enableBroadcast"] = true;
+ if (!member.count("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
+ if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
member["objtype"] = "member";
}
inline void _initNetwork(nlohmann::json &network)
@@ -121,6 +155,7 @@ private:
if (!network.count("creationTime")) network["creationTime"] = OSUtils::now();
if (!network.count("name")) network["name"] = "";
if (!network.count("multicastLimit")) network["multicastLimit"] = (uint64_t)32;
+ if (!network.count("enableBroadcast")) network["enableBroadcast"] = true;
if (!network.count("v4AssignMode")) network["v4AssignMode"] = {{"zt",false}};
if (!network.count("v6AssignMode")) network["v6AssignMode"] = {{"rfc4193",false},{"zt",false},{"6plane",false}};
if (!network.count("authTokens")) network["authTokens"] = nlohmann::json::array();
@@ -154,6 +189,9 @@ private:
Node *const _node;
std::string _path;
+ NetworkController::Sender *_sender;
+ Identity _signingId;
+
struct _CircuitTestEntry
{
ZT_CircuitTest *test;
diff --git a/controller/JSONDB.hpp b/controller/JSONDB.hpp
index a9a5e6ac..bd1ae5a5 100644
--- a/controller/JSONDB.hpp
+++ b/controller/JSONDB.hpp
@@ -79,7 +79,7 @@ public:
{
for(std::map<std::string,_E>::iterator i(_db.lower_bound(prefix));i!=_db.end();) {
if ((i->first.length() >= prefix.length())&&(!memcmp(i->first.data(),prefix.data(),prefix.length()))) {
- if (!func(i->first,get(i->second.obj,maxSinceCheck))) {
+ if (!func(i->first,get(i->first,maxSinceCheck))) {
std::map<std::string,_E>::iterator i2(i); ++i2;
this->erase(i->first);
i = i2;