Integrate moon concept into http config bus, and clean up that code quite a bit.

This commit is contained in:
Adam Ierymenko 2017-02-13 14:27:08 -08:00
parent c95bae2d73
commit 4b11566505
7 changed files with 265 additions and 360 deletions

View file

@ -442,16 +442,6 @@ typedef struct
*/ */
uint64_t address; uint64_t address;
/**
* Current world ID
*/
uint64_t worldId;
/**
* Current world revision/timestamp
*/
uint64_t worldTimestamp;
/** /**
* Public identity in string-serialized form (safe to send to others) * Public identity in string-serialized form (safe to send to others)
* *

View file

@ -362,8 +362,6 @@ uint64_t Node::address() const
void Node::status(ZT_NodeStatus *status) const void Node::status(ZT_NodeStatus *status) const
{ {
status->address = RR->identity.address().toInt(); status->address = RR->identity.address().toInt();
status->worldId = RR->topology->planetWorldId();
status->worldTimestamp = RR->topology->planetWorldTimestamp();
status->publicIdentity = RR->publicIdentityStr.c_str(); status->publicIdentity = RR->publicIdentityStr.c_str();
status->secretIdentity = RR->secretIdentityStr.c_str(); status->secretIdentity = RR->secretIdentityStr.c_str();
status->online = _online ? 1 : 0; status->online = _online ? 1 : 0;
@ -714,6 +712,16 @@ void Node::setTrustedPaths(const struct sockaddr_storage *networks,const uint64_
RR->topology->setTrustedPaths(reinterpret_cast<const InetAddress *>(networks),ids,count); RR->topology->setTrustedPaths(reinterpret_cast<const InetAddress *>(networks),ids,count);
} }
World Node::planet() const
{
return RR->topology->planet();
}
std::vector<World> Node::moons() const
{
return RR->topology->moons();
}
void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig) void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
{ {
if (destination == RR->identity.address()) { if (destination == RR->identity.address()) {

View file

@ -24,6 +24,7 @@
#include <string.h> #include <string.h>
#include <map> #include <map>
#include <vector>
#include "Constants.hpp" #include "Constants.hpp"
@ -54,6 +55,8 @@
namespace ZeroTier { namespace ZeroTier {
class World;
/** /**
* Implementation of Node object as defined in CAPI * Implementation of Node object as defined in CAPI
* *
@ -210,6 +213,9 @@ public:
void postCircuitTestReport(const ZT_CircuitTestReport *report); void postCircuitTestReport(const ZT_CircuitTestReport *report);
void setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count); void setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count);
World planet() const;
std::vector<World> moons() const;
/** /**
* Register that we are expecting a reply to a packet ID * Register that we are expecting a reply to a packet ID
* *

View file

@ -135,6 +135,16 @@ public:
*/ */
inline uint64_t timestamp() const { return _ts; } inline uint64_t timestamp() const { return _ts; }
/**
* @return C25519 signature
*/
inline const C25519::Signature &signature() const { return _signature; }
/**
* @return Public key that must sign next update
*/
inline const C25519::Public &updatesMustBeSignedBy() const { return _updatesMustBeSignedBy; }
/** /**
* Check whether a world update should replace this one * Check whether a world update should replace this one
* *

View file

@ -35,77 +35,17 @@
#include "../node/InetAddress.hpp" #include "../node/InetAddress.hpp"
#include "../node/Node.hpp" #include "../node/Node.hpp"
#include "../node/Utils.hpp" #include "../node/Utils.hpp"
#include "../node/World.hpp"
#include "../osdep/OSUtils.hpp" #include "../osdep/OSUtils.hpp"
namespace ZeroTier { namespace ZeroTier {
static std::string _jsonEscape(const char *s) namespace {
{
std::string buf;
for(const char *p=s;(*p);++p) {
switch(*p) {
case '\t': buf.append("\\t"); break;
case '\b': buf.append("\\b"); break;
case '\r': buf.append("\\r"); break;
case '\n': buf.append("\\n"); break;
case '\f': buf.append("\\f"); break;
case '"': buf.append("\\\""); break;
case '\\': buf.append("\\\\"); break;
case '/': buf.append("\\/"); break;
default: buf.push_back(*p); break;
}
}
return buf;
}
static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); }
static std::string _jsonEnumerate(const struct sockaddr_storage *ss,unsigned int count) static void _networkToJson(nlohmann::json &nj,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
{ {
std::string buf; char tmp[256];
buf.push_back('[');
for(unsigned int i=0;i<count;++i) {
if (i > 0)
buf.push_back(',');
buf.push_back('"');
buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(ss[i]))->toString()));
buf.push_back('"');
}
buf.push_back(']');
return buf;
}
static std::string _jsonEnumerate(const ZT_VirtualNetworkRoute *routes,unsigned int count)
{
std::string buf;
buf.push_back('[');
for(unsigned int i=0;i<count;++i) {
if (i > 0)
buf.push_back(',');
buf.append("{\"target\":\"");
buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(routes[i].target))->toString()));
buf.append("\",\"via\":");
if (routes[i].via.ss_family == routes[i].target.ss_family) {
buf.push_back('"');
buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(routes[i].via))->toIpString()));
buf.append("\",");
} else buf.append("null,");
char tmp[1024];
Utils::snprintf(tmp,sizeof(tmp),"\"flags\":%u,\"metric\":%u}",(unsigned int)routes[i].flags,(unsigned int)routes[i].metric);
buf.append(tmp);
}
buf.push_back(']');
return buf;
}
static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
{
char json[4096];
char prefix[32];
if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
return;
for(unsigned int i=0;i<depth;++i)
prefix[i] = '\t';
prefix[depth] = '\0';
const char *nstatus = "",*ntype = ""; const char *nstatus = "",*ntype = "";
switch(nc->status) { switch(nc->status) {
@ -121,107 +61,48 @@ static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_VirtualNetw
case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break; case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
} }
std::string allowManaged = (localSettings.allowManaged) ? "true" : "false"; Utils::snprintf(tmp,sizeof(tmp),"%.16llx",nc->nwid);
if (localSettings.allowManagedWhitelist.size() != 0) { nj["id"] = tmp;
allowManaged = ""; nj["nwid"] = tmp;
for (InetAddress address : localSettings.allowManagedWhitelist) { Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)((nc->mac >> 40) & 0xff),(unsigned int)((nc->mac >> 32) & 0xff),(unsigned int)((nc->mac >> 24) & 0xff),(unsigned int)((nc->mac >> 16) & 0xff),(unsigned int)((nc->mac >> 8) & 0xff),(unsigned int)(nc->mac & 0xff));
if (allowManaged.size() != 0) allowManaged += ','; nj["mac"] = tmp;
allowManaged += address.toIpString() + "/" + std::to_string(address.netmaskBits()); nj["name"] = nc->name;
} nj["status"] = nstatus;
} nj["type"] = ntype;
nj["mtu"] = nc->mtu;
nj["dhcp"] = (bool)(nc->dhcp == 0);
nj["bridge"] = (bool)(nc->bridge == 0);
nj["broadcastEnabled"] = (bool)(nc->broadcastEnabled == 0);
nj["portError"] = nc->portError;
nj["netconfRevision"] = nc->netconfRevision;
nj["portDeviceName"] = portDeviceName;
nj["allowManaged"] = localSettings.allowManaged;
nj["allowGlobal"] = localSettings.allowGlobal;
nj["allowDefault"] = localSettings.allowDefault;
Utils::snprintf(json,sizeof(json), nlohmann::json aa = nlohmann::json::array();
"%s{\n" for(unsigned int i=0;i<nc->assignedAddressCount;++i) {
"%s\t\"id\": \"%.16llx\",\n" aa.push_back(reinterpret_cast<const InetAddress *>(&(nc->assignedAddresses[i]))->toString());
"%s\t\"nwid\": \"%.16llx\",\n" }
"%s\t\"mac\": \"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",\n" nj["assignedAddresses"] = aa;
"%s\t\"name\": \"%s\",\n"
"%s\t\"status\": \"%s\",\n" nlohmann::json ra = nlohmann::json::array();
"%s\t\"type\": \"%s\",\n" for(unsigned int i=0;i<nc->routeCount;++i) {
"%s\t\"mtu\": %u,\n" nlohmann::json rj;
"%s\t\"dhcp\": %s,\n" rj["target"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].target))->toString();
"%s\t\"bridge\": %s,\n" if (nc->routes[i].via.ss_family == nc->routes[i].target.ss_family)
"%s\t\"broadcastEnabled\": %s,\n" rj["via"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].via))->toIpString();
"%s\t\"portError\": %d,\n" else rj["via"] = nlohmann::json();
"%s\t\"netconfRevision\": %lu,\n" rj["flags"] = (int)nc->routes[i].flags;
"%s\t\"assignedAddresses\": %s,\n" rj["metric"] = (int)nc->routes[i].metric;
"%s\t\"routes\": %s,\n" ra.push_back(rj);
"%s\t\"portDeviceName\": \"%s\",\n" }
"%s\t\"allowManaged\": %s,\n" nj["routes"] = ra;
"%s\t\"allowGlobal\": %s,\n"
"%s\t\"allowDefault\": %s\n"
"%s}",
prefix,
prefix,nc->nwid,
prefix,nc->nwid,
prefix,(unsigned int)((nc->mac >> 40) & 0xff),(unsigned int)((nc->mac >> 32) & 0xff),(unsigned int)((nc->mac >> 24) & 0xff),(unsigned int)((nc->mac >> 16) & 0xff),(unsigned int)((nc->mac >> 8) & 0xff),(unsigned int)(nc->mac & 0xff),
prefix,_jsonEscape(nc->name).c_str(),
prefix,nstatus,
prefix,ntype,
prefix,nc->mtu,
prefix,(nc->dhcp == 0) ? "false" : "true",
prefix,(nc->bridge == 0) ? "false" : "true",
prefix,(nc->broadcastEnabled == 0) ? "false" : "true",
prefix,nc->portError,
prefix,nc->netconfRevision,
prefix,_jsonEnumerate(nc->assignedAddresses,nc->assignedAddressCount).c_str(),
prefix,_jsonEnumerate(nc->routes,nc->routeCount).c_str(),
prefix,_jsonEscape(portDeviceName).c_str(),
prefix,allowManaged.c_str(),
prefix,(localSettings.allowGlobal) ? "true" : "false",
prefix,(localSettings.allowDefault) ? "true" : "false",
prefix);
buf.append(json);
} }
static std::string _jsonEnumerate(unsigned int depth,const ZT_PeerPhysicalPath *pp,unsigned int count) static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer)
{ {
char json[2048]; char tmp[256];
char prefix[32];
if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
return std::string();
for(unsigned int i=0;i<depth;++i)
prefix[i] = '\t';
prefix[depth] = '\0';
std::string buf;
for(unsigned int i=0;i<count;++i) {
if (i > 0)
buf.push_back(',');
Utils::snprintf(json,sizeof(json),
"{\n"
"%s\t\"address\": \"%s\",\n"
"%s\t\"lastSend\": %llu,\n"
"%s\t\"lastReceive\": %llu,\n"
"%s\t\"active\": %s,\n"
"%s\t\"expired\": %s,\n"
"%s\t\"preferred\": %s,\n"
"%s\t\"trustedPathId\": %llu\n"
"%s}",
prefix,_jsonEscape(reinterpret_cast<const InetAddress *>(&(pp[i].address))->toString()).c_str(),
prefix,pp[i].lastSend,
prefix,pp[i].lastReceive,
prefix,(pp[i].expired != 0) ? "false" : "true",
prefix,(pp[i].expired == 0) ? "false" : "true",
prefix,(pp[i].preferred == 0) ? "false" : "true",
prefix,pp[i].trustedPathId,
prefix);
buf.append(json);
}
return buf;
}
static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_Peer *peer)
{
char json[2048];
char prefix[32];
if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
return;
for(unsigned int i=0;i<depth;++i)
prefix[i] = '\t';
prefix[depth] = '\0';
const char *prole = ""; const char *prole = "";
switch(peer->role) { switch(peer->role) {
@ -230,39 +111,57 @@ static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_Peer *peer)
case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break; case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
} }
Utils::snprintf(json,sizeof(json), Utils::snprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
"%s{\n" pj["address"] = tmp;
"%s\t\"address\": \"%.10llx\",\n" pj["versionMajor"] = peer->versionMajor;
"%s\t\"versionMajor\": %d,\n" pj["versionMinor"] = peer->versionMinor;
"%s\t\"versionMinor\": %d,\n" pj["versionRev"] = peer->versionRev;
"%s\t\"versionRev\": %d,\n" Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev);
"%s\t\"version\": \"%d.%d.%d\",\n" pj["version"] = tmp;
"%s\t\"latency\": %u,\n" pj["latency"] = peer->latency;
"%s\t\"role\": \"%s\",\n" pj["role"] = prole;
"%s\t\"paths\": [%s]\n"
"%s}", nlohmann::json pa = nlohmann::json::array();
prefix, for(unsigned int i=0;i<peer->pathCount;++i) {
prefix,peer->address, nlohmann::json j;
prefix,peer->versionMajor, j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString();
prefix,peer->versionMinor, j["lastSend"] = peer->paths[i].lastSend;
prefix,peer->versionRev, j["lastReceive"] = peer->paths[i].lastReceive;
prefix,peer->versionMajor,peer->versionMinor,peer->versionRev, j["active"] = (bool)(peer->paths[i].expired != 0);
prefix,peer->latency, j["expired"] = (bool)(peer->paths[i].expired == 0);
prefix,prole, j["preferred"] = (bool)(peer->paths[i].preferred == 0);
prefix,_jsonEnumerate(depth+1,peer->paths,peer->pathCount).c_str(), j["trustedPathId"] = peer->paths[i].trustedPathId;
prefix); pa.push_back(j);
buf.append(json); }
pj["paths"] = pa;
} }
ControlPlane::ControlPlane(OneService *svc,Node *n,const char *uiStaticPath) : static void _moonToJson(nlohmann::json &mj,const World &world)
{
mj["id"] = world.id();
mj["timestamp"] = world.timestamp();
mj["signature"] = Utils::hex(world.signature().data,world.signature().size());
mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,world.updatesMustBeSignedBy().size());
nlohmann::json ra = nlohmann::json::array();
for(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {
nlohmann::json rj;
rj["identity"] = r->identity.toString(false);
nlohmann::json eps = nlohmann::json::array();
for(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)
eps.push_back(a->toString());
rj["stableEndpoints"] = eps;
ra.push_back(rj);
}
mj["roots"] = ra;
mj["active"] = true;
}
} // anonymous namespace
ControlPlane::ControlPlane(OneService *svc,Node *n) :
_svc(svc), _svc(svc),
_node(n), _node(n),
_controller((EmbeddedNetworkController *)0), _controller((EmbeddedNetworkController *)0)
_uiStaticPath((uiStaticPath) ? uiStaticPath : "")
{
}
ControlPlane::~ControlPlane()
{ {
} }
@ -275,10 +174,12 @@ unsigned int ControlPlane::handleRequest(
std::string &responseBody, std::string &responseBody,
std::string &responseContentType) std::string &responseContentType)
{ {
char json[8194]; char tmp[256];
unsigned int scode = 404; unsigned int scode = 404;
nlohmann::json res;
std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","","")); std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
std::map<std::string,std::string> urlArgs; std::map<std::string,std::string> urlArgs;
Mutex::Lock _l(_lock); Mutex::Lock _l(_lock);
/* Note: this is kind of restricted in what it'll take. It does not support /* Note: this is kind of restricted in what it'll take. It does not support
@ -298,8 +199,6 @@ unsigned int ControlPlane::handleRequest(
else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1); else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
} }
} }
} else {
ps.push_back(std::string("index.html"));
} }
bool isAuth = false; bool isAuth = false;
@ -315,148 +214,113 @@ unsigned int ControlPlane::handleRequest(
} }
if (httpMethod == HTTP_GET) { if (httpMethod == HTTP_GET) {
if (isAuth) {
std::string ext;
std::size_t dotIdx = ps[0].find_last_of('.');
if (dotIdx != std::string::npos)
ext = ps[0].substr(dotIdx);
if ((ps.size() == 1)&&(ext.length() >= 2)&&(ext[0] == '.')) {
/* Static web pages can be served without authentication to enable a simple web
* UI. This is still only allowed from approved IP addresses. Anything with a
* dot in the first path element (e.g. foo.html) is considered a static page,
* as nothing in the API is so named. */
if (_uiStaticPath.length() > 0) {
if (ext == ".html")
responseContentType = "text/html";
else if (ext == ".js")
responseContentType = "application/javascript";
else if (ext == ".jsx")
responseContentType = "text/jsx";
else if (ext == ".json")
responseContentType = "application/json";
else if (ext == ".css")
responseContentType = "text/css";
else if (ext == ".png")
responseContentType = "image/png";
else if (ext == ".jpg")
responseContentType = "image/jpeg";
else if (ext == ".gif")
responseContentType = "image/gif";
else if (ext == ".txt")
responseContentType = "text/plain";
else if (ext == ".xml")
responseContentType = "text/xml";
else if (ext == ".svg")
responseContentType = "image/svg+xml";
else responseContentType = "application/octet-stream";
scode = OSUtils::readFile((_uiStaticPath + ZT_PATH_SEPARATOR_S + ps[0]).c_str(),responseBody) ? 200 : 404;
} else {
scode = 404;
}
} else if (isAuth) {
/* Things that require authentication -- a.k.a. everything but static web app pages. */
if (ps[0] == "status") { if (ps[0] == "status") {
responseContentType = "application/json";
ZT_NodeStatus status; ZT_NodeStatus status;
_node->status(&status); _node->status(&status);
std::string clusterJson; Utils::snprintf(tmp,sizeof(tmp),"%.10llx",status.address);
#ifdef ZT_ENABLE_CLUSTER res["address"] = tmp;
{ res["publicIdentity"] = status.publicIdentity;
ZT_ClusterStatus cs; res["online"] = (bool)status.online;
_node->clusterStatus(&cs); res["tcpFallbackActive"] = _svc->tcpFallbackActive();
res["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
res["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
res["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
res["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
res["version"] = tmp;
res["clock"] = OSUtils::now();
if (cs.clusterSize >= 1) { World planet(_node->planet());
char t[1024]; res["planetWorldId"] = planet.id();
Utils::snprintf(t,sizeof(t),"{\n\t\t\"myId\": %u,\n\t\t\"clusterSize\": %u,\n\t\t\"members\": [",cs.myId,cs.clusterSize); res["planetWorldTimestamp"] = planet.timestamp();
clusterJson.append(t);
for(unsigned int i=0;i<cs.clusterSize;++i) { #ifdef ZT_ENABLE_CLUSTER
Utils::snprintf(t,sizeof(t),"%s\t\t\t{\n\t\t\t\t\"id\": %u,\n\t\t\t\t\"msSinceLastHeartbeat\": %u,\n\t\t\t\t\"alive\": %s,\n\t\t\t\t\"x\": %d,\n\t\t\t\t\"y\": %d,\n\t\t\t\t\"z\": %d,\n\t\t\t\t\"load\": %llu,\n\t\t\t\t\"peers\": %llu\n\t\t\t}", nlohmann::json cj;
((i == 0) ? "\n" : ",\n"), ZT_ClusterStatus cs;
cs.members[i].id, _node->clusterStatus(&cs);
cs.members[i].msSinceLastHeartbeat, if (cs.clusterSize >= 1) {
(cs.members[i].alive != 0) ? "true" : "false", nlohmann::json cja = nlohmann::json::array();
cs.members[i].x, for(unsigned int i=0;i<cs.clusterSize;++i) {
cs.members[i].y, nlohmann::json cjm;
cs.members[i].z, cjm["id"] = (int)cs.members[i].id;
cs.members[i].load, cjm["msSinceLastHeartbeat"] = cs.members[i].msSinceLastHeartbeat;
cs.members[i].peers); cjm["alive"] = (bool)(cs.members[i].alive != 0);
clusterJson.append(t); cjm["x"] = cs.members[i].x;
} cjm["y"] = cs.members[i].y;
clusterJson.append(" ]\n\t\t}"); cjm["z"] = cs.members[i].z;
cjm["load"] = cs.members[i].load;
cjm["peers"] = cs.members[i].peers;
cja.push_back(cjm);
} }
cj["members"] = cja;
cj["myId"] = (int)cs.myId;
cj["clusterSize"] = cs.clusterSize;
} }
res["cluster"] = cj;
#else
res["cluster"] = nlohmann::json();
#endif #endif
Utils::snprintf(json,sizeof(json),
"{\n"
"\t\"address\": \"%.10llx\",\n"
"\t\"publicIdentity\": \"%s\",\n"
"\t\"worldId\": %llu,\n"
"\t\"worldTimestamp\": %llu,\n"
"\t\"online\": %s,\n"
"\t\"tcpFallbackActive\": %s,\n"
"\t\"versionMajor\": %d,\n"
"\t\"versionMinor\": %d,\n"
"\t\"versionRev\": %d,\n"
"\t\"version\": \"%d.%d.%d\",\n"
"\t\"clock\": %llu,\n"
"\t\"cluster\": %s\n"
"}\n",
status.address,
status.publicIdentity,
status.worldId,
status.worldTimestamp,
(status.online) ? "true" : "false",
(_svc->tcpFallbackActive()) ? "true" : "false",
ZEROTIER_ONE_VERSION_MAJOR,
ZEROTIER_ONE_VERSION_MINOR,
ZEROTIER_ONE_VERSION_REVISION,
ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION,
(unsigned long long)OSUtils::now(),
((clusterJson.length() > 0) ? clusterJson.c_str() : "null"));
responseBody = json;
scode = 200;
} else if (ps[0] == "settings") {
responseContentType = "application/json";
responseBody = "{}"; // TODO
scode = 200; scode = 200;
} else if (ps[0] == "moon") {
std::vector<World> moons(_node->moons());
if (ps.size() == 1) {
// Return [array] of all moons
res = nlohmann::json::array();
for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
nlohmann::json mj;
_moonToJson(mj,*m);
res.push_back(mj);
}
scode = 2;;
} else {
// Return a single moon by ID
const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
if (m->id() == id) {
_moonToJson(res,*m);
scode = 200;
break;
}
}
}
} else if (ps[0] == "network") { } else if (ps[0] == "network") {
ZT_VirtualNetworkList *nws = _node->networks(); ZT_VirtualNetworkList *nws = _node->networks();
if (nws) { if (nws) {
if (ps.size() == 1) { if (ps.size() == 1) {
// Return [array] of all networks // Return [array] of all networks
responseContentType = "application/json";
responseBody = "[\n"; res = nlohmann::json::array();
for(unsigned long i=0;i<nws->networkCount;++i) { for(unsigned long i=0;i<nws->networkCount;++i) {
if (i > 0)
responseBody.append(",");
OneService::NetworkSettings localSettings; OneService::NetworkSettings localSettings;
_svc->getNetworkSettings(nws->networks[i].nwid,localSettings); _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
_jsonAppend(1,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings); nlohmann::json nj;
_networkToJson(nj,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
res.push_back(nj);
} }
responseBody.append("\n]\n");
scode = 200; scode = 200;
} else if (ps.size() == 2) { } else if (ps.size() == 2) {
// Return a single network by ID or 404 if not found // Return a single network by ID or 404 if not found
uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
const uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
for(unsigned long i=0;i<nws->networkCount;++i) { for(unsigned long i=0;i<nws->networkCount;++i) {
if (nws->networks[i].nwid == wantnw) { if (nws->networks[i].nwid == wantnw) {
responseContentType = "application/json";
OneService::NetworkSettings localSettings; OneService::NetworkSettings localSettings;
_svc->getNetworkSettings(nws->networks[i].nwid,localSettings); _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
_jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings); _networkToJson(res,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
responseBody.push_back('\n');
scode = 200; scode = 200;
break; break;
} }
} }
} // else 404
} else scode = 404;
_node->freeQueryResult((void *)nws); _node->freeQueryResult((void *)nws);
} else scode = 500; } else scode = 500;
} else if (ps[0] == "peer") { } else if (ps[0] == "peer") {
@ -464,54 +328,78 @@ unsigned int ControlPlane::handleRequest(
if (pl) { if (pl) {
if (ps.size() == 1) { if (ps.size() == 1) {
// Return [array] of all peers // Return [array] of all peers
responseContentType = "application/json";
responseBody = "[\n"; res = nlohmann::json::array();
for(unsigned long i=0;i<pl->peerCount;++i) { for(unsigned long i=0;i<pl->peerCount;++i) {
if (i > 0) nlohmann::json pj;
responseBody.append(",\n"); _peerToJson(pj,&(pl->peers[i]));
_jsonAppend(1,responseBody,&(pl->peers[i])); res.push_back(pj);
} }
responseBody.append("\n]\n");
scode = 200; scode = 200;
} else if (ps.size() == 2) { } else if (ps.size() == 2) {
// Return a single peer by ID or 404 if not found // Return a single peer by ID or 404 if not found
uint64_t wantp = Utils::hexStrToU64(ps[1].c_str()); uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
for(unsigned long i=0;i<pl->peerCount;++i) { for(unsigned long i=0;i<pl->peerCount;++i) {
if (pl->peers[i].address == wantp) { if (pl->peers[i].address == wantp) {
responseContentType = "application/json"; _peerToJson(res,&(pl->peers[i]));
_jsonAppend(0,responseBody,&(pl->peers[i]));
responseBody.push_back('\n');
scode = 200; scode = 200;
break; break;
} }
} }
} // else 404
} else scode = 404;
_node->freeQueryResult((void *)pl); _node->freeQueryResult((void *)pl);
} else scode = 500; } else scode = 500;
} else if (ps[0] == "newIdentity") {
// Return a newly generated ZeroTier identity -- this is primarily for debugging
// and testing to make it easy for automated test scripts to generate test IDs.
Identity newid;
newid.generate();
responseBody = newid.toString(true);
responseContentType = "text/plain";
scode = 200;
} else { } else {
if (_controller) if (_controller) {
scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType); scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
else scode = 404; } else scode = 404;
} }
} else scode = 401; // isAuth == false } else scode = 401; // isAuth == false
} else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) { } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
if (isAuth) { if (isAuth) {
if (ps[0] == "settings") { if (ps[0] == "moon") {
// TODO if (ps.size() == 2) {
uint64_t seed = 0;
try {
nlohmann::json j(OSUtils::jsonParse(body));
if (j.is_object()) {
seed = OSUtils::jsonInt(j["seed"],0);
}
} catch ( ... ) {
// discard invalid JSON
}
std::vector<World> moons(_node->moons());
const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
if (m->id() == id) {
_moonToJson(res,*m);
scode = 200;
break;
}
}
if ((scode != 200)&&(seed != 0)) {
res["seed"] = seed;
res["id"] = id;
res["roots"] = nlohmann::json::array();
res["timestamp"] = 0;
res["signature"] = nlohmann::json();
res["updatesMustBeSignedBy"] = nlohmann::json();
res["active"] = false;
_node->orbit(id,seed);
}
} else scode = 404;
} else if (ps[0] == "network") { } else if (ps[0] == "network") {
if (ps.size() == 2) { if (ps.size() == 2) {
uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str()); uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
_node->join(wantnw,(void *)0); // does nothing if we are a member _node->join(wantnw,(void *)0); // does nothing if we are a member
ZT_VirtualNetworkList *nws = _node->networks(); ZT_VirtualNetworkList *nws = _node->networks();
@ -536,17 +424,16 @@ unsigned int ControlPlane::handleRequest(
} }
_svc->setNetworkSettings(nws->networks[i].nwid,localSettings); _svc->setNetworkSettings(nws->networks[i].nwid,localSettings);
_networkToJson(res,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
responseContentType = "application/json";
_jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
responseBody.push_back('\n');
scode = 200; scode = 200;
break; break;
} }
} }
_node->freeQueryResult((void *)nws); _node->freeQueryResult((void *)nws);
} else scode = 500; } else scode = 500;
}
} else scode = 404;
} else { } else {
if (_controller) if (_controller)
scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType); scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
@ -554,12 +441,16 @@ unsigned int ControlPlane::handleRequest(
} }
} else scode = 401; // isAuth == false } else scode = 401; // isAuth == false
} else if (httpMethod == HTTP_DELETE) { } else if (httpMethod == HTTP_DELETE) {
if (isAuth) { if (isAuth) {
if (ps[0] == "network") { if (ps[0] == "moon") {
if (ps.size() == 2) {
_node->deorbit(Utils::hexStrToU64(ps[1].c_str()));
res["result"] = true;
scode = 200;
} // else 404
} else if (ps[0] == "network") {
ZT_VirtualNetworkList *nws = _node->networks(); ZT_VirtualNetworkList *nws = _node->networks();
if (nws) { if (nws) {
if (ps.size() == 2) { if (ps.size() == 2) {
@ -567,8 +458,7 @@ unsigned int ControlPlane::handleRequest(
for(unsigned long i=0;i<nws->networkCount;++i) { for(unsigned long i=0;i<nws->networkCount;++i) {
if (nws->networks[i].nwid == wantnw) { if (nws->networks[i].nwid == wantnw) {
_node->leave(wantnw,(void **)0); _node->leave(wantnw,(void **)0);
responseBody = "true"; res["result"] = true;
responseContentType = "application/json";
scode = 200; scode = 200;
break; break;
} }
@ -582,13 +472,16 @@ unsigned int ControlPlane::handleRequest(
else scode = 404; else scode = 404;
} }
} else { } else scode = 401; // isAuth = false
scode = 401; // isAuth = false
}
} else { } else {
scode = 400; scode = 400;
responseBody = "Method not supported."; }
if (responseBody.length() == 0) {
if ((res.is_object())||(res.is_array()))
responseBody = OSUtils::jsonDump(res);
else responseBody = "{}";
responseContentType = "application/json";
} }
// Wrap result in jsonp function call if the user included a jsonp= url argument. // Wrap result in jsonp function call if the user included a jsonp= url argument.

View file

@ -40,8 +40,7 @@ struct InetAddress;
class ControlPlane class ControlPlane
{ {
public: public:
ControlPlane(OneService *svc,Node *n,const char *uiStaticPath); ControlPlane(OneService *svc,Node *n);
~ControlPlane();
/** /**
* Set controller, which will be available under /controller * Set controller, which will be available under /controller
@ -88,7 +87,6 @@ private:
OneService *const _svc; OneService *const _svc;
Node *const _node; Node *const _node;
EmbeddedNetworkController *_controller; EmbeddedNetworkController *_controller;
std::string _uiStaticPath;
std::set<std::string> _authTokens; std::set<std::string> _authTokens;
Mutex _lock; Mutex _lock;
}; };

View file

@ -690,7 +690,7 @@ public:
} }
#endif #endif
_controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S "ui").c_str()); _controlPlane = new ControlPlane(this,_node);
_controlPlane->addAuthToken(authToken.c_str()); _controlPlane->addAuthToken(authToken.c_str());
_controlPlane->setController(_controller); _controlPlane->setController(_controller);