More CAPI work, and move old control/ and old node/Node to attic.

This commit is contained in:
Adam Ierymenko 2015-03-31 13:54:50 -07:00
commit 2c5dbecb3c
13 changed files with 380 additions and 394 deletions

949
attic/Node.cpp Normal file
View file

@ -0,0 +1,949 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <map>
#include <set>
#include <utility>
#include <algorithm>
#include <list>
#include <vector>
#include <string>
#include "Constants.hpp"
#ifdef __WINDOWS__
#include <WinSock2.h>
#include <Windows.h>
#include <ShlObj.h>
#else
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/file.h>
#endif
#include "../version.h"
#include "Node.hpp"
#include "RuntimeEnvironment.hpp"
#include "Logger.hpp"
#include "Utils.hpp"
#include "Defaults.hpp"
#include "Identity.hpp"
#include "Topology.hpp"
#include "SocketManager.hpp"
#include "Packet.hpp"
#include "Switch.hpp"
#include "EthernetTap.hpp"
#include "CMWC4096.hpp"
#include "NodeConfig.hpp"
#include "Network.hpp"
#include "MulticastGroup.hpp"
#include "Multicaster.hpp"
#include "Mutex.hpp"
#include "SoftwareUpdater.hpp"
#include "Buffer.hpp"
#include "AntiRecursion.hpp"
#include "HttpClient.hpp"
#include "NetworkConfigMaster.hpp"
namespace ZeroTier {
struct _NodeImpl
{
RuntimeEnvironment renv;
std::string reasonForTerminationStr;
volatile Node::ReasonForTermination reasonForTermination;
volatile bool started;
volatile bool running;
volatile bool resynchronize;
volatile bool disableRootTopologyUpdates;
std::string overrideRootTopology;
// This function performs final node tear-down
inline Node::ReasonForTermination terminate()
{
RuntimeEnvironment *RR = &renv;
LOG("terminating: %s",reasonForTerminationStr.c_str());
running = false;
delete renv.updater; renv.updater = (SoftwareUpdater *)0;
delete renv.nc; renv.nc = (NodeConfig *)0; // shut down all networks, close taps, etc.
delete renv.topology; renv.topology = (Topology *)0; // now we no longer need routing info
delete renv.mc; renv.mc = (Multicaster *)0;
delete renv.antiRec; renv.antiRec = (AntiRecursion *)0;
delete renv.sw; renv.sw = (Switch *)0; // order matters less from here down
delete renv.http; renv.http = (HttpClient *)0;
delete renv.prng; renv.prng = (CMWC4096 *)0;
delete renv.log; renv.log = (Logger *)0; // but stop logging last of all
return reasonForTermination;
}
inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
{
reasonForTerminationStr = rstr;
reasonForTermination = r;
return terminate();
}
};
Node::Node(
const char *hp,
EthernetTapFactory *tf,
SocketManager *sm,
NetworkConfigMaster *nm,
bool resetIdentity,
const char *overrideRootTopology) throw() :
_impl(new _NodeImpl)
{
_NodeImpl *impl = (_NodeImpl *)_impl;
if ((hp)&&(hp[0]))
impl->renv.homePath = hp;
else impl->renv.homePath = ZT_DEFAULTS.defaultHomePath;
impl->renv.tapFactory = tf;
impl->renv.sm = sm;
impl->renv.netconfMaster = nm;
if (resetIdentity) {
// Forget identity and peer database, peer keys, etc.
Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "peers.persist").c_str());
// Truncate network config information in networks.d but leave the files since we
// still want to remember any networks we have joined. This will force those networks
// to be reconfigured with our newly regenerated identity after startup.
std::string networksDotD(impl->renv.homePath + ZT_PATH_SEPARATOR_S + "networks.d");
std::map< std::string,bool > nwfiles(Utils::listDirectory(networksDotD.c_str()));
for(std::map<std::string,bool>::iterator nwf(nwfiles.begin());nwf!=nwfiles.end();++nwf) {
FILE *trun = fopen((networksDotD + ZT_PATH_SEPARATOR_S + nwf->first).c_str(),"w");
if (trun)
fclose(trun);
}
}
impl->reasonForTermination = Node::NODE_RUNNING;
impl->started = false;
impl->running = false;
impl->resynchronize = false;
if (overrideRootTopology) {
impl->disableRootTopologyUpdates = true;
impl->overrideRootTopology = overrideRootTopology;
} else {
impl->disableRootTopologyUpdates = false;
}
}
Node::~Node()
{
delete (_NodeImpl *)_impl;
}
static void _CBztTraffic(const SharedPtr<Socket> &fromSock,void *arg,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
{
((const RuntimeEnvironment *)arg)->sw->onRemotePacket(fromSock,from,data);
}
static void _cbHandleGetRootTopology(void *arg,int code,const std::string &url,const std::string &body)
{
RuntimeEnvironment *RR = (RuntimeEnvironment *)arg;
if ((code != 200)||(body.length() == 0)) {
TRACE("failed to retrieve %s",url.c_str());
return;
}
try {
Dictionary rt(body);
if (!Topology::authenticateRootTopology(rt)) {
LOG("discarded invalid root topology update from %s (signature check failed)",url.c_str());
return;
}
{
std::string rootTopologyPath(RR->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
std::string rootTopology;
if (Utils::readFile(rootTopologyPath.c_str(),rootTopology)) {
Dictionary alreadyHave(rootTopology);
if (alreadyHave == rt) {
TRACE("retrieved root topology from %s but no change (same as on disk)",url.c_str());
return;
} else if (alreadyHave.signatureTimestamp() > rt.signatureTimestamp()) {
TRACE("retrieved root topology from %s but no change (ours is newer)",url.c_str());
return;
}
}
Utils::writeFile(rootTopologyPath.c_str(),body);
}
RR->topology->setSupernodes(Dictionary(rt.get("supernodes")));
} catch ( ... ) {
LOG("discarded invalid root topology update from %s (format invalid)",url.c_str());
return;
}
}
Node::ReasonForTermination Node::run()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
impl->started = true;
impl->running = true;
try {
#ifdef ZT_LOG_STDOUT
RR->log = new Logger((const char *)0,(const char *)0,0);
#else
RR->log = new Logger((RR->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
#endif
LOG("starting version %s",versionString());
// Create non-crypto PRNG right away in case other code in init wants to use it
RR->prng = new CMWC4096();
// Read identity public and secret, generating if not present
{
bool gotId = false;
std::string identitySecretPath(RR->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
std::string identityPublicPath(RR->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
std::string idser;
if (Utils::readFile(identitySecretPath.c_str(),idser))
gotId = RR->identity.fromString(idser);
if ((gotId)&&(!RR->identity.locallyValidate()))
gotId = false;
if (gotId) {
// Make sure identity.public matches identity.secret
idser = std::string();
Utils::readFile(identityPublicPath.c_str(),idser);
std::string pubid(RR->identity.toString(false));
if (idser != pubid) {
if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
}
} else {
LOG("no identity found or identity invalid, generating one... this might take a few seconds...");
RR->identity.generate();
LOG("generated new identity: %s",RR->identity.address().toString().c_str());
idser = RR->identity.toString(true);
if (!Utils::writeFile(identitySecretPath.c_str(),idser))
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
idser = RR->identity.toString(false);
if (!Utils::writeFile(identityPublicPath.c_str(),idser))
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
}
Utils::lockDownFile(identitySecretPath.c_str(),false);
}
// Make sure networks.d exists (used by NodeConfig to remember networks)
{
std::string networksDotD(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
#ifdef __WINDOWS__
CreateDirectoryA(networksDotD.c_str(),NULL);
#else
mkdir(networksDotD.c_str(),0700);
#endif
}
// Make sure iddb.d exists (used by Topology to remember identities)
{
std::string iddbDotD(RR->homePath + ZT_PATH_SEPARATOR_S + "iddb.d");
#ifdef __WINDOWS__
CreateDirectoryA(iddbDotD.c_str(),NULL);
#else
mkdir(iddbDotD.c_str(),0700);
#endif
}
RR->http = new HttpClient();
RR->sw = new Switch(RR);
RR->mc = new Multicaster(RR);
RR->antiRec = new AntiRecursion();
RR->topology = new Topology(RR);
try {
RR->nc = new NodeConfig(RR);
} catch (std::exception &exc) {
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unable to initialize IPC socket: is ZeroTier One already running?");
}
RR->node = this;
#ifdef ZT_AUTO_UPDATE
if (ZT_DEFAULTS.updateLatestNfoURL.length()) {
RR->updater = new SoftwareUpdater(RR);
RR->updater->cleanOldUpdates(); // clean out updates.d on startup
} else {
LOG("WARNING: unable to enable software updates: latest .nfo URL from ZT_DEFAULTS is empty (does this platform actually support software updates?)");
}
#endif
// Initialize root topology from defaults or root-toplogy file in home path on disk
if (impl->overrideRootTopology.length() == 0) {
std::string rootTopologyPath(RR->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
std::string rootTopology;
if (!Utils::readFile(rootTopologyPath.c_str(),rootTopology))
rootTopology = ZT_DEFAULTS.defaultRootTopology;
try {
Dictionary rt(rootTopology);
if (Topology::authenticateRootTopology(rt)) {
// Set supernodes if root topology signature is valid
RR->topology->setSupernodes(Dictionary(rt.get("supernodes",""))); // set supernodes from root-topology
// If root-topology contains noupdate=1, disable further updates and only use what was on disk
impl->disableRootTopologyUpdates = (Utils::strToInt(rt.get("noupdate","0").c_str()) > 0);
} else {
// Revert to built-in defaults if root topology fails signature check
LOG("%s failed signature check, using built-in defaults instead",rootTopologyPath.c_str());
Utils::rm(rootTopologyPath.c_str());
RR->topology->setSupernodes(Dictionary(Dictionary(ZT_DEFAULTS.defaultRootTopology).get("supernodes","")));
impl->disableRootTopologyUpdates = false;
}
} catch ( ... ) {
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"invalid root-topology format");
}
} else {
try {
Dictionary rt(impl->overrideRootTopology);
RR->topology->setSupernodes(Dictionary(rt.get("supernodes","")));
impl->disableRootTopologyUpdates = true;
} catch ( ... ) {
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"invalid root-topology format");
}
}
// Delete peers.persist if it exists -- legacy file, just takes up space
Utils::rm(std::string(RR->homePath + ZT_PATH_SEPARATOR_S + "peers.persist").c_str());
} catch (std::bad_alloc &exc) {
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
} catch (std::runtime_error &exc) {
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
} catch ( ... ) {
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
}
// Core I/O loop
try {
/* Shut down if this file exists but fails to open. This is used on Mac to
* shut down automatically on .app deletion by symlinking this to the
* Info.plist file inside the ZeroTier One application. This causes the
* service to die when the user throws away the app, allowing uninstallation
* in the natural Mac way. */
std::string shutdownIfUnreadablePath(RR->homePath + ZT_PATH_SEPARATOR_S + "shutdownIfUnreadable");
uint64_t lastNetworkAutoconfCheck = Utils::now() - 5000ULL; // check autoconf again after 5s for startup
uint64_t lastPingCheck = 0;
uint64_t lastClean = Utils::now(); // don't need to do this immediately
uint64_t lastMulticastCheck = 0;
uint64_t lastSupernodePingCheck = 0;
uint64_t lastBeacon = 0;
uint64_t lastRootTopologyFetch = 0;
uint64_t lastShutdownIfUnreadableCheck = 0;
long lastDelayDelta = 0;
RR->timeOfLastResynchronize = Utils::now();
// We are up and running
RR->initialized = true;
while (impl->reasonForTermination == NODE_RUNNING) {
uint64_t now = Utils::now();
bool resynchronize = false;
/* This is how the service automatically shuts down when the OSX .app is
* thrown in the trash. It's not used on any other platform for now but
* could do similar things. It's disabled on Windows since it doesn't really
* work there. */
#ifdef __UNIX_LIKE__
if ((now - lastShutdownIfUnreadableCheck) > 10000) {
lastShutdownIfUnreadableCheck = now;
if (Utils::fileExists(shutdownIfUnreadablePath.c_str(),false)) {
int tmpfd = ::open(shutdownIfUnreadablePath.c_str(),O_RDONLY,0);
if (tmpfd < 0) {
return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"shutdownIfUnreadable exists but is not readable");
} else ::close(tmpfd);
}
}
#endif
// If it looks like the computer slept and woke, resynchronize.
if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
resynchronize = true;
LOG("probable suspend/resume detected, pausing a moment for things to settle...");
Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
}
// Supernodes do not resynchronize unless explicitly ordered via SIGHUP.
if ((resynchronize)&&(RR->topology->amSupernode()))
resynchronize = false;
// Check for SIGHUP / force resync.
if (impl->resynchronize) {
impl->resynchronize = false;
resynchronize = true;
LOG("resynchronize forced by user, syncing with network");
}
if (resynchronize) {
RR->tcpTunnelingEnabled = false; // turn off TCP tunneling master switch at first, will be reenabled on persistent UDP failure
RR->timeOfLastResynchronize = now;
}
/* Supernodes are pinged separately and more aggressively. The
* ZT_STARTUP_AGGRO parameter sets a limit on how rapidly they are
* tried, while PingSupernodesThatNeedPing contains the logic for
* determining if they need PING. */
if ((now - lastSupernodePingCheck) >= ZT_STARTUP_AGGRO) {
lastSupernodePingCheck = now;
uint64_t lastReceiveFromAnySupernode = 0; // function object result paramter
RR->topology->eachSupernodePeer(Topology::FindMostRecentDirectReceiveTimestamp(lastReceiveFromAnySupernode));
// Turn on TCP tunneling master switch if we haven't heard anything since before
// the last resynchronize and we've been trying long enough.
uint64_t tlr = RR->timeOfLastResynchronize;
if ((lastReceiveFromAnySupernode < tlr)&&((now - tlr) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT)) {
TRACE("network still unreachable after %u ms, TCP TUNNELING ENABLED",(unsigned int)ZT_TCP_TUNNEL_FAILOVER_TIMEOUT);
RR->tcpTunnelingEnabled = true;
}
RR->topology->eachSupernodePeer(Topology::PingSupernodesThatNeedPing(RR,now));
}
if (resynchronize) {
RR->sm->closeTcpSockets();
} else {
/* Periodically check for changes in our local multicast subscriptions
* and broadcast those changes to directly connected peers. */
if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
lastMulticastCheck = now;
try {
std::vector< SharedPtr<Network> > networks(RR->nc->networks());
for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw)
(*nw)->rescanMulticastGroups();
} catch (std::exception &exc) {
LOG("unexpected exception announcing multicast groups: %s",exc.what());
} catch ( ... ) {
LOG("unexpected exception announcing multicast groups: (unknown)");
}
}
/* Periodically ping all our non-stale direct peers unless we're a supernode.
* Supernodes only ping each other (which is done above). */
if ((!RR->topology->amSupernode())&&((now - lastPingCheck) >= ZT_PING_CHECK_DELAY)) {
lastPingCheck = now;
try {
RR->topology->eachPeer(Topology::PingPeersThatNeedPing(RR,now));
} catch (std::exception &exc) {
LOG("unexpected exception running ping check cycle: %s",exc.what());
} catch ( ... ) {
LOG("unexpected exception running ping check cycle: (unkonwn)");
}
}
}
// Update network configurations when needed.
try {
if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
lastNetworkAutoconfCheck = now;
std::vector< SharedPtr<Network> > nets(RR->nc->networks());
for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
(*n)->requestConfiguration();
}
}
} catch ( ... ) {
LOG("unexpected exception updating network configurations (non-fatal, will retry)");
}
// Do periodic tasks in submodules.
if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
lastClean = now;
try {
RR->topology->clean(now);
} catch ( ... ) {
LOG("unexpected exception in Topology::clean() (non-fatal)");
}
try {
RR->mc->clean(now);
} catch ( ... ) {
LOG("unexpected exception in Multicaster::clean() (non-fatal)");
}
try {
RR->nc->clean();
} catch ( ... ) {
LOG("unexpected exception in NodeConfig::clean() (non-fatal)");
}
try {
if (RR->updater)
RR->updater->checkIfMaxIntervalExceeded(now);
} catch ( ... ) {
LOG("unexpected exception in SoftwareUpdater::checkIfMaxIntervalExceeded() (non-fatal)");
}
}
// Send beacons to physical local LANs
try {
if ((resynchronize)||((now - lastBeacon) >= ZT_BEACON_INTERVAL)) {
lastBeacon = now;
char bcn[ZT_PROTO_BEACON_LENGTH];
void *bcnptr = bcn;
*((uint32_t *)(bcnptr)) = RR->prng->next32();
bcnptr = bcn + 4;
*((uint32_t *)(bcnptr)) = RR->prng->next32();
RR->identity.address().copyTo(bcn + ZT_PROTO_BEACON_IDX_ADDRESS,ZT_ADDRESS_LENGTH);
TRACE("sending LAN beacon to %s",ZT_DEFAULTS.v4Broadcast.toString().c_str());
RR->antiRec->logOutgoingZT(bcn,ZT_PROTO_BEACON_LENGTH);
RR->sm->send(ZT_DEFAULTS.v4Broadcast,false,false,bcn,ZT_PROTO_BEACON_LENGTH);
}
} catch ( ... ) {
LOG("unexpected exception sending LAN beacon (non-fatal)");
}
// Check for updates to root topology (supernodes) periodically
try {
if ((now - lastRootTopologyFetch) >= ZT_UPDATE_ROOT_TOPOLOGY_CHECK_INTERVAL) {
lastRootTopologyFetch = now;
if (!impl->disableRootTopologyUpdates) {
TRACE("fetching root topology from %s",ZT_DEFAULTS.rootTopologyUpdateURL.c_str());
RR->http->GET(ZT_DEFAULTS.rootTopologyUpdateURL,HttpClient::NO_HEADERS,60,&_cbHandleGetRootTopology,RR);
}
}
} catch ( ... ) {
LOG("unexpected exception attempting to check for root topology updates (non-fatal)");
}
// Sleep for loop interval or until something interesting happens.
try {
unsigned long delay = std::min((unsigned long)ZT_MAX_SERVICE_LOOP_INTERVAL,RR->sw->doTimerTasks());
uint64_t start = Utils::now();
RR->sm->poll(delay,&_CBztTraffic,RR);
lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
} catch (std::exception &exc) {
LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
} catch ( ... ) {
LOG("unexpected exception running Switch doTimerTasks: (unknown)");
}
}
} catch ( ... ) {
LOG("FATAL: unexpected exception in core loop: unknown exception");
return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
}
return impl->terminate();
}
const char *Node::terminationMessage() const
throw()
{
if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
return (const char *)0;
return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
}
void Node::terminate(ReasonForTermination reason,const char *reasonText)
throw()
{
((_NodeImpl *)_impl)->reasonForTermination = reason;
((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
((_NodeImpl *)_impl)->renv.sm->whack();
}
void Node::resync()
throw()
{
((_NodeImpl *)_impl)->resynchronize = true;
((_NodeImpl *)_impl)->renv.sm->whack();
}
bool Node::online()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if ((!RR)||(!RR->initialized))
return false;
uint64_t now = Utils::now();
uint64_t since = RR->timeOfLastResynchronize;
std::vector< SharedPtr<Peer> > snp(RR->topology->supernodePeers());
for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
uint64_t lastRec = (*sn)->lastDirectReceive();
if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
return true;
}
return false;
}
bool Node::started()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
return impl->started;
}
bool Node::running()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
return impl->running;
}
bool Node::initialized()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
return ((RR)&&(RR->initialized));
}
uint64_t Node::address()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if ((!RR)||(!RR->initialized))
return 0;
return RR->identity.address().toInt();
}
void Node::join(uint64_t nwid)
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if ((RR)&&(RR->initialized))
RR->nc->join(nwid);
}
void Node::leave(uint64_t nwid)
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if ((RR)&&(RR->initialized))
RR->nc->leave(nwid);
}
struct GatherPeerStatistics
{
uint64_t now;
ZT1_Node_Status *status;
inline void operator()(Topology &t,const SharedPtr<Peer> &p)
{
++status->knownPeers;
if (p->hasActiveDirectPath(now))
++status->directlyConnectedPeers;
if (p->alive(now))
++status->alivePeers;
}
};
void Node::status(ZT1_Node_Status *status)
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
memset(status,0,sizeof(ZT1_Node_Status));
if ((!RR)||(!RR->initialized))
return;
Utils::scopy(status->publicIdentity,sizeof(status->publicIdentity),RR->identity.toString(false).c_str());
RR->identity.address().toString(status->address,sizeof(status->address));
status->rawAddress = RR->identity.address().toInt();
status->knownPeers = 0;
status->supernodes = RR->topology->numSupernodes();
status->directlyConnectedPeers = 0;
status->alivePeers = 0;
GatherPeerStatistics gps;
gps.now = Utils::now();
gps.status = status;
RR->topology->eachPeer<GatherPeerStatistics &>(gps);
if (status->alivePeers > 0) {
double dlsr = (double)status->directlyConnectedPeers / (double)status->alivePeers;
if (dlsr > 1.0) dlsr = 1.0;
if (dlsr < 0.0) dlsr = 0.0;
status->directLinkSuccessRate = (float)dlsr;
} else status->directLinkSuccessRate = 1.0f; // no connections to no active peers == 100% success at nothing
status->online = online();
status->running = impl->running;
status->initialized = true;
}
struct CollectPeersAndPaths
{
std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > > data;
inline void operator()(Topology &t,const SharedPtr<Peer> &p) { this->data.push_back(std::pair< SharedPtr<Peer>,std::vector<Path> >(p,p->paths())); }
};
struct SortPeersAndPathsInAscendingAddressOrder
{
inline bool operator()(const std::pair< SharedPtr<Peer>,std::vector<Path> > &a,const std::pair< SharedPtr<Peer>,std::vector<Path> > &b) const { return (a.first->address() < b.first->address()); }
};
ZT1_Node_PeerList *Node::listPeers()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if ((!RR)||(!RR->initialized))
return (ZT1_Node_PeerList *)0;
CollectPeersAndPaths pp;
RR->topology->eachPeer<CollectPeersAndPaths &>(pp);
std::sort(pp.data.begin(),pp.data.end(),SortPeersAndPathsInAscendingAddressOrder());
unsigned int returnBufSize = sizeof(ZT1_Node_PeerList);
for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p)
returnBufSize += sizeof(ZT1_Node_Peer) + (sizeof(ZT1_Node_PhysicalPath) * (unsigned int)p->second.size());
char *buf = (char *)::malloc(returnBufSize);
if (!buf)
return (ZT1_Node_PeerList *)0;
memset(buf,0,returnBufSize);
ZT1_Node_PeerList *pl = (ZT1_Node_PeerList *)buf;
buf += sizeof(ZT1_Node_PeerList);
pl->peers = (ZT1_Node_Peer *)buf;
buf += (sizeof(ZT1_Node_Peer) * pp.data.size());
pl->numPeers = 0;
uint64_t now = Utils::now();
for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p) {
ZT1_Node_Peer *prec = &(pl->peers[pl->numPeers++]);
if (p->first->remoteVersionKnown())
Utils::snprintf(prec->remoteVersion,sizeof(prec->remoteVersion),"%u.%u.%u",p->first->remoteVersionMajor(),p->first->remoteVersionMinor(),p->first->remoteVersionRevision());
p->first->address().toString(prec->address,sizeof(prec->address));
prec->rawAddress = p->first->address().toInt();
prec->latency = p->first->latency();
prec->role = RR->topology->isSupernode(p->first->address()) ? ZT1_Node_Peer_SUPERNODE : ZT1_Node_Peer_NODE;
prec->paths = (ZT1_Node_PhysicalPath *)buf;
buf += sizeof(ZT1_Node_PhysicalPath) * p->second.size();
prec->numPaths = 0;
for(std::vector<Path>::iterator pi(p->second.begin());pi!=p->second.end();++pi) {
ZT1_Node_PhysicalPath *path = &(prec->paths[prec->numPaths++]);
path->type = (ZT1_Node_PhysicalPathType)pi->type();
if (pi->address().isV6()) {
path->address.type = ZT1_Node_PhysicalAddress_TYPE_IPV6;
memcpy(path->address.bits,pi->address().rawIpData(),16);
// TODO: zoneIndex not supported yet, but should be once echo-location works w/V6
} else {
path->address.type = ZT1_Node_PhysicalAddress_TYPE_IPV4;
memcpy(path->address.bits,pi->address().rawIpData(),4);
}
path->address.port = pi->address().port();
Utils::scopy(path->address.ascii,sizeof(path->address.ascii),pi->address().toIpString().c_str());
path->lastSend = (pi->lastSend() > 0) ? ((long)(now - pi->lastSend())) : (long)-1;
path->lastReceive = (pi->lastReceived() > 0) ? ((long)(now - pi->lastReceived())) : (long)-1;
path->lastPing = (pi->lastPing() > 0) ? ((long)(now - pi->lastPing())) : (long)-1;
path->active = pi->active(now);
path->fixed = pi->fixed();
}
}
return pl;
}
// Fills out everything but ips[] and numIps, which must be done more manually
static void _fillNetworkQueryResultBuffer(const SharedPtr<Network> &network,const SharedPtr<NetworkConfig> &nconf,ZT1_Node_Network *nbuf)
{
nbuf->nwid = network->id();
Utils::snprintf(nbuf->nwidHex,sizeof(nbuf->nwidHex),"%.16llx",(unsigned long long)network->id());
if (nconf) {
Utils::scopy(nbuf->name,sizeof(nbuf->name),nconf->name().c_str());
Utils::scopy(nbuf->description,sizeof(nbuf->description),nconf->description().c_str());
}
Utils::scopy(nbuf->device,sizeof(nbuf->device),network->tapDeviceName().c_str());
Utils::scopy(nbuf->statusStr,sizeof(nbuf->statusStr),Network::statusString(network->status()));
network->mac().toString(nbuf->macStr,sizeof(nbuf->macStr));
network->mac().copyTo(nbuf->mac,sizeof(nbuf->mac));
uint64_t lcu = network->lastConfigUpdate();
if (lcu > 0)
nbuf->configAge = (long)(Utils::now() - lcu);
else nbuf->configAge = -1;
nbuf->status = (ZT1_Node_NetworkStatus)network->status();
nbuf->enabled = network->enabled();
nbuf->isPrivate = (nconf) ? nconf->isPrivate() : true;
}
ZT1_Node_Network *Node::getNetworkStatus(uint64_t nwid)
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if ((!RR)||(!RR->initialized))
return (ZT1_Node_Network *)0;
SharedPtr<Network> network(RR->nc->network(nwid));
if (!network)
return (ZT1_Node_Network *)0;
SharedPtr<NetworkConfig> nconf(network->config2());
std::set<InetAddress> ips(network->ips());
char *buf = (char *)::malloc(sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
if (!buf)
return (ZT1_Node_Network *)0;
memset(buf,0,sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
ZT1_Node_Network *nbuf = (ZT1_Node_Network *)buf;
buf += sizeof(ZT1_Node_Network);
_fillNetworkQueryResultBuffer(network,nconf,nbuf);
nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
nbuf->numIps = 0;
for(std::set<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
if (ip->isV6()) {
ipb->type = ZT1_Node_PhysicalAddress_TYPE_IPV6;
memcpy(ipb->bits,ip->rawIpData(),16);
} else {
ipb->type = ZT1_Node_PhysicalAddress_TYPE_IPV4;
memcpy(ipb->bits,ip->rawIpData(),4);
}
ipb->port = ip->port();
Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
}
return nbuf;
}
ZT1_Node_NetworkList *Node::listNetworks()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if ((!RR)||(!RR->initialized))
return (ZT1_Node_NetworkList *)0;
std::vector< SharedPtr<Network> > networks(RR->nc->networks());
std::vector< SharedPtr<NetworkConfig> > nconfs(networks.size());
std::vector< std::set<InetAddress> > ipsv(networks.size());
unsigned long returnBufSize = sizeof(ZT1_Node_NetworkList);
for(unsigned long i=0;i<networks.size();++i) {
nconfs[i] = networks[i]->config2(); // note: can return NULL
ipsv[i] = networks[i]->ips();
returnBufSize += sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * (unsigned int)ipsv[i].size());
}
char *buf = (char *)::malloc(returnBufSize);
if (!buf)
return (ZT1_Node_NetworkList *)0;
memset(buf,0,returnBufSize);
ZT1_Node_NetworkList *nl = (ZT1_Node_NetworkList *)buf;
buf += sizeof(ZT1_Node_NetworkList);
nl->networks = (ZT1_Node_Network *)buf;
buf += sizeof(ZT1_Node_Network) * networks.size();
for(unsigned long i=0;i<networks.size();++i) {
ZT1_Node_Network *nbuf = &(nl->networks[nl->numNetworks++]);
_fillNetworkQueryResultBuffer(networks[i],nconfs[i],nbuf);
nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
buf += sizeof(ZT1_Node_PhysicalAddress) * ipsv[i].size();
nbuf->numIps = 0;
for(std::set<InetAddress>::iterator ip(ipsv[i].begin());ip!=ipsv[i].end();++ip) {
ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
if (ip->isV6()) {
ipb->type = ZT1_Node_PhysicalAddress_TYPE_IPV6;
memcpy(ipb->bits,ip->rawIpData(),16);
} else {
ipb->type = ZT1_Node_PhysicalAddress_TYPE_IPV4;
memcpy(ipb->bits,ip->rawIpData(),4);
}
ipb->port = ip->port();
Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
}
}
return nl;
}
void Node::freeQueryResult(void *qr)
throw()
{
if (qr)
::free(qr);
}
bool Node::updateCheck()
throw()
{
_NodeImpl *impl = (_NodeImpl *)_impl;
RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
if (RR->updater) {
RR->updater->checkNow();
return true;
}
return false;
}
class _VersionStringMaker
{
public:
char vs[32];
_VersionStringMaker()
{
Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
}
~_VersionStringMaker() {}
};
static const _VersionStringMaker __versionString;
const char *Node::versionString() throw() { return __versionString.vs; }
unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
} // namespace ZeroTier

245
attic/Node.hpp Normal file
View file

@ -0,0 +1,245 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_NODE_HPP
#define ZT_NODE_HPP
#include <stdint.h>
#include "../include/ZeroTierOne.h"
namespace ZeroTier {
class EthernetTapFactory;
class RoutingTable;
class SocketManager;
class NetworkConfigMaster;
/**
* A ZeroTier One node
*/
class Node
{
public:
/**
* Returned by node main if/when it terminates
*/
enum ReasonForTermination
{
/**
* Node is currently in run()
*/
NODE_RUNNING = 0,
/**
* Node is shutting down for normal reasons, including a signal
*/
NODE_NORMAL_TERMINATION = 1,
/**
* An upgrade is available. Its path is in reasonForTermination().
*/
NODE_RESTART_FOR_UPGRADE = 2,
/**
* A serious unrecoverable error has occurred.
*/
NODE_UNRECOVERABLE_ERROR = 3,
/**
* An address collision occurred (typically this should cause re-invocation with resetIdentity set to true)
*/
NODE_ADDRESS_COLLISION = 4
};
/**
* Create a new node
*
* The node is not executed until run() is called. The supplied tap factory
* and routing table must not be freed until the node is no longer
* executing. Node does not delete these objects; the caller still owns
* them.
*
* @param hp Home directory path or NULL for system-wide default for this platform
* @param tf Ethernet tap factory for platform network stack
* @param sm Socket manager for physical network I/O
* @param nm Network configuration master or NULL for none
* @param resetIdentity If true, delete identity before starting and regenerate
* @param overrideRootTopology Override root topology with this dictionary (in string serialized format) and do not update (default: NULL for none)
*/
Node(
const char *hp,
EthernetTapFactory *tf,
SocketManager *sm,
NetworkConfigMaster *nm,
bool resetIdentity,
const char *overrideRootTopology = (const char *)0) throw();
~Node();
/**
* Execute node in current thread, return on shutdown
*
* @return Reason for termination
*/
ReasonForTermination run()
throw();
/**
* Obtain a human-readable reason for node termination
*
* @return Reason for node termination or NULL if run() has not returned
*/
const char *terminationMessage() const
throw();
/**
* Terminate this node, causing run() to return
*
* @param reason Reason for termination
* @param reasonText Text to be returned by terminationMessage()
*/
void terminate(ReasonForTermination reason,const char *reasonText)
throw();
/**
* Forget p2p links now and resynchronize with peers
*
* This can be used if the containing application knows its network environment has
* changed. ZeroTier itself tries to detect such changes, but is not always successful.
*/
void resync()
throw();
/**
* @return True if we appear to be online in some viable capacity
*/
bool online()
throw();
/**
* @return True if run() has been called
*/
bool started()
throw();
/**
* @return True if run() has not yet returned
*/
bool running()
throw();
/**
* @return True if initialization phase of startup is complete
*/
bool initialized()
throw();
/**
* @return This node's address (in least significant 40 bits of 64-bit int) or 0 if not yet initialized
*/
uint64_t address()
throw();
/**
* Join a network
*
* Use getNetworkStatus() to check the network's status after joining. If you
* are already a member of the network, this does nothing.
*
* @param nwid 64-bit network ID
*/
void join(uint64_t nwid)
throw();
/**
* Leave a network (if a member)
*
* @param nwid 64-bit network ID
*/
void leave(uint64_t nwid)
throw();
/**
* Get the status of this node
*
* @param status Buffer to fill with status information
*/
void status(ZT1_Node_Status *status)
throw();
/**
* @return List of known peers or NULL on failure
*/
ZT1_Node_PeerList *listPeers()
throw();
/**
* @param nwid 64-bit network ID
* @return Network status or NULL if we are not a member of this network
*/
ZT1_Node_Network *getNetworkStatus(uint64_t nwid)
throw();
/**
* @return List of networks we've joined or NULL on failure
*/
ZT1_Node_NetworkList *listNetworks()
throw();
/**
* Free a query result buffer
*
* Use this to free the return values of listNetworks(), listPeers(), etc.
*
* @param qr Query result buffer
*/
void freeQueryResult(void *qr)
throw();
/**
* Check for software updates (if enabled) (updates will eventually get factored out of node/)
*/
bool updateCheck()
throw();
static const char *versionString() throw();
static unsigned int versionMajor() throw();
static unsigned int versionMinor() throw();
static unsigned int versionRevision() throw();
private:
// Nodes are not copyable
Node(const Node&);
const Node& operator=(const Node&);
void *const _impl; // private implementation
};
} // namespace ZeroTier
#endif

View file

@ -0,0 +1,281 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <stdexcept>
#include "IpcConnection.hpp"
#ifndef __WINDOWS__
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <sys/select.h>
#endif
namespace ZeroTier {
IpcConnection::IpcConnection(const char *endpoint,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
_handler(commandHandler),
_arg(arg),
_timeout(timeout),
#ifdef __WINDOWS__
_sock(INVALID_HANDLE_VALUE),
_incoming(false),
#else
_sock(-1),
#endif
_run(true),
_running(true)
{
#ifdef __WINDOWS__
_sock = CreateFileA(endpoint,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_EXISTING,0,NULL);
if (_sock == INVALID_HANDLE_VALUE)
throw std::runtime_error("IPC endpoint unreachable");
DWORD pipeMode = PIPE_READMODE_BYTE;
SetNamedPipeHandleState(_sock,&pipeMode,NULL,NULL);
#else
struct sockaddr_un unaddr;
unaddr.sun_family = AF_UNIX;
strncpy(unaddr.sun_path,endpoint,sizeof(unaddr.sun_path));
unaddr.sun_path[sizeof(unaddr.sun_path) - 1] = (char)0;
_sock = socket(AF_UNIX,SOCK_STREAM,0);
if (_sock <= 0)
throw std::runtime_error("unable to create socket of type AF_UNIX");
if (connect(_sock,(struct sockaddr *)&unaddr,sizeof(unaddr))) {
::close(_sock);
throw std::runtime_error("IPC endpoint unreachable");
}
#endif
_thread = Thread::start(this);
}
#ifdef __WINDOWS__
IpcConnection::IpcConnection(HANDLE s,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
#else
IpcConnection::IpcConnection(int s,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
#endif
_handler(commandHandler),
_arg(arg),
_timeout(timeout),
_sock(s),
#ifdef __WINDOWS__
_incoming(true),
#endif
_run(true),
_running(true)
{
_thread = Thread::start(this);
}
IpcConnection::~IpcConnection()
{
_writeLock.lock();
_run = false;
_writeLock.unlock();
#ifdef __WINDOWS__
while (_running) {
Thread::cancelIO(_thread); // cause Windows to break from blocking read and detect shutdown
Sleep(100);
}
#else // !__WINDOWS__
int s = _sock;
_sock = 0;
if (s > 0) {
::shutdown(s,SHUT_RDWR);
::close(s);
}
Thread::join(_thread);
#endif // __WINDOWS__ / !__WINDOWS__
}
void IpcConnection::printf(const char *format,...)
{
va_list ap;
int n;
char tmp[65536];
va_start(ap,format);
n = (int)::vsnprintf(tmp,sizeof(tmp),format,ap);
va_end(ap);
if (n <= 0)
return;
Mutex::Lock _l(_writeLock);
#ifdef __WINDOWS__
_writeBuf.append(tmp,n);
Thread::cancelIO(_thread); // cause Windows to break from blocking read and service write buffer
#else
if (_sock > 0)
::write(_sock,tmp,n);
#endif
}
void IpcConnection::threadMain()
throw()
{
char tmp[16384];
char linebuf[16384];
unsigned int lineptr = 0;
char c;
#ifdef __WINDOWS__
DWORD n,i;
std::string wbuf;
#else // !__WINDOWS__
int s,n,i;
fd_set readfds,writefds,errorfds;
struct timeval tout;
#ifdef SO_NOSIGPIPE
if (_sock > 0) {
i = 1;
::setsockopt(_sock,SOL_SOCKET,SO_NOSIGPIPE,(char *)&i,sizeof(i));
}
#endif // SO_NOSIGPIPE
#endif // __WINDOWS__ / !__WINDOWS__
while (_run) {
#ifdef __WINDOWS__
/* Note that we do not use fucking timeouts in Windows, since it does seem
* to properly detect named pipe endpoint close. But we do use a write buffer
* because Windows won't let you divorce reading and writing threads without
* all that OVERLAPPED cruft. */
{
Mutex::Lock _l(_writeLock);
if (!_run)
break;
if (_writeBuf.length() > 0) {
wbuf.append(_writeBuf);
_writeBuf.clear();
}
}
if (wbuf.length() > 0) {
n = 0;
if ((WriteFile(_sock,wbuf.data(),(DWORD)(wbuf.length()),&n,NULL))&&(n > 0)) {
if (n < (DWORD)wbuf.length())
wbuf.erase(0,n);
else wbuf.clear();
} else if (GetLastError() != ERROR_OPERATION_ABORTED)
break;
FlushFileBuffers(_sock);
}
if (!_run)
break;
n = 0;
if ((!ReadFile(_sock,tmp,sizeof(tmp),&n,NULL))||(n <= 0)) {
if (GetLastError() == ERROR_OPERATION_ABORTED)
n = 0;
else break;
}
if (!_run)
break;
#else // !__WINDOWS__
/* So today I learned that there is no reliable way to detect a half-closed
* Unix domain socket. So to make sure we don't leave orphaned sockets around
* we just use fucking timeouts. If a socket fucking times out, we break from
* the I/O loop and terminate the thread. But this IpcConnection code is ugly
* so maybe the OS is simply offended by it and refuses to reveal its mysteries
* to me. Oh well... this IPC code will probably get canned when we go to
* local HTTP RESTful interfaces or soemthing like that. */
if ((s = _sock) <= 0)
break;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&errorfds);
FD_SET(s,&readfds);
FD_SET(s,&errorfds);
tout.tv_sec = _timeout; // use a fucking timeout
tout.tv_usec = 0;
if (select(s+1,&readfds,&writefds,&errorfds,&tout) <= 0) {
break; // socket has fucking timed out
} else {
if (FD_ISSET(s,&errorfds))
break; // socket has an exception... sometimes works
else {
n = (int)::read(s,tmp,sizeof(tmp));
if ((n <= 0)||(_sock <= 0))
break; // read returned error... sometimes works
}
}
#endif // __WINDOWS__ / !__WINDOWS__
for(i=0;i<n;++i) {
c = (linebuf[lineptr] = tmp[i]);
if ((c == '\r')||(c == '\n')||(c == (char)0)||(lineptr == (sizeof(linebuf) - 1))) {
if (lineptr) {
linebuf[lineptr] = (char)0;
_handler(_arg,this,IPC_EVENT_COMMAND,linebuf);
lineptr = 0;
}
} else ++lineptr;
}
}
_writeLock.lock();
bool r = _run;
_writeLock.unlock();
#ifdef __WINDOWS__
if (_incoming)
DisconnectNamedPipe(_sock);
CloseHandle(_sock);
_running = false;
#endif // __WINDOWS__
if (r)
_handler(_arg,this,IPC_EVENT_CONNECTION_CLOSED,(const char *)0);
}
} // namespace ZeroTier

View file

@ -0,0 +1,107 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_IPCCONNECTION_HPP
#define ZT_IPCCONNECTION_HPP
#include "../node/Constants.hpp"
#include "../node/Thread.hpp"
#include "../node/NonCopyable.hpp"
#include "../node/Mutex.hpp"
#ifdef __WINDOWS__
#include <WinSock2.h>
#include <Windows.h>
#endif
namespace ZeroTier {
class IpcListener;
/**
* Interprocess communication connection
*/
class IpcConnection : NonCopyable
{
friend class IpcListener;
public:
enum EventType
{
IPC_EVENT_COMMAND,
IPC_EVENT_NEW_CONNECTION,
IPC_EVENT_CONNECTION_CLOSED
};
/**
* Connect to an IPC endpoint
*
* @param endpoint Endpoint path
* @param timeout Inactivity timeout in seconds
* @param commandHandler Command handler function
* @param arg First argument to command handler
* @throws std::runtime_error Unable to connect
*/
IpcConnection(const char *endpoint,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg);
~IpcConnection();
/**
* @param format Printf format string
* @param ... Printf arguments
*/
void printf(const char *format,...);
void threadMain()
throw();
private:
// Used by IpcListener to construct incoming connections
#ifdef __WINDOWS__
IpcConnection(HANDLE s,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg);
#else
IpcConnection(int s,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg);
#endif
void (*_handler)(void *,IpcConnection *,IpcConnection::EventType,const char *);
void *_arg;
unsigned int _timeout;
#ifdef __WINDOWS__
HANDLE _sock;
std::string _writeBuf;
bool _incoming;
#else
volatile int _sock;
#endif
Mutex _writeLock;
Thread _thread;
volatile bool _run;
volatile bool _running;
};
} // namespace ZeroTier
#endif

View file

@ -0,0 +1,165 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2014 ZeroTier Networks LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "IpcListener.hpp"
#ifndef __WINDOWS__
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
namespace ZeroTier {
IpcListener::IpcListener(const char *ep,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
_endpoint(ep),
_handler(commandHandler),
_arg(arg),
_timeout(timeout),
#ifdef __WINDOWS__
_run(true),
_running(true)
#else
_sock(0)
#endif
{
#ifndef __WINDOWS__
struct sockaddr_un unaddr;
unaddr.sun_family = AF_UNIX;
strncpy(unaddr.sun_path,_endpoint.c_str(),sizeof(unaddr.sun_path));
unaddr.sun_path[sizeof(unaddr.sun_path) - 1] = (char)0;
struct stat stattmp;
if (stat(_endpoint.c_str(),&stattmp)) {
int testSock = socket(AF_UNIX,SOCK_STREAM,0);
if (testSock <= 0)
throw std::runtime_error("unable to create socket of type AF_UNIX");
if (connect(testSock,(struct sockaddr *)&unaddr,sizeof(unaddr))) {
// error means nothing is listening, orphaned name
::close(testSock);
} else {
// success means endpoint is being actively listened to by a process
::close(testSock);
throw std::runtime_error("IPC endpoint address in use");
}
}
::unlink(_endpoint.c_str());
_sock = socket(AF_UNIX,SOCK_STREAM,0);
if (_sock <= 0)
throw std::runtime_error("unable to create socket of type AF_UNIX");
if (bind(_sock,(struct sockaddr *)&unaddr,sizeof(unaddr))) {
::close(_sock);
throw std::runtime_error("IPC endpoint could not be bound");
}
if (listen(_sock,8)) {
::close(_sock);
throw std::runtime_error("listen() failed for bound AF_UNIX socket");
}
::chmod(_endpoint.c_str(),0777);
#endif
_thread = Thread::start(this);
}
IpcListener::~IpcListener()
{
#ifdef __WINDOWS__
_run = false;
while (_running) {
Thread::cancelIO(_thread);
HANDLE tmp = CreateFileA(_endpoint.c_str(),GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_EXISTING,0,NULL);
if (tmp != INVALID_HANDLE_VALUE)
CloseHandle(tmp);
Sleep(250);
}
#else
int s = _sock;
_sock = 0;
if (s > 0) {
::shutdown(s,SHUT_RDWR);
::close(s);
}
Thread::join(_thread);
::unlink(_endpoint.c_str());
#endif
}
void IpcListener::threadMain()
throw()
{
#ifdef __WINDOWS__
HANDLE s;
while (_run) {
s = CreateNamedPipeA(_endpoint.c_str(),PIPE_ACCESS_DUPLEX,PIPE_READMODE_BYTE|PIPE_TYPE_BYTE|PIPE_WAIT,PIPE_UNLIMITED_INSTANCES,1024,1024,0,NULL);
if (s != INVALID_HANDLE_VALUE) {
if ((ConnectNamedPipe(s,NULL))||(GetLastError() == ERROR_PIPE_CONNECTED)) {
if (!_run) {
DisconnectNamedPipe(s);
CloseHandle(s);
break;
}
try {
_handler(_arg,new IpcConnection(s,_timeout,_handler,_arg),IpcConnection::IPC_EVENT_NEW_CONNECTION,(const char *)0);
} catch ( ... ) {} // handlers should not throw
} else {
CloseHandle(s);
}
}
}
_running = false;
#else
struct sockaddr_un unaddr;
socklen_t socklen;
int s;
while (_sock > 0) {
unaddr.sun_family = AF_UNIX;
strncpy(unaddr.sun_path,_endpoint.c_str(),sizeof(unaddr.sun_path));
unaddr.sun_path[sizeof(unaddr.sun_path) - 1] = (char)0;
socklen = sizeof(unaddr);
s = accept(_sock,(struct sockaddr *)&unaddr,&socklen);
if (s <= 0)
break;
if (!_sock) {
::close(s);
break;
}
try {
_handler(_arg,new IpcConnection(s,_timeout,_handler,_arg),IpcConnection::IPC_EVENT_NEW_CONNECTION,(const char *)0);
} catch ( ... ) {} // handlers should not throw
}
#endif
}
} // namespace ZeroTier

View file

@ -0,0 +1,91 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2014 ZeroTier Networks LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_IPCLISTENER_HPP
#define ZT_IPCLISTENER_HPP
#include "../node/Constants.hpp"
#include "../node/Thread.hpp"
#include "../node/NonCopyable.hpp"
#include "IpcConnection.hpp"
#include <string>
#include <stdexcept>
namespace ZeroTier {
/**
* IPC incoming connection listener (Unix domain sockets or named pipes on Windows)
*/
class IpcListener : NonCopyable
{
public:
/**
* Listen for IPC connections
*
* The supplied handler is passed on to incoming instances of IpcConnection. When
* a connection is first opened, it is called with IPC_EVENT_NEW_CONNECTION. The
* receiver must take ownership of the connection object. When a connection is
* closed, IPC_EVENT_CONNECTION_CLOSED is generated. At this point (or after) the
* receiver must delete the object. IPC_EVENT_COMMAND is generated when lines of
* text are read, and in this cases the last argument is not NULL. No closed event
* is generated in the event of manual delete if the connection is still open.
*
* Yeah, this whole callback model sort of sucks. Might rethink and replace with
* some kind of actor model or something if it gets too unweildy. But for now the
* use cases are simple enough that it's not too bad.
*
* @param IPC endpoint name (OS-specific)
* @param timeout Endpoint inactivity timeout in seconds
* @param commandHandler Function to call for each command
* @param arg First argument to pass to handler
* @throws std::runtime_error Unable to bind to endpoint
*/
IpcListener(const char *ep,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg);
~IpcListener();
void threadMain()
throw();
private:
std::string _endpoint;
void (*_handler)(void *,IpcConnection *,IpcConnection::EventType,const char *);
void *_arg;
unsigned int _timeout;
#ifdef __WINDOWS__
volatile bool _run;
volatile bool _running;
#else
volatile int _sock;
#endif
Thread _thread;
};
} // namespace ZeroTier
#endif

View file

@ -0,0 +1,167 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include "NodeControlClient.hpp"
#include "../node/Constants.hpp"
#include "../node/Utils.hpp"
#include "../node/Defaults.hpp"
#include "IpcConnection.hpp"
#include "IpcListener.hpp"
#include "NodeControlService.hpp"
#ifdef __WINDOWS__
#include <WinSock2.h>
#include <Windows.h>
#include <tchar.h>
#include <wchar.h>
#include <ShlObj.h>
#endif // __WINDOWS__
namespace ZeroTier {
struct _NodeControlClientImpl
{
void (*resultHandler)(void *,const char *);
void *arg;
bool ignoreNextBreak;
IpcConnection *ipcc;
std::string err;
};
static void _CBipcResultHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *result)
{
if ((event == IpcConnection::IPC_EVENT_COMMAND)&&(result)) {
if (!strcmp(result,"200 auth OK")) {
((_NodeControlClientImpl *)arg)->ignoreNextBreak = true;
} else if ((((_NodeControlClientImpl *)arg)->ignoreNextBreak)&&(!strcmp(result,"."))) {
((_NodeControlClientImpl *)arg)->ignoreNextBreak = false;
} else ((_NodeControlClientImpl *)arg)->resultHandler(((_NodeControlClientImpl *)arg)->arg,result);
}
}
NodeControlClient::NodeControlClient(const char *ep,const char *authToken,void (*resultHandler)(void *,const char *),void *arg)
throw() :
_impl((void *)new _NodeControlClientImpl)
{
_NodeControlClientImpl *impl = (_NodeControlClientImpl *)_impl;
impl->resultHandler = resultHandler;
impl->arg = arg;
impl->ignoreNextBreak = false;
try {
impl->ipcc = new IpcConnection(ep,ZT_IPC_TIMEOUT,&_CBipcResultHandler,_impl);
impl->ipcc->printf("auth %s"ZT_EOL_S,authToken);
} catch ( ... ) {
impl->ipcc = (IpcConnection *)0;
impl->err = "failure connecting to running ZeroTier One service";
}
}
NodeControlClient::~NodeControlClient()
{
if (_impl) {
delete ((_NodeControlClientImpl *)_impl)->ipcc;
delete (_NodeControlClientImpl *)_impl;
}
}
const char *NodeControlClient::error() const
throw()
{
if (((_NodeControlClientImpl *)_impl)->err.length())
return ((_NodeControlClientImpl *)_impl)->err.c_str();
return (const char *)0;
}
void NodeControlClient::send(const char *command)
throw()
{
try {
if (((_NodeControlClientImpl *)_impl)->ipcc)
((_NodeControlClientImpl *)_impl)->ipcc->printf("%s"ZT_EOL_S,command);
} catch ( ... ) {}
}
std::vector<std::string> NodeControlClient::splitLine(const char *line)
{
return Utils::split(line," ","\\","\"");
}
const char *NodeControlClient::authTokenDefaultUserPath()
{
static std::string dlp;
static Mutex dlp_m;
Mutex::Lock _l(dlp_m);
#ifdef __WINDOWS__
if (!dlp.length()) {
char buf[16384];
if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_APPDATA,NULL,0,buf)))
dlp = (std::string(buf) + "\\ZeroTier\\One\\authtoken.secret");
}
#else // not __WINDOWS__
if (!dlp.length()) {
const char *home = getenv("HOME");
if (home) {
#ifdef __APPLE__
dlp = (std::string(home) + "/Library/Application Support/ZeroTier/One/authtoken.secret");
#else
dlp = (std::string(home) + "/.zeroTierOneAuthToken");
#endif
}
}
#endif // __WINDOWS__ or not __WINDOWS__
return dlp.c_str();
}
std::string NodeControlClient::getAuthToken(const char *path,bool generateIfNotFound)
{
unsigned char randbuf[24];
std::string token;
if (Utils::readFile(path,token))
return Utils::trim(token);
else token = "";
if (generateIfNotFound) {
Utils::getSecureRandom(randbuf,sizeof(randbuf));
for(unsigned int i=0;i<sizeof(randbuf);++i)
token.push_back(("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")[(unsigned int)randbuf[i] % 62]);
if (!Utils::writeFile(path,token))
return std::string();
Utils::lockDownFile(path,false);
}
return token;
}
} // namespace ZeroTier

View file

@ -0,0 +1,118 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_NODECONTROLCLIENT_HPP
#define ZT_NODECONTROLCLIENT_HPP
#include <string>
#include <vector>
#include "../node/Constants.hpp"
#ifdef __WINDOWS__
#define ZT_IPC_ENDPOINT_BASE "\\\\.\\pipe\\ZeroTierOne-"
#else
#define ZT_IPC_ENDPOINT_BASE "/tmp/.ZeroTierOne-"
#endif
namespace ZeroTier {
/**
* Client for controlling a local ZeroTier One node
*/
class NodeControlClient
{
public:
/**
* Create a new node config client
*
* Initialization may fail. Call error() to check.
*
* @param ep Endpoint to connect to (OS-dependent)
* @param resultHandler Function to call when commands provide results
* @param arg First argument to result handler
*/
NodeControlClient(const char *ep,const char *authToken,void (*resultHandler)(void *,const char *),void *arg)
throw();
~NodeControlClient();
/**
* @return Initialization error or NULL if none
*/
const char *error() const
throw();
/**
* Send a command to the local node
*
* Note that the returned conversation ID will never be 0. A return value
* of 0 indicates a fatal error such as failure to bind to any local UDP
* port.
*
* @param command
* @return Conversation ID that will be provided to result handler when/if results are sent back
*/
void send(const char *command)
throw();
inline void send(const std::string &command)
throw() { return send(command.c_str()); }
/**
* Split a line of results
*
* @param line Line to split
* @return Vector of fields
*/
static std::vector<std::string> splitLine(const char *line);
static inline std::vector<std::string> splitLine(const std::string &line) { return splitLine(line.c_str()); }
/**
* @return Default path for current user's authtoken.secret or ~/.zeroTierOneAuthToken (location is platform-dependent)
*/
static const char *authTokenDefaultUserPath();
/**
* Load (or generate) the authentication token
*
* @param path Full path to authtoken.secret
* @param generateIfNotFound If true, generate and save if not found or readable (requires appropriate privileges, returns empty on failure)
* @return Authentication token or empty string on failure
*/
static std::string getAuthToken(const char *path,bool generateIfNotFound);
private:
// NodeControlClient is not copyable
NodeControlClient(const NodeControlClient&);
const NodeControlClient& operator=(const NodeControlClient&);
void *_impl;
};
} // namespace ZeroTier
#endif

View file

@ -0,0 +1,250 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "NodeControlService.hpp"
#include "NodeControlClient.hpp"
#include "../node/Constants.hpp"
#include "../node/MAC.hpp"
#include "../node/Node.hpp"
#include "../node/Utils.hpp"
namespace ZeroTier {
NodeControlService::NodeControlService(Node *node,const char *authToken) :
_node(node),
_listener((IpcListener *)0),
_authToken(authToken),
_running(true),
_thread(Thread::start(this))
{
}
NodeControlService::~NodeControlService()
{
_running = false;
Thread::join(_thread);
{
Mutex::Lock _l(_connections_m);
for(std::map< IpcConnection *,bool >::iterator c(_connections.begin());c!=_connections.end();++c)
delete c->first;
_connections.clear();
}
delete _listener;
}
void NodeControlService::threadMain()
throw()
{
char tmp[1024];
try {
while (_running) {
if (!_node->running()) {
if (_node->started())
break;
} else if ((_node->initialized())&&(_node->address())) {
Utils::snprintf(tmp,sizeof(tmp),"%s%.10llx",ZT_IPC_ENDPOINT_BASE,(unsigned long long)_node->address());
_listener = new IpcListener(tmp,ZT_IPC_TIMEOUT,&_CBcommandHandler,this);
break;
}
Thread::sleep(100); // wait for Node to start
}
} catch ( ... ) {
delete _listener;
_listener = (IpcListener *)0;
}
}
void NodeControlService::_CBcommandHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *commandLine)
{
switch(event) {
case IpcConnection::IPC_EVENT_COMMAND: {
if ((!((NodeControlService *)arg)->_running)||(!commandLine)||(!commandLine[0]))
return;
((NodeControlService *)arg)->_doCommand(ipcc,commandLine);
} break;
case IpcConnection::IPC_EVENT_NEW_CONNECTION: {
Mutex::Lock _l(((NodeControlService *)arg)->_connections_m);
((NodeControlService *)arg)->_connections[ipcc] = false; // not yet authenticated
} break;
case IpcConnection::IPC_EVENT_CONNECTION_CLOSED: {
Mutex::Lock _l(((NodeControlService *)arg)->_connections_m);
((NodeControlService *)arg)->_connections.erase(ipcc);
delete ipcc;
} break;
}
}
void NodeControlService::_doCommand(IpcConnection *ipcc,const char *commandLine)
{
std::vector<std::string> r;
std::vector<std::string> cmd(Utils::split(commandLine,"\r\n \t","\\","'"));
if ((cmd.empty())||(cmd[0] == "help")) {
ipcc->printf("200 help help"ZT_EOL_S);
ipcc->printf("200 help auth <token>"ZT_EOL_S);
ipcc->printf("200 help info"ZT_EOL_S);
ipcc->printf("200 help listpeers"ZT_EOL_S);
ipcc->printf("200 help listnetworks"ZT_EOL_S);
ipcc->printf("200 help join <network ID>"ZT_EOL_S);
ipcc->printf("200 help leave <network ID>"ZT_EOL_S);
ipcc->printf("200 help terminate [<reason>]"ZT_EOL_S);
ipcc->printf("200 help updatecheck"ZT_EOL_S);
} else if (cmd[0] == "auth") {
if ((cmd.size() > 1)&&(_authToken.length() > 0)&&(_authToken == cmd[1])) {
Mutex::Lock _l(_connections_m);
_connections[ipcc] = true;
ipcc->printf("200 auth OK"ZT_EOL_S);
} else ipcc->printf("403 auth failed"ZT_EOL_S);
} else {
{
Mutex::Lock _l(_connections_m);
if (!_connections[ipcc]) {
ipcc->printf("403 %s unauthorized"ZT_EOL_S"."ZT_EOL_S,cmd[0].c_str());
return;
}
}
if (cmd[0] == "info") {
ipcc->printf("200 info %.10llx %s %s"ZT_EOL_S,_node->address(),(_node->online() ? "ONLINE" : "OFFLINE"),Node::versionString());
} else if (cmd[0] == "listpeers") {
ipcc->printf("200 listpeers <ztaddr> <paths> <latency> <version> <role>"ZT_EOL_S);
ZT1_Node_PeerList *pl = _node->listPeers();
if (pl) {
for(unsigned int i=0;i<pl->numPeers;++i) {
ipcc->printf("200 listpeers %.10llx ",(unsigned long long)pl->peers[i].rawAddress);
if (pl->peers[i].numPaths == 0)
ipcc->printf("-");
else {
for(unsigned int j=0;j<pl->peers[i].numPaths;++j) {
if (j > 0)
ipcc->printf(",");
switch(pl->peers[i].paths[j].type) {
default:
ipcc->printf("unknown;");
break;
case ZT1_Node_PhysicalPath_TYPE_UDP:
ipcc->printf("udp;");
break;
case ZT1_Node_PhysicalPath_TYPE_TCP_OUT:
ipcc->printf("tcp_out;");
break;
case ZT1_Node_PhysicalPath_TYPE_TCP_IN:
ipcc->printf("tcp_in;");
break;
case ZT1_Node_PhysicalPath_TYPE_ETHERNET:
ipcc->printf("eth;");
break;
}
ipcc->printf("%s/%d;%ld;%ld;%ld;%s",
pl->peers[i].paths[j].address.ascii,
(int)pl->peers[i].paths[j].address.port,
pl->peers[i].paths[j].lastSend,
pl->peers[i].paths[j].lastReceive,
pl->peers[i].paths[j].lastPing,
(pl->peers[i].paths[j].fixed ? "fixed" : (pl->peers[i].paths[j].active ? "active" : "inactive")));
}
}
const char *rolestr;
switch(pl->peers[i].role) {
case ZT1_Node_Peer_SUPERNODE: rolestr = "SUPERNODE"; break;
case ZT1_Node_Peer_HUB: rolestr = "HUB"; break;
case ZT1_Node_Peer_NODE: rolestr = "NODE"; break;
default: rolestr = "?"; break;
}
ipcc->printf(" %u %s %s"ZT_EOL_S,
pl->peers[i].latency,
((pl->peers[i].remoteVersion[0]) ? pl->peers[i].remoteVersion : "-"),
rolestr);
}
_node->freeQueryResult(pl);
}
} else if (cmd[0] == "listnetworks") {
ipcc->printf("200 listnetworks <nwid> <name> <mac> <status> <config age> <type> <dev> <ips>"ZT_EOL_S);
ZT1_Node_NetworkList *nl = _node->listNetworks();
if (nl) {
for(unsigned int i=0;i<nl->numNetworks;++i) {
ipcc->printf("200 listnetworks %s %s %s %s %ld %s %s ",
nl->networks[i].nwidHex,
nl->networks[i].name,
nl->networks[i].macStr,
nl->networks[i].statusStr,
nl->networks[i].configAge,
(nl->networks[i].isPrivate ? "private" : "public"),
nl->networks[i].device);
if (nl->networks[i].numIps > 0) {
for(unsigned int j=0;j<nl->networks[i].numIps;++j) {
if (j > 0)
ipcc->printf(",");
ipcc->printf("%s/%d",nl->networks[i].ips[j].ascii,(int)nl->networks[i].ips[j].port);
}
} else ipcc->printf("-");
ipcc->printf(ZT_EOL_S);
}
_node->freeQueryResult(nl);
}
} else if (cmd[0] == "join") {
if (cmd.size() > 1) {
uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
_node->join(nwid);
ipcc->printf("200 join %.16llx OK"ZT_EOL_S,(unsigned long long)nwid);
} else {
ipcc->printf("400 join requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
}
} else if (cmd[0] == "leave") {
if (cmd.size() > 1) {
uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
_node->leave(nwid);
ipcc->printf("200 leave %.16llx OK"ZT_EOL_S,(unsigned long long)nwid);
} else {
ipcc->printf("400 leave requires a network ID (>0) in hexadecimal format"ZT_EOL_S);
}
} else if (cmd[0] == "terminate") {
if (cmd.size() > 1)
_node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
else _node->terminate(Node::NODE_NORMAL_TERMINATION,"terminate via IPC command");
} else if (cmd[0] == "updatecheck") {
if (_node->updateCheck()) {
ipcc->printf("500 software updates are not enabled"ZT_EOL_S);
} else {
ipcc->printf("200 OK"ZT_EOL_S);
}
} else {
ipcc->printf("404 %s No such command. Use 'help' for help."ZT_EOL_S,cmd[0].c_str());
}
}
ipcc->printf("."ZT_EOL_S);
}
} // namespace ZeroTier

View file

@ -0,0 +1,84 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_NODECONTROLSERVICE_HPP
#define ZT_NODECONTROLSERVICE_HPP
#include <string>
#include <map>
#include "IpcConnection.hpp"
#include "IpcListener.hpp"
#include "../node/Constants.hpp"
#include "../node/NonCopyable.hpp"
#include "../node/Thread.hpp"
namespace ZeroTier {
class Node;
/**
* Background controller service that controls and configures a node
*
* This is used with system-installed instances of ZeroTier One to
* provide the IPC-based control bus service for node configuration.
*/
class NodeControlService : NonCopyable
{
public:
/**
* @param node Node to control and configure
* @param authToken Authorization token for clients
*/
NodeControlService(Node *node,const char *authToken);
~NodeControlService();
// Background thread waits for node to initialize, then creates IpcListener and
// terminates. It also terminates on delete if it hasn't bootstrapped yet.
void threadMain()
throw();
private:
static void _CBcommandHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *commandLine);
void _doCommand(IpcConnection *ipcc,const char *commandLine);
Node *_node;
IpcListener *_listener;
std::string _authToken;
std::map< IpcConnection *,bool > _connections;
Mutex _connections_m;
volatile bool _running;
Thread _thread;
};
} // namespace ZeroTier
#endif

View file

@ -0,0 +1,4 @@
ZeroTier Control Plane
======
This code is responsible for the local command bus used to control the ZeroTier One service on a local machine via zerotier-cli or the Qt GUI. It's not part of the core node implementation. It uses Unix domain sockets on unix-like OSes and named pipes on Windows. Authentication is via a simple token mechanism. (Eventually this part of the software is getting a rework.)