summaryrefslogtreecommitdiff
path: root/service/OneService.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'service/OneService.cpp')
-rw-r--r--service/OneService.cpp1561
1 files changed, 1070 insertions, 491 deletions
diff --git a/service/OneService.cpp b/service/OneService.cpp
index 381709f8..b9ea32af 100644
--- a/service/OneService.cpp
+++ b/service/OneService.cpp
@@ -31,12 +31,6 @@
#include "../version.h"
#include "../include/ZeroTierOne.h"
-#ifdef ZT_USE_SYSTEM_HTTP_PARSER
-#include <http_parser.h>
-#else
-#include "../ext/http-parser/http_parser.h"
-#endif
-
#include "../node/Constants.hpp"
#include "../node/Mutex.hpp"
#include "../node/Node.hpp"
@@ -44,32 +38,20 @@
#include "../node/InetAddress.hpp"
#include "../node/MAC.hpp"
#include "../node/Identity.hpp"
+#include "../node/World.hpp"
#include "../osdep/Phy.hpp"
#include "../osdep/Thread.hpp"
#include "../osdep/OSUtils.hpp"
#include "../osdep/Http.hpp"
-#include "../osdep/BackgroundResolver.hpp"
#include "../osdep/PortMapper.hpp"
#include "../osdep/Binder.hpp"
#include "../osdep/ManagedRoute.hpp"
#include "OneService.hpp"
-#include "ControlPlane.hpp"
#include "ClusterGeoIpService.hpp"
#include "ClusterDefinition.hpp"
-
-/**
- * Uncomment to enable UDP breakage switch
- *
- * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
- * will cause direct UDP TX/RX to stop working. This can be used to
- * test TCP tunneling fallback and other robustness features. Deleting
- * this file will cause it to start working again.
- */
-//#define ZT_BREAK_UDP
-
-#include "../controller/EmbeddedNetworkController.hpp"
+#include "SoftwareUpdater.hpp"
#ifdef __WINDOWS__
#include <WinSock2.h>
@@ -85,6 +67,28 @@
#include <ifaddrs.h>
#endif
+#ifdef ZT_USE_SYSTEM_HTTP_PARSER
+#include <http_parser.h>
+#else
+#include "../ext/http-parser/http_parser.h"
+#endif
+
+#include "../ext/json/json.hpp"
+
+using json = nlohmann::json;
+
+/**
+ * Uncomment to enable UDP breakage switch
+ *
+ * If this is defined, the presence of a file called /tmp/ZT_BREAK_UDP
+ * will cause direct UDP TX/RX to stop working. This can be used to
+ * test TCP tunneling fallback and other robustness features. Deleting
+ * this file will cause it to start working again.
+ */
+//#define ZT_BREAK_UDP
+
+#include "../controller/EmbeddedNetworkController.hpp"
+
// Include the right tap device driver for this platform -- add new platforms here
#ifdef ZT_SERVICE_NETCON
@@ -110,6 +114,10 @@ namespace ZeroTier { typedef WindowsEthernetTap EthernetTap; }
#include "../osdep/BSDEthernetTap.hpp"
namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
#endif // __FreeBSD__
+#ifdef __OpenBSD__
+#include "../osdep/BSDEthernetTap.hpp"
+namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
+#endif // __OpenBSD__
#endif // ZT_SERVICE_NETCON
@@ -127,9 +135,8 @@ namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
// Path under ZT1 home for controller database if controller is enabled
#define ZT_CONTROLLER_DB_PATH "controller.d"
-// TCP fallback relay host -- geo-distributed using Amazon Route53 geo-aware DNS
-#define ZT_TCP_FALLBACK_RELAY "tcp-fallback.zerotier.com"
-#define ZT_TCP_FALLBACK_RELAY_PORT 443
+// TCP fallback relay (run by ZeroTier, Inc. -- this will eventually go away)
+#define ZT_TCP_FALLBACK_RELAY "204.80.128.1/443"
// Frequency at which we re-resolve the TCP fallback relay
#define ZT_TCP_FALLBACK_RERESOLVE_DELAY 86400000
@@ -140,239 +147,13 @@ namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
// How often to check for local interface addresses
#define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
+// Clean files from iddb.d that are older than this (60 days)
+#define ZT_IDDB_CLEANUP_AGE 5184000000ULL
+
namespace ZeroTier {
namespace {
-#ifdef ZT_AUTO_UPDATE
-#define ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE (1024 * 1024 * 64)
-#define ZT_AUTO_UPDATE_CHECK_PERIOD 21600000
-class BackgroundSoftwareUpdateChecker
-{
-public:
- bool isValidSigningIdentity(const Identity &id)
- {
- return (
- /* 0001 - 0004 : obsolete, used in old versions */
- /* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
- /* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
- /* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
- /* 0008 */ ||(id == Identity("580bbb8e15:0:ad5ef31155bebc6bc413991992387e083fed26d699997ef76e7c947781edd47d1997161fa56ba337b1a2b44b129fd7c7197ce5185382f06011bc88d1363b4ddd"))
- );
- }
-
- void doUpdateCheck()
- {
- std::string url(OneService::autoUpdateUrl());
- if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
- return;
-
- std::string httpHost;
- std::string httpPath;
- {
- std::size_t slashIdx = url.substr(7).find_first_of('/');
- if (slashIdx == std::string::npos) {
- httpHost = url.substr(7);
- httpPath = "/";
- } else {
- httpHost = url.substr(7,slashIdx);
- httpPath = url.substr(slashIdx + 7);
- }
- }
- if (httpHost.length() == 0)
- return;
-
- std::vector<InetAddress> ips(OSUtils::resolve(httpHost.c_str()));
- for(std::vector<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
- if (!ip->port())
- ip->setPort(80);
- std::string nfoPath = httpPath + "LATEST.nfo";
- std::map<std::string,std::string> requestHeaders,responseHeaders;
- std::string body;
- requestHeaders["Host"] = httpHost;
- unsigned int scode = Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),nfoPath.c_str(),requestHeaders,responseHeaders,body);
- //fprintf(stderr,"UPDATE %s %s %u %lu\n",ip->toString().c_str(),nfoPath.c_str(),scode,body.length());
- if ((scode == 200)&&(body.length() > 0)) {
- /* NFO fields:
- *
- * file=<filename>
- * signedBy=<signing identity>
- * ed25519=<ed25519 ECC signature of archive in hex>
- * vMajor=<major version>
- * vMinor=<minor version>
- * vRevision=<revision> */
- Dictionary<4096> nfo(body.c_str());
- char tmp[2048];
-
- if (nfo.get("vMajor",tmp,sizeof(tmp)) <= 0) return;
- const unsigned int vMajor = Utils::strToUInt(tmp);
- if (nfo.get("vMinor",tmp,sizeof(tmp)) <= 0) return;
- const unsigned int vMinor = Utils::strToUInt(tmp);
- if (nfo.get("vRevision",tmp,sizeof(tmp)) <= 0) return;
- const unsigned int vRevision = Utils::strToUInt(tmp);
- if (Utils::compareVersion(vMajor,vMinor,vRevision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) <= 0) {
- //fprintf(stderr,"UPDATE %u.%u.%u is not newer than our version\n",vMajor,vMinor,vRevision);
- return;
- }
-
- if (nfo.get("signedBy",tmp,sizeof(tmp)) <= 0) return;
- Identity signedBy;
- if ((!signedBy.fromString(tmp))||(!isValidSigningIdentity(signedBy))) {
- //fprintf(stderr,"UPDATE invalid signedBy or not authorized signing identity.\n");
- return;
- }
-
- if (nfo.get("file",tmp,sizeof(tmp)) <= 0) return;
- std::string filePath(tmp);
- if ((!filePath.length())||(filePath.find("..") != std::string::npos))
- return;
- filePath = httpPath + filePath;
-
- std::string fileData;
- if (Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),filePath.c_str(),requestHeaders,responseHeaders,fileData) != 200) {
- //fprintf(stderr,"UPDATE GET %s failed\n",filePath.c_str());
- return;
- }
-
- if (nfo.get("ed25519",tmp,sizeof(tmp)) <= 0) return;
- std::string ed25519(Utils::unhex(tmp));
- if ((ed25519.length() == 0)||(!signedBy.verify(fileData.data(),(unsigned int)fileData.length(),ed25519.data(),(unsigned int)ed25519.length()))) {
- //fprintf(stderr,"UPDATE %s failed signature check!\n",filePath.c_str());
- return;
- }
-
- /* --------------------------------------------------------------- */
- /* We made it! Begin OS-specific installation code. */
-
-#ifdef __APPLE__
- /* OSX version is in the form of a MacOSX .pkg file, so we will
- * launch installer (normally in /usr/sbin) to install it. It will
- * then turn around and shut down the service, update files, and
- * relaunch. */
- {
- char bashp[128],pkgp[128];
- Utils::snprintf(bashp,sizeof(bashp),"/tmp/ZeroTierOne-update-%u.%u.%u.sh",vMajor,vMinor,vRevision);
- Utils::snprintf(pkgp,sizeof(pkgp),"/tmp/ZeroTierOne-update-%u.%u.%u.pkg",vMajor,vMinor,vRevision);
- FILE *pkg = fopen(pkgp,"w");
- if ((!pkg)||(fwrite(fileData.data(),fileData.length(),1,pkg) != 1)) {
- fclose(pkg);
- unlink(bashp);
- unlink(pkgp);
- fprintf(stderr,"UPDATE error writing %s\n",pkgp);
- return;
- }
- fclose(pkg);
- FILE *bash = fopen(bashp,"w");
- if (!bash) {
- fclose(pkg);
- unlink(bashp);
- unlink(pkgp);
- fprintf(stderr,"UPDATE error writing %s\n",bashp);
- return;
- }
- fprintf(bash,
- "#!/bin/bash\n"
- "export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin\n"
- "sleep 1\n"
- "installer -pkg \"%s\" -target /\n"
- "sleep 1\n"
- "rm -f \"%s\" \"%s\"\n"
- "exit 0\n",
- pkgp,
- pkgp,
- bashp);
- fclose(bash);
- long pid = (long)vfork();
- if (pid == 0) {
- setsid(); // detach from parent so that shell isn't killed when parent is killed
- signal(SIGHUP,SIG_IGN);
- signal(SIGTERM,SIG_IGN);
- signal(SIGQUIT,SIG_IGN);
- execl("/bin/bash","/bin/bash",bashp,(char *)0);
- exit(0);
- }
- }
-#endif // __APPLE__
-
-#ifdef __WINDOWS__
- /* Windows version comes in the form of .MSI package that
- * takes care of everything. */
- {
- char tempp[512],batp[512],msip[512],cmdline[512];
- if (GetTempPathA(sizeof(tempp),tempp) <= 0)
- return;
- CreateDirectoryA(tempp,(LPSECURITY_ATTRIBUTES)0);
- Utils::snprintf(batp,sizeof(batp),"%s\\ZeroTierOne-update-%u.%u.%u.bat",tempp,vMajor,vMinor,vRevision);
- Utils::snprintf(msip,sizeof(msip),"%s\\ZeroTierOne-update-%u.%u.%u.msi",tempp,vMajor,vMinor,vRevision);
- FILE *msi = fopen(msip,"wb");
- if ((!msi)||(fwrite(fileData.data(),(size_t)fileData.length(),1,msi) != 1)) {
- fclose(msi);
- return;
- }
- fclose(msi);
- FILE *bat = fopen(batp,"wb");
- if (!bat)
- return;
- fprintf(bat,
- "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
- "NET.EXE STOP \"ZeroTierOneService\"\r\n"
- "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
- "MSIEXEC.EXE /i \"%s\" /qn\r\n"
- "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
- "NET.EXE START \"ZeroTierOneService\"\r\n"
- "DEL \"%s\"\r\n"
- "DEL \"%s\"\r\n",
- msip,
- msip,
- batp);
- fclose(bat);
- STARTUPINFOA si;
- PROCESS_INFORMATION pi;
- memset(&si,0,sizeof(si));
- memset(&pi,0,sizeof(pi));
- Utils::snprintf(cmdline,sizeof(cmdline),"CMD.EXE /c \"%s\"",batp);
- CreateProcessA(NULL,cmdline,NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
- }
-#endif // __WINDOWS__
-
- /* --------------------------------------------------------------- */
-
- return;
- } // else try to fetch from next IP address
- }
- }
-
- void threadMain()
- throw()
- {
- try {
- this->doUpdateCheck();
- } catch ( ... ) {}
- }
-};
-static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
-#endif // ZT_AUTO_UPDATE
-
-static bool isBlacklistedLocalInterfaceForZeroTierTraffic(const char *ifn)
-{
-#if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
- if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
- if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
- if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
- if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
-#endif
-
-#ifdef __APPLE__
- if ((ifn[0] == 'l')&&(ifn[1] == 'o')) return true; // loopback
- if ((ifn[0] == 'z')&&(ifn[1] == 't')) return true; // sanity check: zt#
- if ((ifn[0] == 't')&&(ifn[1] == 'u')&&(ifn[2] == 'n')) return true; // tun# is probably an OpenVPN tunnel or similar
- if ((ifn[0] == 't')&&(ifn[1] == 'a')&&(ifn[2] == 'p')) return true; // tap# is probably an OpenVPN tunnel or similar
- if ((ifn[0] == 'u')&&(ifn[1] == 't')&&(ifn[2] == 'u')&&(ifn[3] == 'n')) return true; // ... as is utun#
-#endif
-
- return false;
-}
-
static std::string _trimString(const std::string &s)
{
unsigned long end = (unsigned long)s.length();
@@ -392,6 +173,122 @@ static std::string _trimString(const std::string &s)
return s.substr(start,end - start);
}
+static void _networkToJson(nlohmann::json &nj,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
+{
+ char tmp[256];
+
+ const char *nstatus = "",*ntype = "";
+ switch(nc->status) {
+ case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
+ case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
+ case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
+ case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
+ case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
+ case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
+ }
+ switch(nc->type) {
+ case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
+ case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
+ }
+
+ 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());
+ }
+ 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);
+ }
+ nj["routes"] = ra;
+}
+
+static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer)
+{
+ char tmp[256];
+
+ const char *prole = "";
+ switch(peer->role) {
+ case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
+ case ZT_PEER_ROLE_MOON: prole = "MOON"; break;
+ case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
+ }
+
+ 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["trustedPathId"] = peer->paths[i].trustedPathId;
+ j["linkQuality"] = (double)peer->paths[i].linkQuality / (double)ZT_PATH_LINK_QUALITY_MAX;
+ j["active"] = (bool)(peer->paths[i].expired == 0);
+ j["expired"] = (bool)(peer->paths[i].expired != 0);
+ j["preferred"] = (bool)(peer->paths[i].preferred != 0);
+ pa.push_back(j);
+ }
+ pj["paths"] = pa;
+}
+
+static void _moonToJson(nlohmann::json &mj,const World &world)
+{
+ char tmp[64];
+ Utils::snprintf(tmp,sizeof(tmp),"%.16llx",world.id());
+ mj["id"] = tmp;
+ mj["timestamp"] = world.timestamp();
+ mj["signature"] = Utils::hex(world.signature().data,(unsigned int)world.signature().size());
+ mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,(unsigned int)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["waiting"] = false;
+}
+
class OneServiceImpl;
static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf);
@@ -400,7 +297,8 @@ static long SnodeDataStoreGetFunction(ZT_Node *node,void *uptr,const char *name,
static int SnodeDataStorePutFunction(ZT_Node *node,void *uptr,const char *name,const void *data,unsigned long len,int secure);
static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl);
static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
-static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
+static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr);
+static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result);
#ifdef ZT_ENABLE_CLUSTER
static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len);
@@ -482,10 +380,25 @@ public:
// begin member variables --------------------------------------------------
const std::string _homePath;
- BackgroundResolver _tcpFallbackResolver;
+ std::string _authToken;
EmbeddedNetworkController *_controller;
Phy<OneServiceImpl *> _phy;
Node *_node;
+ SoftwareUpdater *_updater;
+ bool _updateAutoApply;
+ unsigned int _primaryPort;
+
+ // Local configuration and memo-ized static path definitions
+ json _localConfig;
+ Hashtable< uint64_t,std::vector<InetAddress> > _v4Hints;
+ Hashtable< uint64_t,std::vector<InetAddress> > _v6Hints;
+ Hashtable< uint64_t,std::vector<InetAddress> > _v4Blacklists;
+ Hashtable< uint64_t,std::vector<InetAddress> > _v6Blacklists;
+ std::vector< InetAddress > _globalV4Blacklist;
+ std::vector< InetAddress > _globalV6Blacklist;
+ std::vector< InetAddress > _allowManagementFrom;
+ std::vector< std::string > _interfacePrefixBlacklist;
+ Mutex _localConfig_m;
/*
* To attempt to handle NAT/gateway craziness we use three local UDP ports:
@@ -498,7 +411,6 @@ public:
* destructively with uPnP port mapping behavior in very weird buggy ways.
* It's only used if uPnP/NAT-PMP is enabled in this build.
*/
-
Binder _bindings[3];
unsigned int _ports[3];
uint16_t _portsBE[3]; // ports in big-endian network byte order as in sockaddr
@@ -507,9 +419,6 @@ public:
PhySocket *_v4TcpControlSocket;
PhySocket *_v6TcpControlSocket;
- // JSON API handler
- ControlPlane *_controlPlane;
-
// Time we last received a packet from a global address
uint64_t _lastDirectReceiveFromGlobal;
#ifdef ZT_TCP_FALLBACK_RELAY
@@ -553,6 +462,7 @@ public:
Mutex _termReason_m;
// uPnP/NAT-PMP port mapper if enabled
+ bool _portMappingEnabled; // local.conf settings
#ifdef ZT_USE_MINIUPNPC
PortMapper *_portMapper;
#endif
@@ -572,11 +482,12 @@ public:
OneServiceImpl(const char *hp,unsigned int port) :
_homePath((hp) ? hp : ".")
- ,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
,_controller((EmbeddedNetworkController *)0)
,_phy(this,false,true)
,_node((Node *)0)
- ,_controlPlane((ControlPlane *)0)
+ ,_updater((SoftwareUpdater *)0)
+ ,_updateAutoApply(false)
+ ,_primaryPort(port)
,_lastDirectReceiveFromGlobal(0)
#ifdef ZT_TCP_FALLBACK_RELAY
,_lastSendToGlobalV4(0)
@@ -585,6 +496,7 @@ public:
,_nextBackgroundTaskDeadline(0)
,_tcpFallbackTunnel((TcpConnection *)0)
,_termReason(ONE_STILL_RUNNING)
+ ,_portMappingEnabled(true)
#ifdef ZT_USE_MINIUPNPC
,_portMapper((PortMapper *)0)
#endif
@@ -598,56 +510,6 @@ public:
_ports[0] = 0;
_ports[1] = 0;
_ports[2] = 0;
-
- // The control socket is bound to the default/static port on localhost. If we
- // can do this, we have successfully allocated a port. The binders will take
- // care of binding non-local addresses for ZeroTier traffic.
- const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
- for(int k=0;k<portTrials;++k) {
- if (port == 0) {
- unsigned int randp = 0;
- Utils::getSecureRandom(&randp,sizeof(randp));
- port = 20000 + (randp % 45500);
- }
-
- if (_trialBind(port)) {
- struct sockaddr_in in4;
- memset(&in4,0,sizeof(in4));
- in4.sin_family = AF_INET;
- in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @127.0.0.1
- in4.sin_port = Utils::hton((uint16_t)port);
- _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
-
- struct sockaddr_in6 in6;
- memset((void *)&in6,0,sizeof(in6));
- in6.sin6_family = AF_INET6;
- in6.sin6_port = in4.sin_port;
- in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
- _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
-
- // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
- // have only IPv4 or only IPv6 stacks.
- if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
- _ports[0] = port;
- break;
- } else {
- if (_v4TcpControlSocket)
- _phy.close(_v4TcpControlSocket,false);
- if (_v6TcpControlSocket)
- _phy.close(_v6TcpControlSocket,false);
- port = 0;
- }
- } else {
- port = 0;
- }
- }
-
- if (_ports[0] == 0)
- throw std::runtime_error("cannot bind to local control interface port");
-
- char portstr[64];
- Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
- OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
}
virtual ~OneServiceImpl()
@@ -674,16 +536,15 @@ public:
virtual ReasonForTermination run()
{
try {
- std::string authToken;
{
- std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
- if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
+ const std::string authTokenPath(_homePath + ZT_PATH_SEPARATOR_S "authtoken.secret");
+ if (!OSUtils::readFile(authTokenPath.c_str(),_authToken)) {
unsigned char foo[24];
Utils::getSecureRandom(foo,sizeof(foo));
- authToken = "";
+ _authToken = "";
for(unsigned int i=0;i<sizeof(foo);++i)
- authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
- if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
+ _authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
+ if (!OSUtils::writeFile(authTokenPath.c_str(),_authToken)) {
Mutex::Lock _l(_termReason_m);
_termReason = ONE_UNRECOVERABLE_ERROR;
_fatalErrorMessage = "authtoken.secret could not be written";
@@ -692,22 +553,151 @@ public:
OSUtils::lockDownFile(authTokenPath.c_str(),false);
}
}
+ _authToken = _trimString(_authToken);
}
- authToken = _trimString(authToken);
// Clean up any legacy files if present
- OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S + "peers.save").c_str());
-
- _node = new Node(
- OSUtils::now(),
- this,
- SnodeDataStoreGetFunction,
- SnodeDataStorePutFunction,
- SnodeWirePacketSendFunction,
- SnodeVirtualNetworkFrameFunction,
- SnodeVirtualNetworkConfigFunction,
- SnodePathCheckFunction,
- SnodeEventCallback);
+ OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S "peers.save").c_str());
+ OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S "world").c_str());
+
+ {
+ struct ZT_Node_Callbacks cb;
+ cb.version = 0;
+ cb.dataStoreGetFunction = SnodeDataStoreGetFunction;
+ cb.dataStorePutFunction = SnodeDataStorePutFunction;
+ cb.wirePacketSendFunction = SnodeWirePacketSendFunction;
+ cb.virtualNetworkFrameFunction = SnodeVirtualNetworkFrameFunction;
+ cb.virtualNetworkConfigFunction = SnodeVirtualNetworkConfigFunction;
+ cb.eventCallback = SnodeEventCallback;
+ cb.pathCheckFunction = SnodePathCheckFunction;
+ cb.pathLookupFunction = SnodePathLookupFunction;
+ _node = new Node(this,&cb,OSUtils::now());
+ }
+
+ // Read local configuration
+ {
+ uint64_t trustedPathIds[ZT_MAX_TRUSTED_PATHS];
+ InetAddress trustedPathNetworks[ZT_MAX_TRUSTED_PATHS];
+ unsigned int trustedPathCount = 0;
+
+ // Old style "trustedpaths" flat file -- will eventually go away
+ FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S "trustedpaths").c_str(),"r");
+ if (trustpaths) {
+ char buf[1024];
+ while ((fgets(buf,sizeof(buf),trustpaths))&&(trustedPathCount < ZT_MAX_TRUSTED_PATHS)) {
+ int fno = 0;
+ char *saveptr = (char *)0;
+ uint64_t trustedPathId = 0;
+ InetAddress trustedPathNetwork;
+ for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
+ if (fno == 0) {
+ trustedPathId = Utils::hexStrToU64(f);
+ } else if (fno == 1) {
+ trustedPathNetwork = InetAddress(f);
+ } else break;
+ ++fno;
+ }
+ if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (trustedPathNetwork.netmaskBits() > 0) ) {
+ trustedPathIds[trustedPathCount] = trustedPathId;
+ trustedPathNetworks[trustedPathCount] = trustedPathNetwork;
+ ++trustedPathCount;
+ }
+ }
+ fclose(trustpaths);
+ }
+
+ // Read local config file
+ Mutex::Lock _l2(_localConfig_m);
+ std::string lcbuf;
+ if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lcbuf)) {
+ try {
+ _localConfig = OSUtils::jsonParse(lcbuf);
+ if (!_localConfig.is_object()) {
+ fprintf(stderr,"WARNING: unable to parse local.conf (root element is not a JSON object)" ZT_EOL_S);
+ }
+ } catch ( ... ) {
+ fprintf(stderr,"WARNING: unable to parse local.conf (invalid JSON)" ZT_EOL_S);
+ }
+ }
+
+ // Get any trusted paths in local.conf (we'll parse the rest of physical[] elsewhere)
+ json &physical = _localConfig["physical"];
+ if (physical.is_object()) {
+ for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
+ InetAddress net(OSUtils::jsonString(phy.key(),""));
+ if (net) {
+ if (phy.value().is_object()) {
+ uint64_t tpid;
+ if ((tpid = OSUtils::jsonInt(phy.value()["trustedPathId"],0ULL)) != 0ULL) {
+ if ( ((net.ss_family == AF_INET)||(net.ss_family == AF_INET6)) && (trustedPathCount < ZT_MAX_TRUSTED_PATHS) && (net.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (net.netmaskBits() > 0) ) {
+ trustedPathIds[trustedPathCount] = tpid;
+ trustedPathNetworks[trustedPathCount] = net;
+ ++trustedPathCount;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Set trusted paths if there are any
+ if (trustedPathCount)
+ _node->setTrustedPaths(reinterpret_cast<const struct sockaddr_storage *>(trustedPathNetworks),trustedPathIds,trustedPathCount);
+ }
+ applyLocalConfig();
+
+ // Bind TCP control socket
+ const int portTrials = (_primaryPort == 0) ? 256 : 1; // if port is 0, pick random
+ for(int k=0;k<portTrials;++k) {
+ if (_primaryPort == 0) {
+ unsigned int randp = 0;
+ Utils::getSecureRandom(&randp,sizeof(randp));
+ _primaryPort = 20000 + (randp % 45500);
+ }
+
+ if (_trialBind(_primaryPort)) {
+ struct sockaddr_in in4;
+ memset(&in4,0,sizeof(in4));
+ in4.sin_family = AF_INET;
+ in4.sin_addr.s_addr = Utils::hton((uint32_t)((_allowManagementFrom.size() > 0) ? 0 : 0x7f000001)); // right now we just listen for TCP @127.0.0.1
+ in4.sin_port = Utils::hton((uint16_t)_primaryPort);
+ _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
+
+ struct sockaddr_in6 in6;
+ memset((void *)&in6,0,sizeof(in6));
+ in6.sin6_family = AF_INET6;
+ in6.sin6_port = in4.sin_port;
+ if (_allowManagementFrom.size() == 0)
+ in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
+ _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
+
+ // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
+ // have only IPv4 or only IPv6 stacks.
+ if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
+ _ports[0] = _primaryPort;
+ break;
+ } else {
+ if (_v4TcpControlSocket)
+ _phy.close(_v4TcpControlSocket,false);
+ if (_v6TcpControlSocket)
+ _phy.close(_v6TcpControlSocket,false);
+ _primaryPort = 0;
+ }
+ } else {
+ _primaryPort = 0;
+ }
+ }
+ if (_ports[0] == 0) {
+ Mutex::Lock _l(_termReason_m);
+ _termReason = ONE_UNRECOVERABLE_ERROR;
+ _fatalErrorMessage = "cannot bind to local control interface port";
+ return _termReason;
+ }
+
+ // Write file containing primary port to be read by CLIs, etc.
+ char portstr[64];
+ Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
+ OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S "zerotier-one.port").c_str(),std::string(portstr));
// Attempt to bind to a secondary port chosen from our ZeroTier address.
// This exists because there are buggy NATs out there that fail if more
@@ -726,70 +716,49 @@ public:
}
#ifdef ZT_USE_MINIUPNPC
- // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
- // use the other two ports for that because some NATs do really funky
- // stuff with ports that are explicitly mapped that breaks things.
- if (_ports[1]) {
- _ports[2] = _ports[1];
- for(int i=0;;++i) {
- if (i > 1000) {
- _ports[2] = 0;
- break;
- } else if (++_ports[2] >= 65536) {
- _ports[2] = 20000;
+ if (_portMappingEnabled) {
+ // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
+ // use the other two ports for that because some NATs do really funky
+ // stuff with ports that are explicitly mapped that breaks things.
+ if (_ports[1]) {
+ _ports[2] = _ports[1];
+ for(int i=0;;++i) {
+ if (i > 1000) {
+ _ports[2] = 0;
+ break;
+ } else if (++_ports[2] >= 65536) {
+ _ports[2] = 20000;
+ }
+ if (_trialBind(_ports[2]))
+ break;
+ }
+ if (_ports[2]) {
+ char uniqueName[64];
+ Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
+ _portMapper = new PortMapper(_ports[2],uniqueName);
}
- if (_trialBind(_ports[2]))
- break;
- }
- if (_ports[2]) {
- char uniqueName[64];
- Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
- _portMapper = new PortMapper(_ports[2],uniqueName);
}
}
#endif
+ // Populate ports in big-endian format for quick compare
for(int i=0;i<3;++i)
_portsBE[i] = Utils::hton((uint16_t)_ports[i]);
- {
- FILE *trustpaths = fopen((_homePath + ZT_PATH_SEPARATOR_S + "trustedpaths").c_str(),"r");
- uint64_t ids[ZT_MAX_TRUSTED_PATHS];
- InetAddress addresses[ZT_MAX_TRUSTED_PATHS];
- if (trustpaths) {
- char buf[1024];
- unsigned int count = 0;
- while ((fgets(buf,sizeof(buf),trustpaths))&&(count < ZT_MAX_TRUSTED_PATHS)) {
- int fno = 0;
- char *saveptr = (char *)0;
- uint64_t trustedPathId = 0;
- InetAddress trustedPathNetwork;
- for(char *f=Utils::stok(buf,"=\r\n \t",&saveptr);(f);f=Utils::stok((char *)0,"=\r\n \t",&saveptr)) {
- if (fno == 0) {
- trustedPathId = Utils::hexStrToU64(f);
- } else if (fno == 1) {
- trustedPathNetwork = InetAddress(f);
- } else break;
- ++fno;
- }
- if ( (trustedPathId != 0) && ((trustedPathNetwork.ss_family == AF_INET)||(trustedPathNetwork.ss_family == AF_INET6)) && (trustedPathNetwork.ipScope() != InetAddress::IP_SCOPE_GLOBAL) && (trustedPathNetwork.netmaskBits() > 0) ) {
- ids[count] = trustedPathId;
- addresses[count] = trustedPathNetwork;
- ++count;
- }
- }
- fclose(trustpaths);
- if (count)
- _node->setTrustedPaths(reinterpret_cast<const struct sockaddr_storage *>(addresses),ids,count);
- }
+ // Check for legacy controller.db and terminate if present to prevent nasty surprises for DIY controller folks
+ if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S "controller.db").c_str())) {
+ Mutex::Lock _l(_termReason_m);
+ _termReason = ONE_UNRECOVERABLE_ERROR;
+ _fatalErrorMessage = "controller.db is present in our home path! run migrate-sqlite to migrate to new controller.d format.";
+ return _termReason;
}
- _controller = new EmbeddedNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str());
+ _controller = new EmbeddedNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S ZT_CONTROLLER_DB_PATH).c_str());
_node->setNetconfMaster((void *)_controller);
#ifdef ZT_ENABLE_CLUSTER
- if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str())) {
- _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S + "cluster").c_str());
+ if (OSUtils::fileExists((_homePath + ZT_PATH_SEPARATOR_S "cluster").c_str())) {
+ _clusterDefinition = new ClusterDefinition(_node->address(),(_homePath + ZT_PATH_SEPARATOR_S "cluster").c_str());
if (_clusterDefinition->size() > 0) {
std::vector<ClusterDefinition::MemberDefinition> members(_clusterDefinition->members());
for(std::vector<ClusterDefinition::MemberDefinition>::iterator m(members.begin());m!=members.end();++m) {
@@ -801,7 +770,7 @@ public:
Mutex::Lock _l(_termReason_m);
_termReason = ONE_UNRECOVERABLE_ERROR;
- _fatalErrorMessage = "Cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
+ _fatalErrorMessage = "cluster: can't determine my cluster member ID: able to bind more than one cluster message socket IP/port!";
return _termReason;
}
_clusterMessageSocket = cs;
@@ -812,7 +781,7 @@ public:
if (!_clusterMessageSocket) {
Mutex::Lock _l(_termReason_m);
_termReason = ONE_UNRECOVERABLE_ERROR;
- _fatalErrorMessage = "Cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
+ _fatalErrorMessage = "cluster: can't determine my cluster member ID: unable to bind to any cluster message socket IP/port.";
return _termReason;
}
@@ -836,29 +805,31 @@ public:
}
#endif
- _controlPlane = new ControlPlane(this,_node,(_homePath + ZT_PATH_SEPARATOR_S + "ui").c_str());
- _controlPlane->addAuthToken(authToken.c_str());
- _controlPlane->setController(_controller);
-
- { // Remember networks from previous session
- std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str()));
+ { // Load existing networks
+ std::vector<std::string> networksDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "networks.d").c_str()));
for(std::vector<std::string>::iterator f(networksDotD.begin());f!=networksDotD.end();++f) {
std::size_t dot = f->find_last_of('.');
if ((dot == 16)&&(f->substr(16) == ".conf"))
_node->join(Utils::hexStrToU64(f->substr(0,dot).c_str()),(void *)0);
}
}
+ { // Load existing moons
+ std::vector<std::string> moonsDotD(OSUtils::listDirectory((_homePath + ZT_PATH_SEPARATOR_S "moons.d").c_str()));
+ for(std::vector<std::string>::iterator f(moonsDotD.begin());f!=moonsDotD.end();++f) {
+ std::size_t dot = f->find_last_of('.');
+ if ((dot == 16)&&(f->substr(16) == ".moon"))
+ _node->orbit(Utils::hexStrToU64(f->substr(0,dot).c_str()),0);
+ }
+ }
_nextBackgroundTaskDeadline = 0;
uint64_t clockShouldBe = OSUtils::now();
_lastRestart = clockShouldBe;
uint64_t lastTapMulticastGroupCheck = 0;
- uint64_t lastTcpFallbackResolve = 0;
uint64_t lastBindRefresh = 0;
- uint64_t lastLocalInterfaceAddressCheck = (OSUtils::now() - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
-#ifdef ZT_AUTO_UPDATE
- uint64_t lastSoftwareUpdateCheck = 0;
-#endif // ZT_AUTO_UPDATE
+ uint64_t lastUpdateCheck = clockShouldBe;
+ uint64_t lastLocalInterfaceAddressCheck = (clockShouldBe - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
+ uint64_t lastCleanedIddb = 0;
for(;;) {
_run_m.lock();
if (!_run) {
@@ -873,6 +844,12 @@ public:
const uint64_t now = OSUtils::now();
+ // Clean iddb.d on start and every 24 hours
+ if ((now - lastCleanedIddb) > 86400000) {
+ lastCleanedIddb = now;
+ OSUtils::cleanDirectory((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str(),now - ZT_IDDB_CLEANUP_AGE);
+ }
+
// Attempt to detect sleep/wake events by detecting delay overruns
bool restarted = false;
if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
@@ -880,6 +857,13 @@ public:
restarted = true;
}
+ // Check for updates (if enabled)
+ if ((_updater)&&((now - lastUpdateCheck) > 10000)) {
+ lastUpdateCheck = now;
+ if (_updater->check(now) && _updateAutoApply)
+ _updater->apply();
+ }
+
// Refresh bindings in case device's interfaces have changed, and also sync routes to update any shadow routes (e.g. shadow default)
if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
lastBindRefresh = now;
@@ -903,18 +887,6 @@ public:
dl = _nextBackgroundTaskDeadline;
}
-#ifdef ZT_AUTO_UPDATE
- if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
- lastSoftwareUpdateCheck = now;
- Thread::start(&backgroundSoftwareUpdateChecker);
- }
-#endif // ZT_AUTO_UPDATE
-
- if ((now - lastTcpFallbackResolve) >= ZT_TCP_FALLBACK_RERESOLVE_DELAY) {
- lastTcpFallbackResolve = now;
- _tcpFallbackResolver.resolveNow();
- }
-
if ((_tcpFallbackTunnel)&&((now - _lastDirectReceiveFromGlobal) < (ZT_TCP_FALLBACK_AFTER / 2)))
_phy.close(_tcpFallbackTunnel->sock);
@@ -977,8 +949,8 @@ public:
_nets.clear();
}
- delete _controlPlane;
- _controlPlane = (ControlPlane *)0;
+ delete _updater;
+ _updater = (SoftwareUpdater *)0;
delete _node;
_node = (Node *)0;
@@ -1006,11 +978,6 @@ public:
else return std::string();
}
- virtual bool tcpFallbackActive() const
- {
- return (_tcpFallbackTunnel != (TcpConnection *)0);
- }
-
virtual void terminate()
{
_run_m.lock();
@@ -1054,13 +1021,529 @@ public:
return true;
}
- // Begin private implementation methods
+ // Internal implementation methods -----------------------------------------
+
+ inline unsigned int handleControlPlaneHttpRequest(
+ const InetAddress &fromAddress,
+ unsigned int httpMethod,
+ const std::string &path,
+ const std::map<std::string,std::string> &headers,
+ const std::string &body,
+ std::string &responseBody,
+ std::string &responseContentType)
+ {
+ char tmp[256];
+ unsigned int scode = 404;
+ json res;
+ std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
+ std::map<std::string,std::string> urlArgs;
+
+ /* Note: this is kind of restricted in what it'll take. It does not support
+ * URL encoding, and /'s in URL args will screw it up. But the only URL args
+ * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
+ * paths to simply-named resources. */
+ if (ps.size() > 0) {
+ std::size_t qpos = ps[ps.size() - 1].find('?');
+ if (qpos != std::string::npos) {
+ std::string args(ps[ps.size() - 1].substr(qpos + 1));
+ ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
+ std::vector<std::string> asplit(OSUtils::split(args.c_str(),"&","",""));
+ for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
+ std::size_t eqpos = a->find('=');
+ if (eqpos == std::string::npos)
+ urlArgs[*a] = "";
+ else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
+ }
+ }
+ }
+
+ bool isAuth = false;
+ {
+ std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
+ if ((ah != headers.end())&&(_authToken == ah->second)) {
+ isAuth = true;
+ } else {
+ ah = urlArgs.find("auth");
+ if ((ah != urlArgs.end())&&(_authToken == ah->second))
+ isAuth = true;
+ }
+ }
+
+#ifdef __SYNOLOGY__
+ // Authenticate via Synology's built-in cgi script
+ if (!isAuth) {
+ /*
+ fprintf(stderr, "path = %s\n", path.c_str());
+ fprintf(stderr, "headers.size=%d\n", headers.size());
+ std::map<std::string, std::string>::const_iterator it(headers.begin());
+ while(it != headers.end()) {
+ fprintf(stderr,"header[%s] = %s\n", (it->first).c_str(), (it->second).c_str());
+ it++;
+ }
+ */
+ // parse out url args
+ int synotoken_pos = path.find("SynoToken");
+ int argpos = path.find("?");
+ if(synotoken_pos != std::string::npos && argpos != std::string::npos) {
+ std::string cookie = path.substr(argpos+1, synotoken_pos-(argpos+1));
+ std::string synotoken = path.substr(synotoken_pos);
+ std::string cookie_val = cookie.substr(cookie.find("=")+1);
+ std::string synotoken_val = synotoken.substr(synotoken.find("=")+1);
+ // Set necessary env for auth script
+ std::map<std::string,std::string>::const_iterator ah2(headers.find("x-forwarded-for"));
+ setenv("HTTP_COOKIE", cookie_val.c_str(), true);
+ setenv("HTTP_X_SYNO_TOKEN", synotoken_val.c_str(), true);
+ setenv("REMOTE_ADDR", ah2->second.c_str(),true);
+ //fprintf(stderr, "HTTP_COOKIE: %s\n",std::getenv ("HTTP_COOKIE"));
+ //fprintf(stderr, "HTTP_X_SYNO_TOKEN: %s\n",std::getenv ("HTTP_X_SYNO_TOKEN"));
+ //fprintf(stderr, "REMOTE_ADDR: %s\n",std::getenv ("REMOTE_ADDR"));
+ // check synology web auth
+ char user[256], buf[1024];
+ FILE *fp = NULL;
+ bzero(user, 256);
+ fp = popen("/usr/syno/synoman/webman/modules/authenticate.cgi", "r");
+ if(!fp)
+ isAuth = false;
+ else {
+ bzero(buf, sizeof(buf));
+ fread(buf, 1024, 1, fp);
+ if(strlen(buf) > 0) {
+ snprintf(user, 256, "%s", buf);
+ isAuth = true;
+ }
+ }
+ pclose(fp);
+ }
+ }
+#endif
+
+ if (httpMethod == HTTP_GET) {
+ if (isAuth) {
+ if (ps[0] == "status") {
+ ZT_NodeStatus status;
+ _node->status(&status);
+
+ Utils::snprintf(tmp,sizeof(tmp),"%.10llx",status.address);
+ res["address"] = tmp;
+ res["publicIdentity"] = status.publicIdentity;
+ res["online"] = (bool)(status.online != 0);
+ res["tcpFallbackActive"] = (_tcpFallbackTunnel != (TcpConnection *)0);
+ 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();
+
+ {
+ Mutex::Lock _l(_localConfig_m);
+ res["config"] = _localConfig;
+ }
+ json &settings = res["config"]["settings"];
+ settings["primaryPort"] = OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
+#ifdef ZT_USE_MINIUPNPC
+ settings["portMappingEnabled"] = OSUtils::jsonBool(settings["portMappingEnabled"],true);
+#else
+ settings["portMappingEnabled"] = false; // not supported in build
+#endif
+ settings["softwareUpdate"] = OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT);
+
+ const World planet(_node->planet());
+ res["planetWorldId"] = planet.id();
+ res["planetWorldTimestamp"] = planet.timestamp();
+
+#ifdef ZT_ENABLE_CLUSTER
+ json cj;
+ ZT_ClusterStatus cs;
+ _node->clusterStatus(&cs);
+ if (cs.clusterSize >= 1) {
+ json cja = json::array();
+ for(unsigned int i=0;i<cs.clusterSize;++i) {
+ 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"] = json();
+#endif
+
+ scode = 200;
+ } else if (ps[0] == "moon") {
+ std::vector<World> moons(_node->moons());
+ if (ps.size() == 1) {
+ // Return [array] of all moons
+
+ res = json::array();
+ for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
+ json mj;
+ _moonToJson(mj,*m);
+ res.push_back(mj);
+ }
+
+ scode = 200;
+ } 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
+
+ res = nlohmann::json::array();
+ for(unsigned long i=0;i<nws->networkCount;++i) {
+ OneService::NetworkSettings localSettings;
+ getNetworkSettings(nws->networks[i].nwid,localSettings);
+ nlohmann::json nj;
+ _networkToJson(nj,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
+ res.push_back(nj);
+ }
+
+ scode = 200;
+ } else if (ps.size() == 2) {
+ // Return a single network by ID or 404 if not found
+
+ 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) {
+ OneService::NetworkSettings localSettings;
+ getNetworkSettings(nws->networks[i].nwid,localSettings);
+ _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
+ scode = 200;
+ break;
+ }
+ }
+
+ } else scode = 404;
+ _node->freeQueryResult((void *)nws);
+ } else scode = 500;
+ } else if (ps[0] == "peer") {
+ ZT_PeerList *pl = _node->peers();
+ if (pl) {
+ if (ps.size() == 1) {
+ // Return [array] of all peers
+
+ res = nlohmann::json::array();
+ for(unsigned long i=0;i<pl->peerCount;++i) {
+ nlohmann::json pj;
+ _peerToJson(pj,&(pl->peers[i]));
+ res.push_back(pj);
+ }
+
+ 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) {
+ _peerToJson(res,&(pl->peers[i]));
+ scode = 200;
+ break;
+ }
+ }
+
+ } else scode = 404;
+ _node->freeQueryResult((void *)pl);
+ } else scode = 500;
+ } else {
+ if (_controller) {
+ scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
+ } else scode = 404;
+ }
+
+ } else scode = 401; // isAuth == false
+ } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
+ if (isAuth) {
+
+ if (ps[0] == "moon") {
+ if (ps.size() == 2) {
+
+ uint64_t seed = 0;
+ try {
+ json j(OSUtils::jsonParse(body));
+ if (j.is_object()) {
+ seed = Utils::hexStrToU64(OSUtils::jsonString(j["seed"],"0").c_str());
+ }
+ } 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)) {
+ char tmp[64];
+ Utils::snprintf(tmp,sizeof(tmp),"%.16llx",id);
+ res["id"] = tmp;
+ res["roots"] = json::array();
+ res["timestamp"] = 0;
+ res["signature"] = json();
+ res["updatesMustBeSignedBy"] = json();
+ res["waiting"] = true;
+ _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();
+ if (nws) {
+ for(unsigned long i=0;i<nws->networkCount;++i) {
+ if (nws->networks[i].nwid == wantnw) {
+ OneService::NetworkSettings localSettings;
+ getNetworkSettings(nws->networks[i].nwid,localSettings);
+
+ try {
+ json j(OSUtils::jsonParse(body));
+ if (j.is_object()) {
+ json &allowManaged = j["allowManaged"];
+ if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
+ json &allowGlobal = j["allowGlobal"];
+ if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
+ json &allowDefault = j["allowDefault"];
+ if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
+ }
+ } catch ( ... ) {
+ // discard invalid JSON
+ }
+
+ setNetworkSettings(nws->networks[i].nwid,localSettings);
+ _networkToJson(res,&(nws->networks[i]),portDeviceName(nws->networks[i].nwid),localSettings);
+
+ 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);
+ else scode = 404;
+ }
+
+ } else scode = 401; // isAuth == false
+ } else if (httpMethod == HTTP_DELETE) {
+ if (isAuth) {
+
+ 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) {
+ uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
+ for(unsigned long i=0;i<nws->networkCount;++i) {
+ if (nws->networks[i].nwid == wantnw) {
+ _node->leave(wantnw,(void **)0);
+ res["result"] = true;
+ scode = 200;
+ break;
+ }
+ }
+ } // else 404
+ _node->freeQueryResult((void *)nws);
+ } else scode = 500;
+ } else {
+ if (_controller)
+ scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
+ else scode = 404;
+ }
+
+ } else scode = 401; // isAuth = false
+ } else {
+ scode = 400;
+ }
+
+ 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.
+ // Also double-check isAuth since forbidding this without auth feels safer.
+ std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
+ if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
+ if (responseBody.length() > 0)
+ responseBody = jsonp->second + "(" + responseBody + ");";
+ else responseBody = jsonp->second + "(null);";
+ responseContentType = "application/javascript";
+ }
+
+ return scode;
+ }
+
+ // Must be called after _localConfig is read or modified
+ void applyLocalConfig()
+ {
+ Mutex::Lock _l(_localConfig_m);
+
+ _v4Hints.clear();
+ _v6Hints.clear();
+ _v4Blacklists.clear();
+ _v6Blacklists.clear();
+ json &virt = _localConfig["virtual"];
+ if (virt.is_object()) {
+ for(json::iterator v(virt.begin());v!=virt.end();++v) {
+ const std::string nstr = v.key();
+ if ((nstr.length() == ZT_ADDRESS_LENGTH_HEX)&&(v.value().is_object())) {
+ const Address ztaddr(Utils::hexStrToU64(nstr.c_str()));
+ if (ztaddr) {
+ const uint64_t ztaddr2 = ztaddr.toInt();
+ std::vector<InetAddress> &v4h = _v4Hints[ztaddr2];
+ std::vector<InetAddress> &v6h = _v6Hints[ztaddr2];
+ std::vector<InetAddress> &v4b = _v4Blacklists[ztaddr2];
+ std::vector<InetAddress> &v6b = _v6Blacklists[ztaddr2];
+
+ json &tryAddrs = v.value()["try"];
+ if (tryAddrs.is_array()) {
+ for(unsigned long i=0;i<tryAddrs.size();++i) {
+ const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
+ if (ip.ss_family == AF_INET)
+ v4h.push_back(ip);
+ else if (ip.ss_family == AF_INET6)
+ v6h.push_back(ip);
+ }
+ }
+ json &blAddrs = v.value()["blacklist"];
+ if (blAddrs.is_array()) {
+ for(unsigned long i=0;i<blAddrs.size();++i) {
+ const InetAddress ip(OSUtils::jsonString(tryAddrs[i],""));
+ if (ip.ss_family == AF_INET)
+ v4b.push_back(ip);
+ else if (ip.ss_family == AF_INET6)
+ v6b.push_back(ip);
+ }
+ }
+
+ if (v4h.empty()) _v4Hints.erase(ztaddr2);
+ if (v6h.empty()) _v6Hints.erase(ztaddr2);
+ if (v4b.empty()) _v4Blacklists.erase(ztaddr2);
+ if (v6b.empty()) _v6Blacklists.erase(ztaddr2);
+ }
+ }
+ }
+ }
+
+ _globalV4Blacklist.clear();
+ _globalV6Blacklist.clear();
+ json &physical = _localConfig["physical"];
+ if (physical.is_object()) {
+ for(json::iterator phy(physical.begin());phy!=physical.end();++phy) {
+ const InetAddress net(OSUtils::jsonString(phy.key(),""));
+ if ((net)&&(net.netmaskBits() > 0)) {
+ if (phy.value().is_object()) {
+ if (OSUtils::jsonBool(phy.value()["blacklist"],false)) {
+ if (net.ss_family == AF_INET)
+ _globalV4Blacklist.push_back(net);
+ else if (net.ss_family == AF_INET6)
+ _globalV6Blacklist.push_back(net);
+ }
+ }
+ }
+ }
+ }
+
+ _allowManagementFrom.clear();
+ _interfacePrefixBlacklist.clear();
+ json &settings = _localConfig["settings"];
+ if (settings.is_object()) {
+ _primaryPort = (unsigned int)OSUtils::jsonInt(settings["primaryPort"],(uint64_t)_primaryPort) & 0xffff;
+ _portMappingEnabled = OSUtils::jsonBool(settings["portMappingEnabled"],true);
+
+ const std::string up(OSUtils::jsonString(settings["softwareUpdate"],ZT_SOFTWARE_UPDATE_DEFAULT));
+ const bool udist = OSUtils::jsonBool(settings["softwareUpdateDist"],false);
+ if (((up == "apply")||(up == "download"))||(udist)) {
+ if (!_updater)
+ _updater = new SoftwareUpdater(*_node,_homePath);
+ _updateAutoApply = (up == "apply");
+ _updater->setUpdateDistribution(udist);
+ _updater->setChannel(OSUtils::jsonString(settings["softwareUpdateChannel"],ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL));
+ } else {
+ delete _updater;
+ _updater = (SoftwareUpdater *)0;
+ _updateAutoApply = false;
+ }
+
+ json &ignoreIfs = settings["interfacePrefixBlacklist"];
+ if (ignoreIfs.is_array()) {
+ for(unsigned long i=0;i<ignoreIfs.size();++i) {
+ const std::string tmp(OSUtils::jsonString(ignoreIfs[i],""));
+ if (tmp.length() > 0)
+ _interfacePrefixBlacklist.push_back(tmp);
+ }
+ }
+
+ json &amf = settings["allowManagementFrom"];
+ if (amf.is_array()) {
+ for(unsigned long i=0;i<amf.size();++i) {
+ const InetAddress nw(OSUtils::jsonString(amf[i],""));
+ if (nw)
+ _allowManagementFrom.push_back(nw);
+ }
+ }
+ }
+ }
// Checks if a managed IP or route target is allowed
bool checkIfManagedIsAllowed(const NetworkState &n,const InetAddress &target)
{
if (!n.settings.allowManaged)
return false;
+
+ if (n.settings.allowManagedWhitelist.size() > 0) {
+ bool allowed = false;
+ for (InetAddress addr : n.settings.allowManagedWhitelist) {
+ if (addr.containsAddress(target) && addr.netmaskBits() <= target.netmaskBits()) {
+ allowed = true;
+ break;
+ }
+ }
+ if (!allowed) return false;
+ }
+
if (target.isDefaultRoute())
return n.settings.allowDefault;
switch(target.ipScope()) {
@@ -1107,18 +1590,17 @@ public:
fprintf(stderr,"ERROR: unable to remove ip address %s" ZT_EOL_S, ip->toString().c_str());
}
}
- for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
#ifdef __SYNOLOGY__
- if (!n.tap->addIp(*ip))
- fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString().c_str());
+ if (!n.tap->addIpSyn(newManagedIps))
+ fprintf(stderr,"ERROR: unable to add ip addresses to ifcfg" ZT_EOL_S);
#else
+ for(std::vector<InetAddress>::iterator ip(newManagedIps.begin());ip!=newManagedIps.end();++ip) {
if (std::find(n.managedIps.begin(),n.managedIps.end(),*ip) == n.managedIps.end()) {
-
if (!n.tap->addIp(*ip))
fprintf(stderr,"ERROR: unable to add ip address %s" ZT_EOL_S, ip->toString().c_str());
- }
-#endif
+ }
}
+#endif
n.managedIps.swap(newManagedIps);
}
@@ -1191,6 +1673,10 @@ public:
}
}
+ // =========================================================================
+ // Handlers for Node and Phy<> callbacks
+ // =========================================================================
+
inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
{
#ifdef ZT_ENABLE_CLUSTER
@@ -1264,12 +1750,10 @@ public:
inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
{
- if ((!from)||(reinterpret_cast<const InetAddress *>(from)->ipScope() != InetAddress::IP_SCOPE_LOOPBACK)) {
- // Non-Loopback: deny (for now)
+ if (!from) {
_phy.close(sockN,false);
return;
} else {
- // Loopback == HTTP JSON API request
TcpConnection *tc = new TcpConnection();
_tcpConnections.insert(tc);
tc->type = TcpConnection::TCP_HTTP_INCOMING;
@@ -1450,9 +1934,32 @@ public:
if (OSUtils::readFile(nlcpath,nlcbuf)) {
Dictionary<4096> nc;
nc.load(nlcbuf.c_str());
- n.settings.allowManaged = nc.getB("allowManaged",true);
- n.settings.allowGlobal = nc.getB("allowGlobal",false);
- n.settings.allowDefault = nc.getB("allowDefault",false);
+ Buffer<1024> allowManaged;
+ if (nc.get("allowManaged", allowManaged) && allowManaged.size() != 0) {
+ std::string addresses (allowManaged.begin(), allowManaged.size());
+ if (allowManaged.size() <= 5) { // untidy parsing for backward compatibility
+ if (allowManaged[0] == '1' || allowManaged[0] == 't' || allowManaged[0] == 'T') {
+ n.settings.allowManaged = true;
+ } else {
+ n.settings.allowManaged = false;
+ }
+ } else {
+ // this should be a list of IP addresses
+ n.settings.allowManaged = true;
+ size_t pos = 0;
+ while (true) {
+ size_t nextPos = addresses.find(',', pos);
+ std::string address = addresses.substr(pos, (nextPos == std::string::npos ? addresses.size() : nextPos) - pos);
+ n.settings.allowManagedWhitelist.push_back(InetAddress(address));
+ if (nextPos == std::string::npos) break;
+ pos = nextPos + 1;
+ }
+ }
+ } else {
+ n.settings.allowManaged = true;
+ }
+ n.settings.allowGlobal = nc.getB("allowGlobal", false);
+ n.settings.allowDefault = nc.getB("allowDefault", false);
}
} catch (std::exception &exc) {
#ifdef __WINDOWS__
@@ -1475,6 +1982,16 @@ public:
case ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE:
memcpy(&(n.config),nwc,sizeof(ZT_VirtualNetworkConfig));
if (n.tap) { // sanity check
+#ifdef __WINDOWS__
+ // wait for up to 5 seconds for the WindowsEthernetTap to actually be initialized
+ //
+ // without WindowsEthernetTap::isInitialized() returning true, the won't actually
+ // be online yet and setting managed routes on it will fail.
+ const int MAX_SLEEP_COUNT = 500;
+ for (int i = 0; !n.tap->isInitialized() && i < MAX_SLEEP_COUNT; i++) {
+ Sleep(10);
+ }
+#endif
syncManagedStuff(n,true,true);
} else {
_nets.erase(nwid);
@@ -1526,6 +2043,13 @@ public:
}
} break;
+ case ZT_EVENT_USER_MESSAGE: {
+ const ZT_UserMessage *um = reinterpret_cast<const ZT_UserMessage *>(metaData);
+ if ((um->typeId == ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE)&&(_updater)) {
+ _updater->handleSoftwareUpdateUserMessage(um->origin,um->data,um->length);
+ }
+ } break;
+
default:
break;
}
@@ -1627,16 +2151,9 @@ public:
_tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
_tcpFallbackTunnel->writeBuf.append((const char *)data,len);
} else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
- std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
- if (tunnelIps.empty()) {
- if (!_tcpFallbackResolver.running())
- _tcpFallbackResolver.resolveNow();
- } else {
- bool connected = false;
- InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
- addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
- _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
- }
+ bool connected = false;
+ const InetAddress addr(ZT_TCP_FALLBACK_RELAY);
+ _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
}
}
_lastSendToGlobalV4 = now;
@@ -1670,30 +2187,74 @@ public:
n->tap->put(MAC(sourceMac),MAC(destMac),etherType,data,len);
}
- inline int nodePathCheckFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
+ inline int nodePathCheckFunction(uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
{
- Mutex::Lock _l(_nets_m);
-
- for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
- if (n->second.tap) {
- std::vector<InetAddress> ips(n->second.tap->ips());
- for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
- if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
- return 0;
+ // Make sure we're not trying to do ZeroTier-over-ZeroTier
+ {
+ Mutex::Lock _l(_nets_m);
+ for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
+ if (n->second.tap) {
+ std::vector<InetAddress> ips(n->second.tap->ips());
+ for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
+ if (i->containsAddress(*(reinterpret_cast<const InetAddress *>(remoteAddr)))) {
+ return 0;
+ }
}
}
}
}
-
+
/* Note: I do not think we need to scan for overlap with managed routes
* because of the "route forking" and interface binding that we do. This
* ensures (we hope) that ZeroTier traffic will still take the physical
* path even if its managed routes override this for other traffic. Will
- * revisit if we see problems with this. */
+ * revisit if we see recursion problems. */
+
+ // Check blacklists
+ const Hashtable< uint64_t,std::vector<InetAddress> > *blh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
+ const std::vector<InetAddress> *gbl = (const std::vector<InetAddress> *)0;
+ if (remoteAddr->ss_family == AF_INET) {
+ blh = &_v4Blacklists;
+ gbl = &_globalV4Blacklist;
+ } else if (remoteAddr->ss_family == AF_INET6) {
+ blh = &_v6Blacklists;
+ gbl = &_globalV6Blacklist;
+ }
+ if (blh) {
+ Mutex::Lock _l(_localConfig_m);
+ const std::vector<InetAddress> *l = blh->get(ztaddr);
+ if (l) {
+ for(std::vector<InetAddress>::const_iterator a(l->begin());a!=l->end();++a) {
+ if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
+ return 0;
+ }
+ }
+ for(std::vector<InetAddress>::const_iterator a(gbl->begin());a!=gbl->end();++a) {
+ if (a->containsAddress(*reinterpret_cast<const InetAddress *>(remoteAddr)))
+ return 0;
+ }
+ }
return 1;
}
+ inline int nodePathLookupFunction(uint64_t ztaddr,int family,struct sockaddr_storage *result)
+ {
+ const Hashtable< uint64_t,std::vector<InetAddress> > *lh = (const Hashtable< uint64_t,std::vector<InetAddress> > *)0;
+ if (family < 0)
+ lh = (_node->prng() & 1) ? &_v4Hints : &_v6Hints;
+ else if (family == AF_INET)
+ lh = &_v4Hints;
+ else if (family == AF_INET6)
+ lh = &_v6Hints;
+ else return 0;
+ const std::vector<InetAddress> *l = lh->get(ztaddr);
+ if ((l)&&(l->size() > 0)) {
+ memcpy(result,&((*l)[(unsigned long)_node->prng() % l->size()]),sizeof(struct sockaddr_storage));
+ return 1;
+ } else return 0;
+ }
+
inline void tapFrameHandler(uint64_t nwid,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
{
_node->processVirtualNetworkFrame(OSUtils::now(),nwid,from.toInt(),to.toInt(),etherType,vlanId,data,len,&_nextBackgroundTaskDeadline);
@@ -1706,16 +2267,34 @@ public:
std::string contentType("text/plain"); // default if not changed in handleRequest()
unsigned int scode = 404;
- try {
- if (_controlPlane)
- scode = _controlPlane->handleRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
- else scode = 500;
- } catch (std::exception &exc) {
- fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
- scode = 500;
- } catch ( ... ) {
- fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exceptino" ZT_EOL_S);
- scode = 500;
+ bool allow;
+ {
+ Mutex::Lock _l(_localConfig_m);
+ if (_allowManagementFrom.size() == 0) {
+ allow = (tc->from.ipScope() == InetAddress::IP_SCOPE_LOOPBACK);
+ } else {
+ allow = false;
+ for(std::vector<InetAddress>::const_iterator i(_allowManagementFrom.begin());i!=_allowManagementFrom.end();++i) {
+ if (i->containsAddress(tc->from)) {
+ allow = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if (allow) {
+ try {
+ scode = handleControlPlaneHttpRequest(tc->from,tc->parser.method,tc->url,tc->headers,tc->body,data,contentType);
+ } catch (std::exception &exc) {
+ fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: %s" ZT_EOL_S,exc.what());
+ scode = 500;
+ } catch ( ... ) {
+ fprintf(stderr,"WARNING: unexpected exception processing control HTTP request: unknown exceptino" ZT_EOL_S);
+ scode = 500;
+ }
+ } else {
+ scode = 401;
}
const char *scodestr;
@@ -1757,16 +2336,38 @@ public:
bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
{
- if (isBlacklistedLocalInterfaceForZeroTierTraffic(ifname))
- return false;
+#if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
+ if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
+ if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
+ if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
+ if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
+#endif
- Mutex::Lock _l(_nets_m);
- for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
- if (n->second.tap) {
- std::vector<InetAddress> ips(n->second.tap->ips());
- for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
- if (i->ipsEqual(ifaddr))
- return false;
+#ifdef __APPLE__
+ if ((ifname[0] == 'l')&&(ifname[1] == 'o')) return false; // loopback
+ if ((ifname[0] == 'z')&&(ifname[1] == 't')) return false; // sanity check: zt#
+ if ((ifname[0] == 't')&&(ifname[1] == 'u')&&(ifname[2] == 'n')) return false; // tun# is probably an OpenVPN tunnel or similar
+ if ((ifname[0] == 't')&&(ifname[1] == 'a')&&(ifname[2] == 'p')) return false; // tap# is probably an OpenVPN tunnel or similar
+ if ((ifname[0] == 'u')&&(ifname[1] == 't')&&(ifname[2] == 'u')&&(ifname[3] == 'n')) return false; // ... as is utun#
+#endif
+
+ {
+ Mutex::Lock _l(_localConfig_m);
+ for(std::vector<std::string>::const_iterator p(_interfacePrefixBlacklist.begin());p!=_interfacePrefixBlacklist.end();++p) {
+ if (!strncmp(p->c_str(),ifname,p->length()))
+ return false;
+ }
+ }
+
+ {
+ Mutex::Lock _l(_nets_m);
+ for(std::map<uint64_t,NetworkState>::const_iterator n(_nets.begin());n!=_nets.end();++n) {
+ if (n->second.tap) {
+ std::vector<InetAddress> ips(n->second.tap->ips());
+ for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
+ if (i->ipsEqual(ifaddr))
+ return false;
+ }
}
}
}
@@ -1839,8 +2440,10 @@ static int SnodeWirePacketSendFunction(ZT_Node *node,void *uptr,const struct soc
{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodeWirePacketSendFunction(localAddr,addr,data,len,ttl); }
static void SnodeVirtualNetworkFrameFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
{ reinterpret_cast<OneServiceImpl *>(uptr)->nodeVirtualNetworkFrameFunction(nwid,nuptr,sourceMac,destMac,etherType,vlanId,data,len); }
-static int SnodePathCheckFunction(ZT_Node *node,void *uptr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
-{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(localAddr,remoteAddr); }
+static int SnodePathCheckFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,const struct sockaddr_storage *localAddr,const struct sockaddr_storage *remoteAddr)
+{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathCheckFunction(ztaddr,localAddr,remoteAddr); }
+static int SnodePathLookupFunction(ZT_Node *node,void *uptr,uint64_t ztaddr,int family,struct sockaddr_storage *result)
+{ return reinterpret_cast<OneServiceImpl *>(uptr)->nodePathLookupFunction(ztaddr,family,result); }
#ifdef ZT_ENABLE_CLUSTER
static void SclusterSendFunction(void *uptr,unsigned int toMemberId,const void *data,unsigned int len)
@@ -1956,30 +2559,6 @@ std::string OneService::platformDefaultHomePath()
return OSUtils::platformDefaultHomePath();
}
-std::string OneService::autoUpdateUrl()
-{
-#ifdef ZT_AUTO_UPDATE
-
-/*
-#if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
- if (sizeof(void *) == 8)
- return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
- else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
-#endif
-*/
-
-#if defined(__APPLE__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
- return "http://download.zerotier.com/update/mac_intel/";
-#endif
-
-#ifdef __WINDOWS__
- return "http://download.zerotier.com/update/win_intel/";
-#endif
-
-#endif // ZT_AUTO_UPDATE
- return std::string();
-}
-
OneService *OneService::newInstance(const char *hp,unsigned int port) { return new OneServiceImpl(hp,port); }
OneService::~OneService() {}