diff options
author | Adam Ierymenko <adam.ierymenko@gmail.com> | 2017-02-13 14:27:08 -0800 |
---|---|---|
committer | Adam Ierymenko <adam.ierymenko@gmail.com> | 2017-02-13 14:27:08 -0800 |
commit | 4b115665057a334c08e427e0f34a4e3a48514ea1 (patch) | |
tree | 7abbc2a4ba05ccdd57a920f5f5e8a43683e4ac44 | |
parent | c95bae2d7389fdaff84e6c518f7f0ebbd1b46230 (diff) | |
download | infinitytier-4b115665057a334c08e427e0f34a4e3a48514ea1.tar.gz infinitytier-4b115665057a334c08e427e0f34a4e3a48514ea1.zip |
Integrate moon concept into http config bus, and clean up that code quite a bit.
-rw-r--r-- | include/ZeroTierOne.h | 10 | ||||
-rw-r--r-- | node/Node.cpp | 12 | ||||
-rw-r--r-- | node/Node.hpp | 6 | ||||
-rw-r--r-- | node/World.hpp | 10 | ||||
-rw-r--r-- | service/ControlPlane.cpp | 577 | ||||
-rw-r--r-- | service/ControlPlane.hpp | 4 | ||||
-rw-r--r-- | service/OneService.cpp | 2 |
7 files changed, 263 insertions, 358 deletions
diff --git a/include/ZeroTierOne.h b/include/ZeroTierOne.h index 38ae7d8a..9690489a 100644 --- a/include/ZeroTierOne.h +++ b/include/ZeroTierOne.h @@ -443,16 +443,6 @@ typedef struct 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) * * This pointer will remain valid as long as the node exists. diff --git a/node/Node.cpp b/node/Node.cpp index 388a4fb2..6dc89387 100644 --- a/node/Node.cpp +++ b/node/Node.cpp @@ -362,8 +362,6 @@ uint64_t Node::address() const void Node::status(ZT_NodeStatus *status) const { status->address = RR->identity.address().toInt(); - status->worldId = RR->topology->planetWorldId(); - status->worldTimestamp = RR->topology->planetWorldTimestamp(); status->publicIdentity = RR->publicIdentityStr.c_str(); status->secretIdentity = RR->secretIdentityStr.c_str(); 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); } +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) { if (destination == RR->identity.address()) { diff --git a/node/Node.hpp b/node/Node.hpp index d83ce968..a1d4b719 100644 --- a/node/Node.hpp +++ b/node/Node.hpp @@ -24,6 +24,7 @@ #include <string.h> #include <map> +#include <vector> #include "Constants.hpp" @@ -54,6 +55,8 @@ namespace ZeroTier { +class World; + /** * Implementation of Node object as defined in CAPI * @@ -210,6 +213,9 @@ public: void postCircuitTestReport(const ZT_CircuitTestReport *report); 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 * diff --git a/node/World.hpp b/node/World.hpp index 8fe6dd2e..6e835bec 100644 --- a/node/World.hpp +++ b/node/World.hpp @@ -136,6 +136,16 @@ public: 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 * * @param update Candidate update diff --git a/service/ControlPlane.cpp b/service/ControlPlane.cpp index 0b0fbc09..100deeda 100644 --- a/service/ControlPlane.cpp +++ b/service/ControlPlane.cpp @@ -35,77 +35,17 @@ #include "../node/InetAddress.hpp" #include "../node/Node.hpp" #include "../node/Utils.hpp" +#include "../node/World.hpp" + #include "../osdep/OSUtils.hpp" namespace ZeroTier { -static std::string _jsonEscape(const char *s) -{ - 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()); } +namespace { -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; - 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'; + char tmp[256]; const char *nstatus = "",*ntype = ""; 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; } - std::string allowManaged = (localSettings.allowManaged) ? "true" : "false"; - if (localSettings.allowManagedWhitelist.size() != 0) { - allowManaged = ""; - for (InetAddress address : localSettings.allowManagedWhitelist) { - if (allowManaged.size() != 0) allowManaged += ','; - allowManaged += address.toIpString() + "/" + std::to_string(address.netmaskBits()); - } + Utils::snprintf(tmp,sizeof(tmp),"%.16llx",nc->nwid); + nj["id"] = tmp; + nj["nwid"] = tmp; + 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)); + nj["mac"] = tmp; + 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; + + nlohmann::json aa = nlohmann::json::array(); + for(unsigned int i=0;i<nc->assignedAddressCount;++i) { + aa.push_back(reinterpret_cast<const InetAddress *>(&(nc->assignedAddresses[i]))->toString()); } - - Utils::snprintf(json,sizeof(json), - "%s{\n" - "%s\t\"id\": \"%.16llx\",\n" - "%s\t\"nwid\": \"%.16llx\",\n" - "%s\t\"mac\": \"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",\n" - "%s\t\"name\": \"%s\",\n" - "%s\t\"status\": \"%s\",\n" - "%s\t\"type\": \"%s\",\n" - "%s\t\"mtu\": %u,\n" - "%s\t\"dhcp\": %s,\n" - "%s\t\"bridge\": %s,\n" - "%s\t\"broadcastEnabled\": %s,\n" - "%s\t\"portError\": %d,\n" - "%s\t\"netconfRevision\": %lu,\n" - "%s\t\"assignedAddresses\": %s,\n" - "%s\t\"routes\": %s,\n" - "%s\t\"portDeviceName\": \"%s\",\n" - "%s\t\"allowManaged\": %s,\n" - "%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) -{ - char json[2048]; - 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); + nj["assignedAddresses"] = aa; + + nlohmann::json ra = nlohmann::json::array(); + for(unsigned int i=0;i<nc->routeCount;++i) { + nlohmann::json rj; + rj["target"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].target))->toString(); + if (nc->routes[i].via.ss_family == nc->routes[i].target.ss_family) + rj["via"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].via))->toIpString(); + else rj["via"] = nlohmann::json(); + rj["flags"] = (int)nc->routes[i].flags; + rj["metric"] = (int)nc->routes[i].metric; + ra.push_back(rj); } - return buf; + nj["routes"] = ra; } -static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_Peer *peer) +static void _peerToJson(nlohmann::json &pj,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'; + char tmp[256]; const char *prole = ""; 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; } - Utils::snprintf(json,sizeof(json), - "%s{\n" - "%s\t\"address\": \"%.10llx\",\n" - "%s\t\"versionMajor\": %d,\n" - "%s\t\"versionMinor\": %d,\n" - "%s\t\"versionRev\": %d,\n" - "%s\t\"version\": \"%d.%d.%d\",\n" - "%s\t\"latency\": %u,\n" - "%s\t\"role\": \"%s\",\n" - "%s\t\"paths\": [%s]\n" - "%s}", - prefix, - prefix,peer->address, - prefix,peer->versionMajor, - prefix,peer->versionMinor, - prefix,peer->versionRev, - prefix,peer->versionMajor,peer->versionMinor,peer->versionRev, - prefix,peer->latency, - prefix,prole, - prefix,_jsonEnumerate(depth+1,peer->paths,peer->pathCount).c_str(), - prefix); - buf.append(json); + Utils::snprintf(tmp,sizeof(tmp),"%.10llx",peer->address); + pj["address"] = tmp; + pj["versionMajor"] = peer->versionMajor; + pj["versionMinor"] = peer->versionMinor; + pj["versionRev"] = peer->versionRev; + Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev); + pj["version"] = tmp; + pj["latency"] = peer->latency; + pj["role"] = prole; + + nlohmann::json pa = nlohmann::json::array(); + for(unsigned int i=0;i<peer->pathCount;++i) { + nlohmann::json j; + j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString(); + j["lastSend"] = peer->paths[i].lastSend; + j["lastReceive"] = peer->paths[i].lastReceive; + j["active"] = (bool)(peer->paths[i].expired != 0); + j["expired"] = (bool)(peer->paths[i].expired == 0); + j["preferred"] = (bool)(peer->paths[i].preferred == 0); + j["trustedPathId"] = peer->paths[i].trustedPathId; + pa.push_back(j); + } + pj["paths"] = pa; } -ControlPlane::ControlPlane(OneService *svc,Node *n,const char *uiStaticPath) : - _svc(svc), - _node(n), - _controller((EmbeddedNetworkController *)0), - _uiStaticPath((uiStaticPath) ? 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; } -ControlPlane::~ControlPlane() +} // anonymous namespace + +ControlPlane::ControlPlane(OneService *svc,Node *n) : + _svc(svc), + _node(n), + _controller((EmbeddedNetworkController *)0) { } @@ -275,10 +174,12 @@ unsigned int ControlPlane::handleRequest( std::string &responseBody, std::string &responseContentType) { - char json[8194]; + char tmp[256]; unsigned int scode = 404; + nlohmann::json res; std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","","")); std::map<std::string,std::string> urlArgs; + Mutex::Lock _l(_lock); /* 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 { - ps.push_back(std::string("index.html")); } bool isAuth = false; @@ -315,148 +214,113 @@ unsigned int ControlPlane::handleRequest( } if (httpMethod == HTTP_GET) { - - 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 (isAuth) { if (ps[0] == "status") { - responseContentType = "application/json"; - ZT_NodeStatus status; _node->status(&status); - std::string clusterJson; + Utils::snprintf(tmp,sizeof(tmp),"%.10llx",status.address); + res["address"] = tmp; + res["publicIdentity"] = status.publicIdentity; + res["online"] = (bool)status.online; + 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(); + + World planet(_node->planet()); + res["planetWorldId"] = planet.id(); + res["planetWorldTimestamp"] = planet.timestamp(); + #ifdef ZT_ENABLE_CLUSTER - { - ZT_ClusterStatus cs; - _node->clusterStatus(&cs); - - if (cs.clusterSize >= 1) { - char t[1024]; - Utils::snprintf(t,sizeof(t),"{\n\t\t\"myId\": %u,\n\t\t\"clusterSize\": %u,\n\t\t\"members\": [",cs.myId,cs.clusterSize); - clusterJson.append(t); - for(unsigned int i=0;i<cs.clusterSize;++i) { - 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}", - ((i == 0) ? "\n" : ",\n"), - cs.members[i].id, - cs.members[i].msSinceLastHeartbeat, - (cs.members[i].alive != 0) ? "true" : "false", - cs.members[i].x, - cs.members[i].y, - cs.members[i].z, - cs.members[i].load, - cs.members[i].peers); - clusterJson.append(t); - } - clusterJson.append(" ]\n\t\t}"); + nlohmann::json cj; + ZT_ClusterStatus cs; + _node->clusterStatus(&cs); + if (cs.clusterSize >= 1) { + nlohmann::json cja = nlohmann::json::array(); + for(unsigned int i=0;i<cs.clusterSize;++i) { + nlohmann::json cjm; + cjm["id"] = (int)cs.members[i].id; + cjm["msSinceLastHeartbeat"] = cs.members[i].msSinceLastHeartbeat; + cjm["alive"] = (bool)(cs.members[i].alive != 0); + cjm["x"] = cs.members[i].x; + cjm["y"] = cs.members[i].y; + 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 - 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; + } 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") { ZT_VirtualNetworkList *nws = _node->networks(); if (nws) { if (ps.size() == 1) { // Return [array] of all networks - responseContentType = "application/json"; - responseBody = "[\n"; + + res = nlohmann::json::array(); for(unsigned long i=0;i<nws->networkCount;++i) { - if (i > 0) - responseBody.append(","); OneService::NetworkSettings 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; } else if (ps.size() == 2) { // 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) { if (nws->networks[i].nwid == wantnw) { - responseContentType = "application/json"; OneService::NetworkSettings localSettings; _svc->getNetworkSettings(nws->networks[i].nwid,localSettings); - _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings); - responseBody.push_back('\n'); + _networkToJson(res,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings); scode = 200; break; } } - } // else 404 + + } else scode = 404; _node->freeQueryResult((void *)nws); } else scode = 500; } else if (ps[0] == "peer") { @@ -464,54 +328,78 @@ unsigned int ControlPlane::handleRequest( if (pl) { if (ps.size() == 1) { // Return [array] of all peers - responseContentType = "application/json"; - responseBody = "[\n"; + + res = nlohmann::json::array(); for(unsigned long i=0;i<pl->peerCount;++i) { - if (i > 0) - responseBody.append(",\n"); - _jsonAppend(1,responseBody,&(pl->peers[i])); + nlohmann::json pj; + _peerToJson(pj,&(pl->peers[i])); + res.push_back(pj); } - responseBody.append("\n]\n"); + scode = 200; } else if (ps.size() == 2) { // Return a single peer by ID or 404 if not found + uint64_t wantp = Utils::hexStrToU64(ps[1].c_str()); for(unsigned long i=0;i<pl->peerCount;++i) { if (pl->peers[i].address == wantp) { - responseContentType = "application/json"; - _jsonAppend(0,responseBody,&(pl->peers[i])); - responseBody.push_back('\n'); + _peerToJson(res,&(pl->peers[i])); scode = 200; break; } } - } // else 404 + + } else scode = 404; _node->freeQueryResult((void *)pl); } 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 { - if (_controller) + if (_controller) { 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 if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) { - if (isAuth) { - if (ps[0] == "settings") { - // TODO + if (ps[0] == "moon") { + 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") { if (ps.size() == 2) { + uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str()); _node->join(wantnw,(void *)0); // does nothing if we are a member ZT_VirtualNetworkList *nws = _node->networks(); @@ -536,17 +424,16 @@ unsigned int ControlPlane::handleRequest( } _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; break; } } _node->freeQueryResult((void *)nws); } else scode = 500; - } + + } else scode = 404; } else { if (_controller) 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 if (httpMethod == HTTP_DELETE) { - 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(); if (nws) { if (ps.size() == 2) { @@ -567,8 +458,7 @@ unsigned int ControlPlane::handleRequest( for(unsigned long i=0;i<nws->networkCount;++i) { if (nws->networks[i].nwid == wantnw) { _node->leave(wantnw,(void **)0); - responseBody = "true"; - responseContentType = "application/json"; + res["result"] = true; scode = 200; break; } @@ -582,13 +472,16 @@ unsigned int ControlPlane::handleRequest( else scode = 404; } - } else { - scode = 401; // isAuth = false - } - + } else scode = 401; // isAuth = false } else { 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. diff --git a/service/ControlPlane.hpp b/service/ControlPlane.hpp index ec9b94d7..a1f743cb 100644 --- a/service/ControlPlane.hpp +++ b/service/ControlPlane.hpp @@ -40,8 +40,7 @@ struct InetAddress; class ControlPlane { public: - ControlPlane(OneService *svc,Node *n,const char *uiStaticPath); - ~ControlPlane(); + ControlPlane(OneService *svc,Node *n); /** * Set controller, which will be available under /controller @@ -88,7 +87,6 @@ private: OneService *const _svc; Node *const _node; EmbeddedNetworkController *_controller; - std::string _uiStaticPath; std::set<std::string> _authTokens; Mutex _lock; }; diff --git a/service/OneService.cpp b/service/OneService.cpp index 6465463b..d56333c0 100644 --- a/service/OneService.cpp +++ b/service/OneService.cpp @@ -690,7 +690,7 @@ public: } #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->setController(_controller); |