upgraded core to 1.2.0
This commit is contained in:
1845
zto/controller/EmbeddedNetworkController.cpp
Normal file
1845
zto/controller/EmbeddedNetworkController.cpp
Normal file
File diff suppressed because it is too large
Load Diff
217
zto/controller/EmbeddedNetworkController.hpp
Normal file
217
zto/controller/EmbeddedNetworkController.hpp
Normal file
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* ZeroTier One - Network Virtualization Everywhere
|
||||
* Copyright (C) 2011-2015 ZeroTier, Inc.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef ZT_SQLITENETWORKCONTROLLER_HPP
|
||||
#define ZT_SQLITENETWORKCONTROLLER_HPP
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <list>
|
||||
|
||||
#include "../node/Constants.hpp"
|
||||
|
||||
#include "../node/NetworkController.hpp"
|
||||
#include "../node/Mutex.hpp"
|
||||
#include "../node/Utils.hpp"
|
||||
#include "../node/Address.hpp"
|
||||
#include "../node/InetAddress.hpp"
|
||||
|
||||
#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 4
|
||||
|
||||
// TTL for circuit tests
|
||||
#define ZT_EMBEDDEDNETWORKCONTROLLER_CIRCUIT_TEST_EXPIRATION 120000
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
class Node;
|
||||
|
||||
class EmbeddedNetworkController : public NetworkController
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @param node Parent node
|
||||
* @param dbPath Path to store data
|
||||
*/
|
||||
EmbeddedNetworkController(Node *node,const char *dbPath);
|
||||
virtual ~EmbeddedNetworkController();
|
||||
|
||||
virtual void init(const Identity &signingId,Sender *sender);
|
||||
|
||||
virtual void request(
|
||||
uint64_t nwid,
|
||||
const InetAddress &fromAddr,
|
||||
uint64_t requestPacketId,
|
||||
const Identity &identity,
|
||||
const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
|
||||
|
||||
unsigned int handleControlPlaneHttpGET(
|
||||
const std::vector<std::string> &path,
|
||||
const std::map<std::string,std::string> &urlArgs,
|
||||
const std::map<std::string,std::string> &headers,
|
||||
const std::string &body,
|
||||
std::string &responseBody,
|
||||
std::string &responseContentType);
|
||||
unsigned int handleControlPlaneHttpPOST(
|
||||
const std::vector<std::string> &path,
|
||||
const std::map<std::string,std::string> &urlArgs,
|
||||
const std::map<std::string,std::string> &headers,
|
||||
const std::string &body,
|
||||
std::string &responseBody,
|
||||
std::string &responseContentType);
|
||||
unsigned int handleControlPlaneHttpDELETE(
|
||||
const std::vector<std::string> &path,
|
||||
const std::map<std::string,std::string> &urlArgs,
|
||||
const std::map<std::string,std::string> &headers,
|
||||
const std::string &body,
|
||||
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
|
||||
struct _NetworkMemberInfo
|
||||
{
|
||||
_NetworkMemberInfo() : authorizedMemberCount(0),activeMemberCount(0),totalMemberCount(0),mostRecentDeauthTime(0) {}
|
||||
std::set<Address> activeBridges;
|
||||
std::set<InetAddress> allocatedIps;
|
||||
unsigned long authorizedMemberCount;
|
||||
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);
|
||||
inline void _clearNetworkMemberInfoCache(const uint64_t nwid)
|
||||
{
|
||||
Mutex::Lock _l(_nmiCache_m);
|
||||
_nmiCache.erase(nwid);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
if (!member.count("authorized")) member["authorized"] = false;
|
||||
if (!member.count("authHistory")) member["authHistory"] = nlohmann::json::array();
|
||||
if (!member.count("ipAssignments")) member["ipAssignments"] = nlohmann::json::array();
|
||||
if (!member.count("recentLog")) member["recentLog"] = nlohmann::json::array();
|
||||
if (!member.count("activeBridge")) member["activeBridge"] = false;
|
||||
if (!member.count("tags")) member["tags"] = nlohmann::json::array();
|
||||
if (!member.count("capabilities")) member["capabilities"] = nlohmann::json::array();
|
||||
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("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
|
||||
if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
|
||||
member["objtype"] = "member";
|
||||
}
|
||||
inline void _initNetwork(nlohmann::json &network)
|
||||
{
|
||||
if (!network.count("private")) network["private"] = true;
|
||||
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();
|
||||
if (!network.count("capabilities")) network["capabilities"] = nlohmann::json::array();
|
||||
if (!network.count("tags")) network["tags"] = nlohmann::json::array();
|
||||
if (!network.count("routes")) network["routes"] = nlohmann::json::array();
|
||||
if (!network.count("ipAssignmentPools")) network["ipAssignmentPools"] = nlohmann::json::array();
|
||||
if (!network.count("rules")) {
|
||||
// If unspecified, rules are set to allow anything and behave like a flat L2 segment
|
||||
network["rules"] = {{
|
||||
{ "not",false },
|
||||
{ "or", false },
|
||||
{ "type","ACTION_ACCEPT" }
|
||||
}};
|
||||
}
|
||||
network["objtype"] = "network";
|
||||
}
|
||||
inline void _addNetworkNonPersistedFields(nlohmann::json &network,uint64_t now,const _NetworkMemberInfo &nmi)
|
||||
{
|
||||
network["clock"] = now;
|
||||
network["authorizedMemberCount"] = nmi.authorizedMemberCount;
|
||||
network["activeMemberCount"] = nmi.activeMemberCount;
|
||||
network["totalMemberCount"] = nmi.totalMemberCount;
|
||||
}
|
||||
inline void _addMemberNonPersistedFields(nlohmann::json &member,uint64_t now)
|
||||
{
|
||||
member["clock"] = now;
|
||||
}
|
||||
|
||||
JSONDB _db;
|
||||
Mutex _db_m;
|
||||
|
||||
Node *const _node;
|
||||
std::string _path;
|
||||
|
||||
NetworkController::Sender *_sender;
|
||||
Identity _signingId;
|
||||
|
||||
std::list< ZT_CircuitTest > _tests;
|
||||
Mutex _tests_m;
|
||||
|
||||
std::map< std::pair<uint64_t,uint64_t>,uint64_t > _lastRequestTime; // last request time by <address,networkId>
|
||||
Mutex _lastRequestTime_m;
|
||||
};
|
||||
|
||||
} // namespace ZeroTier
|
||||
|
||||
#endif
|
||||
184
zto/controller/JSONDB.cpp
Normal file
184
zto/controller/JSONDB.cpp
Normal file
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* ZeroTier One - Network Virtualization Everywhere
|
||||
* Copyright (C) 2011-2015 ZeroTier, Inc.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "JSONDB.hpp"
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
static const nlohmann::json _EMPTY_JSON(nlohmann::json::object());
|
||||
|
||||
bool JSONDB::writeRaw(const std::string &n,const std::string &obj)
|
||||
{
|
||||
if (!_isValidObjectName(n))
|
||||
return false;
|
||||
|
||||
const std::string path(_genPath(n,true));
|
||||
if (!path.length())
|
||||
return false;
|
||||
|
||||
const std::string buf(obj);
|
||||
if (!OSUtils::writeFile(path.c_str(),buf))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool JSONDB::put(const std::string &n,const nlohmann::json &obj)
|
||||
{
|
||||
if (!_isValidObjectName(n))
|
||||
return false;
|
||||
|
||||
const std::string path(_genPath(n,true));
|
||||
if (!path.length())
|
||||
return false;
|
||||
|
||||
const std::string buf(OSUtils::jsonDump(obj));
|
||||
if (!OSUtils::writeFile(path.c_str(),buf))
|
||||
return false;
|
||||
|
||||
_E &e = _db[n];
|
||||
e.obj = obj;
|
||||
e.lastModifiedOnDisk = OSUtils::getLastModified(path.c_str());
|
||||
e.lastCheck = OSUtils::now();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
const nlohmann::json &JSONDB::get(const std::string &n,unsigned long maxSinceCheck)
|
||||
{
|
||||
if (!_isValidObjectName(n))
|
||||
return _EMPTY_JSON;
|
||||
|
||||
const uint64_t now = OSUtils::now();
|
||||
std::string buf;
|
||||
std::map<std::string,_E>::iterator e(_db.find(n));
|
||||
|
||||
if (e != _db.end()) {
|
||||
if ((now - e->second.lastCheck) <= (uint64_t)maxSinceCheck)
|
||||
return e->second.obj;
|
||||
|
||||
const std::string path(_genPath(n,false));
|
||||
if (!path.length()) // sanity check
|
||||
return _EMPTY_JSON;
|
||||
|
||||
// We are somewhat tolerant to momentary disk failures here. This may
|
||||
// occur over e.g. EC2's elastic filesystem (NFS).
|
||||
const uint64_t lm = OSUtils::getLastModified(path.c_str());
|
||||
if (e->second.lastModifiedOnDisk != lm) {
|
||||
if (OSUtils::readFile(path.c_str(),buf)) {
|
||||
try {
|
||||
e->second.obj = OSUtils::jsonParse(buf);
|
||||
e->second.lastModifiedOnDisk = lm; // don't update these if there is a parse error -- try again and again ASAP
|
||||
e->second.lastCheck = now;
|
||||
} catch ( ... ) {} // parse errors result in "holding pattern" behavior
|
||||
}
|
||||
}
|
||||
|
||||
return e->second.obj;
|
||||
} else {
|
||||
const std::string path(_genPath(n,false));
|
||||
if (!path.length())
|
||||
return _EMPTY_JSON;
|
||||
|
||||
if (!OSUtils::readFile(path.c_str(),buf))
|
||||
return _EMPTY_JSON;
|
||||
|
||||
const uint64_t lm = OSUtils::getLastModified(path.c_str());
|
||||
_E &e2 = _db[n];
|
||||
try {
|
||||
e2.obj = OSUtils::jsonParse(buf);
|
||||
} catch ( ... ) {
|
||||
e2.obj = _EMPTY_JSON;
|
||||
buf = "{}";
|
||||
}
|
||||
e2.lastModifiedOnDisk = lm;
|
||||
e2.lastCheck = now;
|
||||
|
||||
return e2.obj;
|
||||
}
|
||||
}
|
||||
|
||||
void JSONDB::erase(const std::string &n)
|
||||
{
|
||||
if (!_isValidObjectName(n))
|
||||
return;
|
||||
|
||||
std::string path(_genPath(n,true));
|
||||
if (!path.length())
|
||||
return;
|
||||
|
||||
OSUtils::rm(path.c_str());
|
||||
_db.erase(n);
|
||||
}
|
||||
|
||||
void JSONDB::_reload(const std::string &p)
|
||||
{
|
||||
std::map<std::string,char> l(OSUtils::listDirectoryFull(p.c_str()));
|
||||
for(std::map<std::string,char>::iterator li(l.begin());li!=l.end();++li) {
|
||||
if (li->second == 'f') {
|
||||
// assume p starts with _basePath, which it always does -- will throw otherwise
|
||||
std::string n(p.substr(_basePath.length()));
|
||||
while ((n.length() > 0)&&(n[0] == ZT_PATH_SEPARATOR)) n = n.substr(1);
|
||||
if (ZT_PATH_SEPARATOR != '/') std::replace(n.begin(),n.end(),ZT_PATH_SEPARATOR,'/');
|
||||
if ((n.length() > 0)&&(n[n.length() - 1] != '/')) n.push_back('/');
|
||||
n.append(li->first);
|
||||
if ((n.length() > 5)&&(n.substr(n.length() - 5) == ".json")) {
|
||||
this->get(n.substr(0,n.length() - 5),0); // causes load and cache or update
|
||||
}
|
||||
} else if (li->second == 'd') {
|
||||
this->_reload(p + ZT_PATH_SEPARATOR + li->first);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool JSONDB::_isValidObjectName(const std::string &n)
|
||||
{
|
||||
if (n.length() == 0)
|
||||
return false;
|
||||
const char *p = n.c_str();
|
||||
char c;
|
||||
// For security reasons we should not allow dots, backslashes, or other path characters or potential path characters.
|
||||
while ((c = *(p++))) {
|
||||
if (!( ((c >= 'a')&&(c <= 'z')) || ((c >= 'A')&&(c <= 'Z')) || ((c >= '0')&&(c <= '9')) || (c == '/') || (c == '_') || (c == '~') || (c == '-') ))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string JSONDB::_genPath(const std::string &n,bool create)
|
||||
{
|
||||
std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
|
||||
if (pt.size() == 0)
|
||||
return std::string();
|
||||
|
||||
std::string p(_basePath);
|
||||
if (create) OSUtils::mkdir(p.c_str());
|
||||
for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
|
||||
p.push_back(ZT_PATH_SEPARATOR);
|
||||
p.append(pt[i]);
|
||||
if (create) OSUtils::mkdir(p.c_str());
|
||||
}
|
||||
|
||||
p.push_back(ZT_PATH_SEPARATOR);
|
||||
p.append(pt[pt.size()-1]);
|
||||
p.append(".json");
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
} // namespace ZeroTier
|
||||
118
zto/controller/JSONDB.hpp
Normal file
118
zto/controller/JSONDB.hpp
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* ZeroTier One - Network Virtualization Everywhere
|
||||
* Copyright (C) 2011-2015 ZeroTier, Inc.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef ZT_JSONDB_HPP
|
||||
#define ZT_JSONDB_HPP
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
#include "../node/Constants.hpp"
|
||||
#include "../node/Utils.hpp"
|
||||
#include "../ext/json/json.hpp"
|
||||
#include "../osdep/OSUtils.hpp"
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
/**
|
||||
* Hierarchical JSON store that persists into the filesystem
|
||||
*/
|
||||
class JSONDB
|
||||
{
|
||||
public:
|
||||
JSONDB(const std::string &basePath) :
|
||||
_basePath(basePath)
|
||||
{
|
||||
_reload(_basePath);
|
||||
}
|
||||
|
||||
inline void reload()
|
||||
{
|
||||
_db.clear();
|
||||
_reload(_basePath);
|
||||
}
|
||||
|
||||
bool writeRaw(const std::string &n,const std::string &obj);
|
||||
|
||||
bool put(const std::string &n,const nlohmann::json &obj);
|
||||
|
||||
inline bool put(const std::string &n1,const std::string &n2,const nlohmann::json &obj) { return this->put((n1 + "/" + n2),obj); }
|
||||
inline bool put(const std::string &n1,const std::string &n2,const std::string &n3,const nlohmann::json &obj) { return this->put((n1 + "/" + n2 + "/" + n3),obj); }
|
||||
inline bool put(const std::string &n1,const std::string &n2,const std::string &n3,const std::string &n4,const nlohmann::json &obj) { return this->put((n1 + "/" + n2 + "/" + n3 + "/" + n4),obj); }
|
||||
inline bool put(const std::string &n1,const std::string &n2,const std::string &n3,const std::string &n4,const std::string &n5,const nlohmann::json &obj) { return this->put((n1 + "/" + n2 + "/" + n3 + "/" + n4 + "/" + n5),obj); }
|
||||
|
||||
const nlohmann::json &get(const std::string &n,unsigned long maxSinceCheck = 0);
|
||||
|
||||
inline const nlohmann::json &get(const std::string &n1,const std::string &n2,unsigned long maxSinceCheck = 0) { return this->get((n1 + "/" + n2),maxSinceCheck); }
|
||||
inline const nlohmann::json &get(const std::string &n1,const std::string &n2,const std::string &n3,unsigned long maxSinceCheck = 0) { return this->get((n1 + "/" + n2 + "/" + n3),maxSinceCheck); }
|
||||
inline const nlohmann::json &get(const std::string &n1,const std::string &n2,const std::string &n3,const std::string &n4,unsigned long maxSinceCheck = 0) { return this->get((n1 + "/" + n2 + "/" + n3 + "/" + n4),maxSinceCheck); }
|
||||
inline const nlohmann::json &get(const std::string &n1,const std::string &n2,const std::string &n3,const std::string &n4,const std::string &n5,unsigned long maxSinceCheck = 0) { return this->get((n1 + "/" + n2 + "/" + n3 + "/" + n4 + "/" + n5),maxSinceCheck); }
|
||||
|
||||
void erase(const std::string &n);
|
||||
|
||||
inline void erase(const std::string &n1,const std::string &n2) { this->erase(n1 + "/" + n2); }
|
||||
inline void erase(const std::string &n1,const std::string &n2,const std::string &n3) { this->erase(n1 + "/" + n2 + "/" + n3); }
|
||||
inline void erase(const std::string &n1,const std::string &n2,const std::string &n3,const std::string &n4) { this->erase(n1 + "/" + n2 + "/" + n3 + "/" + n4); }
|
||||
inline void erase(const std::string &n1,const std::string &n2,const std::string &n3,const std::string &n4,const std::string &n5) { this->erase(n1 + "/" + n2 + "/" + n3 + "/" + n4 + "/" + n5); }
|
||||
|
||||
template<typename F>
|
||||
inline void filter(const std::string &prefix,unsigned long maxSinceCheck,F func)
|
||||
{
|
||||
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->first,maxSinceCheck))) {
|
||||
std::map<std::string,_E>::iterator i2(i); ++i2;
|
||||
this->erase(i->first);
|
||||
i = i2;
|
||||
} else ++i;
|
||||
} else break;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool operator==(const JSONDB &db) const { return ((_basePath == db._basePath)&&(_db == db._db)); }
|
||||
inline bool operator!=(const JSONDB &db) const { return (!(*this == db)); }
|
||||
|
||||
private:
|
||||
void _reload(const std::string &p);
|
||||
bool _isValidObjectName(const std::string &n);
|
||||
std::string _genPath(const std::string &n,bool create);
|
||||
|
||||
struct _E
|
||||
{
|
||||
nlohmann::json obj;
|
||||
uint64_t lastModifiedOnDisk;
|
||||
uint64_t lastCheck;
|
||||
|
||||
inline bool operator==(const _E &e) const { return (obj == e.obj); }
|
||||
inline bool operator!=(const _E &e) const { return (obj != e.obj); }
|
||||
};
|
||||
|
||||
std::string _basePath;
|
||||
std::map<std::string,_E> _db;
|
||||
};
|
||||
|
||||
} // namespace ZeroTier
|
||||
|
||||
#endif
|
||||
248
zto/controller/README.md
Normal file
248
zto/controller/README.md
Normal file
@@ -0,0 +1,248 @@
|
||||
Network Controller Microservice
|
||||
======
|
||||
|
||||
Every ZeroTier virtual network has a *network controller*. This is our reference implementation and is the same one we use to power our own hosted services at [my.zerotier.com](https://my.zerotier.com/). Network controllers act as configuration servers and certificate authorities for the members of networks. Controllers are located on the network by simply parsing out the first 10 digits of a network's 16-digit network ID: these are the address of the controller.
|
||||
|
||||
As of ZeroTier One version 1.2.0 this code is included in normal builds for desktop, laptop, and server (Linux, etc.) targets, allowing any device to create virtual networks without having to be rebuilt from source with special flags to enable this feature. While this does offer a convenient way to create ad-hoc networks or experiment, we recommend running a dedicated controller somewhere secure and stable for any "serious" use case.
|
||||
|
||||
Controller data is stored in JSON format under `controller.d` in the ZeroTier working directory. It can be copied, rsync'd, placed in `git`, etc. The files under `controller.d` should not be modified in place while the controller is running or data loss may result, and if they are edited directly take care not to save corrupt JSON since that can also lead to data loss when the controller is restarted. Going through the API is strongly preferred to directly modifying these files.
|
||||
|
||||
### Upgrading from Older (1.1.14 or earlier) Versions
|
||||
|
||||
Older versions of this code used a SQLite database instead of in-filesystem JSON. A migration utility called `migrate-sqlite` is included here and *must* be used to migrate this data to the new format. If the controller is started with an old `controller.db` in its working directory it will terminate after printing an error to *stderr*. This is done to prevent "surprises" for those running DIY controllers using the old code.
|
||||
|
||||
The migration tool is written in nodeJS and can be used like this:
|
||||
|
||||
cd migrate-sqlite
|
||||
npm install
|
||||
node migrate.js </path/to/controller.db> </path/to/controller.d>
|
||||
|
||||
Very old versions of nodeJS may have issues. We tested it with version 7.
|
||||
|
||||
### Scalability and Reliability
|
||||
|
||||
Controllers can in theory host up to 2^24 networks and serve many millions of devices (or more), but we recommend spreading large numbers of networks across many controllers for load balancing and fault tolerance reasons. Since the controller uses the filesystem as its data store we recommend fast filesystems and fast SSD drives for heavily loaded controllers.
|
||||
|
||||
Since ZeroTier nodes are mobile and do not need static IPs, implementing high availability fail-over for controllers is easy. Just replicate their working directories from master to backup and have something automatically fire up the backup if the master goes down. Many modern orchestration tools have built-in support for this. It would also be possible in theory to run controllers on a replicated or distributed filesystem, but we haven't tested this yet.
|
||||
|
||||
### Dockerizing Controllers
|
||||
|
||||
ZeroTier network controllers can easily be run in Docker or other container systems. Since containers do not need to actually join networks, extra privilege options like "--device=/dev/net/tun --privileged" are not needed. You'll just need to map the local JSON API port of the running controller and allow it to access the Internet (over UDP/9993 at a minimum) so things can reach and query it.
|
||||
|
||||
### Network Controller API
|
||||
|
||||
The controller API is hosted via the same JSON API endpoint that ZeroTier One uses for local control (usually at 127.0.0.1 port 9993). All controller options are routed under the `/controller` base path.
|
||||
|
||||
The controller microservice does not implement any fine-grained access control (authentication is via authtoken.secret just like the regular JSON API) or other complex mangement features. It just takes network and network member configurations and reponds to controller queries. We have an enterprise product called [ZeroTier Central](https://my.zerotier.com/) that we host as a service (and that companies can license to self-host) that does this.
|
||||
|
||||
All working network IDs on a controller must begin with the controller's ZeroTier address. The API will *allow* "foreign" networks to be added but the controller will have no way of doing anything with them since nobody will know to query it. (In the future we might support secondaries, which would make this relevant.)
|
||||
|
||||
The JSON API is *very* sensitive about types. Integers must be integers and strings strings, etc. Incorrectly typed and unrecognized fields may result in ignored fields or a 400 (bad request) error.
|
||||
|
||||
#### `/controller`
|
||||
|
||||
* Purpose: Check for controller function and return controller status
|
||||
* Methods: GET
|
||||
* Returns: { object }
|
||||
|
||||
| Field | Type | Description | Writable |
|
||||
| ------------------ | ----------- | ------------------------------------------------- | -------- |
|
||||
| controller | boolean | Always 'true' | no |
|
||||
| apiVersion | integer | Controller API version, currently 3 | no |
|
||||
| clock | integer | Current clock on controller, ms since epoch | no |
|
||||
|
||||
#### `/controller/network`
|
||||
|
||||
* Purpose: List all networks hosted by this controller
|
||||
* Methods: GET
|
||||
* Returns: [ string, ... ]
|
||||
|
||||
This returns an array of 16-digit hexadecimal network IDs.
|
||||
|
||||
#### `/controller/network/<network ID>`
|
||||
|
||||
* Purpose: Create, configure, and delete hosted networks
|
||||
* Methods: GET, POST, DELETE
|
||||
* Returns: { object }
|
||||
|
||||
By making queries to this path you can create, configure, and delete networks. DELETE is final, so don't do it unless you really mean it.
|
||||
|
||||
When POSTing new networks take care that their IDs are not in use, otherwise you may overwrite an existing one. To create a new network with a random unused ID, POST to `/controller/network/##########______`. The #'s are the controller's 10-digit ZeroTier address and they're followed by six underscores. Check the `nwid` field of the returned JSON object for your network's newly allocated ID. Subsequent POSTs to this network must refer to its actual path.
|
||||
|
||||
| Field | Type | Description | Writable |
|
||||
| --------------------- | ------------- | ------------------------------------------------- | -------- |
|
||||
| id | string | 16-digit network ID | no |
|
||||
| nwid | string | 16-digit network ID (old, but still around) | no |
|
||||
| clock | integer | Current clock, ms since epoch | no |
|
||||
| name | string | A short name for this network | YES |
|
||||
| private | boolean | Is access control enabled? | YES |
|
||||
| enableBroadcast | boolean | Ethernet ff:ff:ff:ff:ff:ff allowed? | YES |
|
||||
| allowPassiveBridging | boolean | Allow any member to bridge (very experimental) | YES |
|
||||
| v4AssignMode | object | IPv4 management and assign options (see below) | YES |
|
||||
| v6AssignMode | object | IPv6 management and assign options (see below) | YES |
|
||||
| multicastLimit | integer | Maximum recipients for a multicast packet | YES |
|
||||
| creationTime | integer | Time network was first created | no |
|
||||
| revision | integer | Network config revision counter | no |
|
||||
| authorizedMemberCount | integer | Number of authorized members (for private nets) | no |
|
||||
| activeMemberCount | integer | Number of members that appear to be online | no |
|
||||
| totalMemberCount | integer | Total known members of this network | no |
|
||||
| routes | array[object] | Managed IPv4 and IPv6 routes; see below | YES |
|
||||
| ipAssignmentPools | array[object] | IP auto-assign ranges; see below | YES |
|
||||
| rules | array[object] | Traffic rules; see below | YES |
|
||||
|
||||
Recent changes:
|
||||
|
||||
* The `ipLocalRoutes` field appeared in older versions but is no longer present. Routes will now show up in `routes`.
|
||||
* The `relays` field is gone since network preferred relays are gone. This capability is replaced by VL1 level federation ("federated roots").
|
||||
|
||||
Other important points:
|
||||
|
||||
* Networks without rules won't carry any traffic. If you don't specify any on network creation an "accept anything" rule set will automatically be added.
|
||||
* Managed IP address assignments and IP assignment pools that do not fall within a route configured in `routes` are ignored and won't be used or sent to members.
|
||||
* The default for `private` is `true` and this is probably what you want. Turning `private` off means *anyone* can join your network with only its 16-digit network ID. It's also impossible to de-authorize a member as these networks don't issue or enforce certificates. Such "party line" networks are used for decentralized app backplanes, gaming, and testing but are otherwise not common.
|
||||
|
||||
**Auto-Assign Modes:**
|
||||
|
||||
Auto assign modes (`v4AssignMode` and `v6AssignMode`) contain objects that map assignment modes to booleans.
|
||||
|
||||
For IPv4 the only valid setting is `zt` which, if true, causes IPv4 addresses to be auto-assigned from `ipAssignmentPools` to members that do not have an IPv4 assignment. Note that active bridges are exempt and will not get auto-assigned IPs since this can interfere with bridging. (You can still manually assign one if you want.)
|
||||
|
||||
IPv6 includes this option and two others: `6plane` and `rfc4193`. These assign private IPv6 addresses to each member based on a deterministic assignment scheme that allows members to emulate IPv6 NDP to skip multicast for better performance and scalability. The `rfc4193` mode gives every member a /128 on a /88 network, while `6plane` gives every member a /80 within a /40 network but uses NDP emulation to route *all* IPs under that /80 to its owner. The `6plane` mode is great for use cases like Docker since it allows every member to assign IPv6 addresses within its /80 that just work instantly and globally across the network.
|
||||
|
||||
**IP assignment pool object format:**
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------- | ------------- | ------------------------------------------------- |
|
||||
| ipRangeStart | string | Starting IP address in range |
|
||||
| ipRangeEnd | string | Ending IP address in range (inclusive) |
|
||||
|
||||
Pools are only used if auto-assignment is on for the given address type (IPv4 or IPv6) and if the entire range falls within a managed route.
|
||||
|
||||
IPv6 ranges work just like IPv4 ranges and look like this:
|
||||
|
||||
{
|
||||
"ipRangeStart": "fd00:feed:feed:beef:0000:0000:0000:0000",
|
||||
"ipRangeEnd": "fd00:feed:feed:beef:ffff:ffff:ffff:ffff"
|
||||
}
|
||||
|
||||
(You can POST a shortened-form IPv6 address but the API will always report back un-shortened canonical form addresses.)
|
||||
|
||||
That defines a range within network `fd00:feed:feed:beef::/64` that contains up to 2^64 addresses. If an IPv6 range is large enough, the controller will assign addresses by placing each member's device ID into the address in a manner similar to the RFC4193 and 6PLANE modes. Otherwise it will assign addresses at random.
|
||||
|
||||
**Rule object format:**
|
||||
|
||||
Each rule is actually a sequence of zero or more `MATCH_` entries in the rule array followed by an `ACTION_` entry that describes what to do if all the preceding entries match. An `ACTION_` without any preceding `MATCH_` entries is always taken, so setting a single `ACTION_ACCEPT` rule yields a network that allows all traffic. If no rules are present the default action is `ACTION_DROP`.
|
||||
|
||||
Rules are evaluated in the order in which they appear in the array. There is currently a limit of 256 entries per network. Capabilities should be used if a larger and more complex rule set is needed since they allow rules to be grouped by purpose and only shipped to members that need them.
|
||||
|
||||
Each rule table entry has two common fields.
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------- | ------------- | ------------------------------------------------- |
|
||||
| type | string | Entry type (all caps, case sensitive) |
|
||||
| not | boolean | If true, MATCHes match if they don't match |
|
||||
|
||||
The following fields may or may not be present depending on rule type:
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------- | ------------- | ------------------------------------------------- |
|
||||
| zt | string | 10-digit hex ZeroTier address |
|
||||
| etherType | integer | Ethernet frame type |
|
||||
| mac | string | Hex MAC address (with or without :'s) |
|
||||
| ip | string | IPv4 or IPv6 address |
|
||||
| ipTos | integer | IP type of service |
|
||||
| ipProtocol | integer | IP protocol (e.g. TCP) |
|
||||
| start | integer | Start of an integer range (e.g. port range) |
|
||||
| end | integer | End of an integer range (inclusive) |
|
||||
| id | integer | Tag ID |
|
||||
| value | integer | Tag value or comparison value |
|
||||
| mask | integer | Bit mask (for characteristics flags) |
|
||||
|
||||
The entry types and their additional fields are:
|
||||
|
||||
| Entry type | Description | Fields |
|
||||
| ------------------------------- | ----------------------------------------------------------------- | -------------- |
|
||||
| `ACTION_DROP` | Drop any packets matching this rule | (none) |
|
||||
| `ACTION_ACCEPT` | Accept any packets matching this rule | (none) |
|
||||
| `ACTION_TEE` | Send a copy of this packet to a node (rule parsing continues) | `zt` |
|
||||
| `ACTION_REDIRECT` | Redirect this packet to another node | `zt` |
|
||||
| `ACTION_DEBUG_LOG` | Output debug info on match (if built with rules engine debug) | (none) |
|
||||
| `MATCH_SOURCE_ZEROTIER_ADDRESS` | Match VL1 ZeroTier address of packet sender. | `zt` |
|
||||
| `MATCH_DEST_ZEROTIER_ADDRESS` | Match VL1 ZeroTier address of recipient | `zt` |
|
||||
| `MATCH_ETHERTYPE` | Match Ethernet frame type | `etherType` |
|
||||
| `MATCH_MAC_SOURCE` | Match source Ethernet MAC address | `mac` |
|
||||
| `MATCH_MAC_DEST` | Match destination Ethernet MAC address | `mac` |
|
||||
| `MATCH_IPV4_SOURCE` | Match source IPv4 address | `ip` |
|
||||
| `MATCH_IPV4_DEST` | Match destination IPv4 address | `ip` |
|
||||
| `MATCH_IPV6_SOURCE` | Match source IPv6 address | `ip` |
|
||||
| `MATCH_IPV6_DEST` | Match destination IPv6 address | `ip` |
|
||||
| `MATCH_IP_TOS` | Match IP TOS field | `ipTos` |
|
||||
| `MATCH_IP_PROTOCOL` | Match IP protocol field | `ipProtocol` |
|
||||
| `MATCH_IP_SOURCE_PORT_RANGE` | Match a source IP port range | `start`,`end` |
|
||||
| `MATCH_IP_DEST_PORT_RANGE` | Match a destination IP port range | `start`,`end` |
|
||||
| `MATCH_CHARACTERISTICS` | Match on characteristics flags | `mask`,`value` |
|
||||
| `MATCH_FRAME_SIZE_RANGE` | Match a range of Ethernet frame sizes | `start`,`end` |
|
||||
| `MATCH_TAGS_SAMENESS` | Match if both sides' tags differ by no more than value | `id`,`value` |
|
||||
| `MATCH_TAGS_BITWISE_AND` | Match if both sides' tags AND to value | `id`,`value` |
|
||||
| `MATCH_TAGS_BITWISE_OR` | Match if both sides' tags OR to value | `id`,`value` |
|
||||
| `MATCH_TAGS_BITWISE_XOR` | Match if both sides` tags XOR to value | `id`,`value` |
|
||||
|
||||
Important notes about rules engine behavior:
|
||||
|
||||
* IPv4 and IPv6 IP address rules do not match for frames that are not IPv4 or IPv6 respectively.
|
||||
* `ACTION_DEBUG_LOG` is a no-op on nodes not built with `ZT_RULES_ENGINE_DEBUGGING` enabled (see Network.cpp). If that is enabled nodes will dump a trace of rule evaluation results to *stdout* when this action is encountered but will otherwise keep evaluating rules. This is used for basic "smoke testing" of the rules engine.
|
||||
* Multicast packets and packets destined for bridged devices treated a little differently. They are matched more than once. They are matched at the point of send with a NULL ZeroTier destination address, meaning that `MATCH_DEST_ZEROTIER_ADDRESS` is useless. That's because the true VL1 destination is not yet known. Then they are matched again for each true VL1 destination. On these later subsequent matches TEE actions are ignored and REDIRECT rules are interpreted as DROPs. This prevents multiple TEE or REDIRECT packets from being sent to third party devices.
|
||||
* Rules in capabilities are always matched as if the current device is the sender (inbound == false). A capability specifies sender side rules that can be enforced on both sides.
|
||||
|
||||
#### `/controller/network/<network ID>/member`
|
||||
|
||||
* Purpose: Get a set of all members on this network
|
||||
* Methods: GET
|
||||
* Returns: { object }
|
||||
|
||||
This returns a JSON object containing all member IDs as keys and their `memberRevisionCounter` values as values.
|
||||
|
||||
#### `/controller/network/<network ID>/active`
|
||||
|
||||
* Purpose: Get a set of all active members on this network
|
||||
* Methods: GET
|
||||
* Returns: { object }
|
||||
|
||||
This returns an object containing all currently online members and the most recent `recentLog` entries for their last request.
|
||||
|
||||
#### `/controller/network/<network ID>/member/<address>`
|
||||
|
||||
* Purpose: Create, authorize, or remove a network member
|
||||
* Methods: GET, POST, DELETE
|
||||
* Returns: { object }
|
||||
|
||||
| Field | Type | Description | Writable |
|
||||
| --------------------- | ------------- | ------------------------------------------------- | -------- |
|
||||
| id | string | Member's 10-digit ZeroTier address | no |
|
||||
| address | string | Member's 10-digit ZeroTier address | no |
|
||||
| nwid | string | 16-digit network ID | no |
|
||||
| clock | integer | Current clock, ms since epoch | no |
|
||||
| authorized | boolean | Is member authorized? (for private networks) | YES |
|
||||
| authHistory | array[object] | History of auth changes, latest at end | no |
|
||||
| activeBridge | boolean | Member is able to bridge to other Ethernet nets | YES |
|
||||
| identity | string | Member's public ZeroTier identity (if known) | no |
|
||||
| ipAssignments | array[string] | Managed IP address assignments | YES |
|
||||
| memberRevision | integer | Member revision counter | no |
|
||||
| recentLog | array[object] | Recent member activity log; see below | no |
|
||||
|
||||
Note that managed IP assignments are only used if they fall within a managed route. Otherwise they are ignored.
|
||||
|
||||
**Recent log object format:**
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------- | ------------- | ------------------------------------------------- |
|
||||
| ts | integer | Time of request, ms since epoch |
|
||||
| auth | boolean | Was member authorized? |
|
||||
| authBy | string | How was member authorized? |
|
||||
| vMajor | integer | Client major version or -1 if unknown |
|
||||
| vMinor | integer | Client minor version or -1 if unknown |
|
||||
| vRev | integer | Client revision or -1 if unknown |
|
||||
| vProto | integer | ZeroTier protocol version reported by client |
|
||||
| fromAddr | string | Physical address if known |
|
||||
|
||||
The controller can only know a member's `fromAddr` if it's able to establish a direct path to it. Members behind very restrictive firewalls may not have this information since the controller will be receiving the member's requests by way of a relay. ZeroTier does not back-trace IP paths as packets are relayed since this would add a lot of protocol overhead.
|
||||
320
zto/controller/migrate-sqlite/migrate.js
Normal file
320
zto/controller/migrate-sqlite/migrate.js
Normal file
@@ -0,0 +1,320 @@
|
||||
'use strict';
|
||||
|
||||
var sqlite3 = require('sqlite3').verbose();
|
||||
var fs = require('fs');
|
||||
var async = require('async');
|
||||
|
||||
function blobToIPv4(b)
|
||||
{
|
||||
if (!b)
|
||||
return null;
|
||||
if (b.length !== 16)
|
||||
return null;
|
||||
return b.readUInt8(12).toString()+'.'+b.readUInt8(13).toString()+'.'+b.readUInt8(14).toString()+'.'+b.readUInt8(15).toString();
|
||||
}
|
||||
function blobToIPv6(b)
|
||||
{
|
||||
if (!b)
|
||||
return null;
|
||||
if (b.length !== 16)
|
||||
return null;
|
||||
var s = '';
|
||||
for(var i=0;i<16;++i) {
|
||||
var x = b.readUInt8(i).toString(16);
|
||||
if (x.length === 1)
|
||||
s += '0';
|
||||
s += x;
|
||||
if ((((i+1) & 1) === 0)&&(i !== 15))
|
||||
s += ':';
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
if (process.argv.length !== 4) {
|
||||
console.log('ZeroTier Old Sqlite3 Controller DB Migration Utility');
|
||||
console.log('(c)2017 ZeroTier, Inc. [GPL3]');
|
||||
console.log('');
|
||||
console.log('Usage: node migrate.js </path/to/controller.db> </path/to/controller.d>');
|
||||
console.log('');
|
||||
console.log('The first argument must be the path to the old Sqlite3 controller.db');
|
||||
console.log('file. The second must be the path to the EMPTY controller.d database');
|
||||
console.log('directory for a new (1.1.17 or newer) controller. If this path does');
|
||||
console.log('not exist it will be created.');
|
||||
console.log('');
|
||||
console.log('WARNING: this will ONLY work correctly on a 1.1.14 controller database.');
|
||||
console.log('If your controller is old you should first upgrade to 1.1.14 and run the');
|
||||
console.log('controller so that it will brings its Sqlite3 database up to the latest');
|
||||
console.log('version before running this migration.');
|
||||
console.log('');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var oldDbPath = process.argv[2];
|
||||
var newDbPath = process.argv[3];
|
||||
|
||||
console.log('Starting migrate of "'+oldDbPath+'" to "'+newDbPath+'"...');
|
||||
console.log('');
|
||||
|
||||
var old = new sqlite3.Database(oldDbPath);
|
||||
|
||||
var networks = {};
|
||||
|
||||
var nodeIdentities = {};
|
||||
var networkCount = 0;
|
||||
var memberCount = 0;
|
||||
var routeCount = 0;
|
||||
var ipAssignmentPoolCount = 0;
|
||||
var ipAssignmentCount = 0;
|
||||
var ruleCount = 0;
|
||||
var oldSchemaVersion = -1;
|
||||
|
||||
async.series([function(nextStep) {
|
||||
|
||||
old.each('SELECT v from Config WHERE k = \'schemaVersion\'',function(err,row) {
|
||||
oldSchemaVersion = parseInt(row.v)||-1;
|
||||
},nextStep);
|
||||
|
||||
},function(nextStep) {
|
||||
|
||||
if (oldSchemaVersion !== 4) {
|
||||
console.log('FATAL: this MUST be run on a 1.1.14 controller.db! Upgrade your old');
|
||||
console.log('controller to 1.1.14 first and run it once to bring its DB up to date.');
|
||||
return process.exit(1);
|
||||
}
|
||||
|
||||
console.log('Reading networks...');
|
||||
old.each('SELECT * FROM Network',function(err,row) {
|
||||
if ((typeof row.id === 'string')&&(row.id.length === 16)) {
|
||||
var flags = parseInt(row.flags)||0;
|
||||
networks[row.id] = {
|
||||
id: row.id,
|
||||
nwid: row.id,
|
||||
objtype: 'network',
|
||||
authTokens: [],
|
||||
capabilities: [],
|
||||
creationTime: parseInt(row.creationTime)||0,
|
||||
enableBroadcast: !!row.enableBroadcast,
|
||||
ipAssignmentPools: [],
|
||||
lastModified: Date.now(),
|
||||
multicastLimit: row.multicastLimit||32,
|
||||
name: row.name||'',
|
||||
private: !!row.private,
|
||||
revision: parseInt(row.revision)||1,
|
||||
rules: [{ 'type': 'ACTION_ACCEPT' }], // populated later if there are defined rules, otherwise default is allow all
|
||||
routes: [],
|
||||
v4AssignMode: {
|
||||
'zt': ((flags & 1) !== 0)
|
||||
},
|
||||
v6AssignMode: {
|
||||
'6plane': ((flags & 4) !== 0),
|
||||
'rfc4193': ((flags & 2) !== 0),
|
||||
'zt': ((flags & 8) !== 0)
|
||||
},
|
||||
_members: {} // temporary
|
||||
};
|
||||
++networkCount;
|
||||
//console.log(networks[row.id]);
|
||||
}
|
||||
},nextStep);
|
||||
|
||||
},function(nextStep) {
|
||||
|
||||
console.log(' '+networkCount+' networks.');
|
||||
console.log('Reading network route definitions...');
|
||||
old.each('SELECT * from Route WHERE ipVersion = 4 OR ipVersion = 6',function(err,row) {
|
||||
var network = networks[row.networkId];
|
||||
if (network) {
|
||||
var rt = {
|
||||
target: (((row.ipVersion == 4) ? blobToIPv4(row.target) : blobToIPv6(row.target))+'/'+row.targetNetmaskBits),
|
||||
via: ((row.via) ? ((row.ipVersion == 4) ? blobToIPv4(row.via) : blobToIPv6(row.via)) : null)
|
||||
};
|
||||
network.routes.push(rt);
|
||||
++routeCount;
|
||||
}
|
||||
},nextStep);
|
||||
|
||||
},function(nextStep) {
|
||||
|
||||
console.log(' '+routeCount+' routes in '+networkCount+' networks.');
|
||||
console.log('Reading IP assignment pools...');
|
||||
old.each('SELECT * FROM IpAssignmentPool WHERE ipVersion = 4 OR ipVersion = 6',function(err,row) {
|
||||
var network = networks[row.networkId];
|
||||
if (network) {
|
||||
var p = {
|
||||
ipRangeStart: ((row.ipVersion == 4) ? blobToIPv4(row.ipRangeStart) : blobToIPv6(row.ipRangeStart)),
|
||||
ipRangeEnd: ((row.ipVersion == 4) ? blobToIPv4(row.ipRangeEnd) : blobToIPv6(row.ipRangeEnd))
|
||||
};
|
||||
network.ipAssignmentPools.push(p);
|
||||
++ipAssignmentPoolCount;
|
||||
}
|
||||
},nextStep);
|
||||
|
||||
},function(nextStep) {
|
||||
|
||||
console.log(' '+ipAssignmentPoolCount+' IP assignment pools in '+networkCount+' networks.');
|
||||
console.log('Reading known node identities...');
|
||||
old.each('SELECT * FROM Node',function(err,row) {
|
||||
nodeIdentities[row.id] = row.identity;
|
||||
},nextStep);
|
||||
|
||||
},function(nextStep) {
|
||||
|
||||
console.log(' '+Object.keys(nodeIdentities).length+' known identities.');
|
||||
console.log('Reading network members...');
|
||||
old.each('SELECT * FROM Member',function(err,row) {
|
||||
var network = networks[row.networkId];
|
||||
if (network) {
|
||||
network._members[row.nodeId] = {
|
||||
id: row.nodeId,
|
||||
address: row.nodeId,
|
||||
objtype: 'member',
|
||||
authorized: !!row.authorized,
|
||||
activeBridge: !!row.activeBridge,
|
||||
authHistory: [],
|
||||
capabilities: [],
|
||||
creationTime: 0,
|
||||
identity: nodeIdentities[row.nodeId]||null,
|
||||
ipAssignments: [],
|
||||
lastAuthorizedTime: (row.authorized) ? Date.now() : 0,
|
||||
lastDeauthorizedTime: (row.authorized) ? 0 : Date.now(),
|
||||
lastModified: Date.now(),
|
||||
lastRequestMetaData: '',
|
||||
noAutoAssignIps: false,
|
||||
nwid: row.networkId,
|
||||
revision: parseInt(row.memberRevision)||1,
|
||||
tags: [],
|
||||
recentLog: []
|
||||
};
|
||||
++memberCount;
|
||||
//console.log(network._members[row.nodeId]);
|
||||
}
|
||||
},nextStep);
|
||||
|
||||
},function(nextStep) {
|
||||
|
||||
console.log(' '+memberCount+' members of '+networkCount+' networks.');
|
||||
console.log('Reading static IP assignments...');
|
||||
old.each('SELECT * FROM IpAssignment WHERE ipVersion = 4 OR ipVersion = 6',function(err,row) {
|
||||
var network = networks[row.networkId];
|
||||
if (network) {
|
||||
var member = network._members[row.nodeId];
|
||||
if ((member)&&((member.authorized)||(!network['private']))) { // don't mirror assignments to unauthorized members to avoid conflicts
|
||||
if (row.ipVersion == 4) {
|
||||
member.ipAssignments.push(blobToIPv4(row.ip));
|
||||
++ipAssignmentCount;
|
||||
} else if (row.ipVersion == 6) {
|
||||
member.ipAssignments.push(blobToIPv6(row.ip));
|
||||
++ipAssignmentCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
},nextStep);
|
||||
|
||||
},function(nextStep) {
|
||||
|
||||
// Old versions only supported Ethertype whitelisting, so that's
|
||||
// all we mirror forward. The other fields were always unused.
|
||||
|
||||
console.log(' '+ipAssignmentCount+' IP assignments for '+memberCount+' authorized members of '+networkCount+' networks.');
|
||||
console.log('Reading allowed Ethernet types (old basic rules)...');
|
||||
var etherTypesByNetwork = {};
|
||||
old.each('SELECT DISTINCT networkId,ruleNo,etherType FROM Rule WHERE "action" = \'accept\'',function(err,row) {
|
||||
if (row.networkId in networks) {
|
||||
var et = parseInt(row.etherType)||0;
|
||||
var ets = etherTypesByNetwork[row.networkId];
|
||||
if (!ets)
|
||||
etherTypesByNetwork[row.networkId] = [ et ];
|
||||
else ets.push(et);
|
||||
}
|
||||
},function(err) {
|
||||
if (err) return nextStep(err);
|
||||
for(var nwid in etherTypesByNetwork) {
|
||||
var ets = etherTypesByNetwork[nwid].sort();
|
||||
var network = networks[nwid];
|
||||
if (network) {
|
||||
var rules = [];
|
||||
if (ets.indexOf(0) >= 0) {
|
||||
// If 0 is in the list, all Ethernet types are allowed so we accept all.
|
||||
rules.push({ 'type': 'ACTION_ACCEPT' });
|
||||
} else {
|
||||
// Otherwise we whitelist.
|
||||
for(var i=0;i<ets.length;++i) {
|
||||
rules.push({
|
||||
'etherType': ets[i],
|
||||
'not': true,
|
||||
'or': false,
|
||||
'type': 'MATCH_ETHERTYPE'
|
||||
});
|
||||
}
|
||||
rules.push({ 'type': 'ACTION_DROP' });
|
||||
rules.push({ 'type': 'ACTION_ACCEPT' });
|
||||
}
|
||||
network.rules = rules;
|
||||
++ruleCount;
|
||||
}
|
||||
}
|
||||
return nextStep(null);
|
||||
});
|
||||
|
||||
}],function(err) {
|
||||
|
||||
if (err) {
|
||||
console.log('FATAL: '+err.toString());
|
||||
return process.exit(1);
|
||||
}
|
||||
|
||||
console.log(' '+ruleCount+' ethernet type whitelists converted to new format rules.');
|
||||
old.close();
|
||||
console.log('Done reading and converting Sqlite3 database! Writing JSONDB files...');
|
||||
|
||||
try {
|
||||
fs.mkdirSync(newDbPath,0o700);
|
||||
} catch (e) {}
|
||||
var nwBase = newDbPath+'/network';
|
||||
try {
|
||||
fs.mkdirSync(nwBase,0o700);
|
||||
} catch (e) {}
|
||||
nwBase = nwBase + '/';
|
||||
var nwids = Object.keys(networks).sort();
|
||||
var fileCount = 0;
|
||||
for(var ni=0;ni<nwids.length;++ni) {
|
||||
var network = networks[nwids[ni]];
|
||||
|
||||
var mids = Object.keys(network._members).sort();
|
||||
if (mids.length > 0) {
|
||||
try {
|
||||
fs.mkdirSync(nwBase+network.id);
|
||||
} catch (e) {}
|
||||
var mbase = nwBase+network.id+'/member';
|
||||
try {
|
||||
fs.mkdirSync(mbase,0o700);
|
||||
} catch (e) {}
|
||||
mbase = mbase + '/';
|
||||
|
||||
for(var mi=0;mi<mids.length;++mi) {
|
||||
var member = network._members[mids[mi]];
|
||||
fs.writeFileSync(mbase+member.id+'.json',JSON.stringify(member,null,1),{ mode: 0o600 });
|
||||
++fileCount;
|
||||
//console.log(mbase+member.id+'.json');
|
||||
}
|
||||
}
|
||||
|
||||
delete network._members; // temporary field, not part of actual JSONDB, so don't write
|
||||
fs.writeFileSync(nwBase+network.id+'.json',JSON.stringify(network,null,1),{ mode: 0o600 });
|
||||
++fileCount;
|
||||
//console.log(nwBase+network.id+'.json');
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('SUCCESS! Wrote '+fileCount+' JSONDB files.');
|
||||
|
||||
console.log('');
|
||||
console.log('You should still inspect the new DB before going live. Also be sure');
|
||||
console.log('to "chown -R" and "chgrp -R" the new DB to the user and group under');
|
||||
console.log('which the ZeroTier One instance acting as controller will be running.');
|
||||
console.log('The controller must be able to read and write the DB, of course.');
|
||||
console.log('');
|
||||
console.log('Have fun!');
|
||||
|
||||
return process.exit(0);
|
||||
});
|
||||
15
zto/controller/migrate-sqlite/package.json
Normal file
15
zto/controller/migrate-sqlite/package.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "migrate-sqlite",
|
||||
"version": "1.0.0",
|
||||
"description": "Migrate old SQLite to new JSON filesystem DB for ZeroTier network controller",
|
||||
"main": "migrate.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "Adam Ierymenko <adam.ierymenko@zerotier.com>",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"async": "^2.1.4",
|
||||
"sqlite3": "^3.1.8"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user