attic cleanup

This commit is contained in:
Adam Ierymenko 2015-04-25 17:25:06 -07:00
parent e78899fddf
commit 7af1f3a79a
5 changed files with 0 additions and 2333 deletions

View File

@ -1,949 +0,0 @@
/*
* 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

View File

@ -1,245 +0,0 @@
/*
* 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

@ -1,162 +0,0 @@
/*
* 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 "WindowsEthernetTapFactory.hpp"
#include "WindowsEthernetTap.hpp"
namespace ZeroTier {
WindowsEthernetTapFactory::Env::Env()
{
#ifdef _WIN64
is64Bit = TRUE;
devcon = "\\devcon_x64.exe";
tapDriver = "\\tap-windows\\x64\\zttap200.inf";
#else
is64Bit = FALSE;
IsWow64Process(GetCurrentProcess(),&is64Bit);
devcon = ((is64Bit == TRUE) ? "\\devcon_x64.exe" : "\\devcon_x86.exe");
tapDriver = ((is64Bit == TRUE) ? "\\tap-windows\\x64\\zttap200.inf" : "\\tap-windows\\x86\\zttap200.inf");
#endif
}
const WindowsEthernetTapFactory::Env WindowsEthernetTapFactory::WINENV;
WindowsEthernetTapFactory::WindowsEthernetTapFactory(const char *pathToHelpers) :
_pathToHelpers(pathToHelpers)
{
}
WindowsEthernetTapFactory::~WindowsEthernetTapFactory()
{
Mutex::Lock _l(_devices_m);
for(std::vector<EthernetTap *>::iterator d(_devices.begin());d!=_devices.end();++d)
delete *d;
}
EthernetTap *WindowsEthernetTapFactory::open(
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *desiredDevice,
const char *friendlyName,
void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
void *arg)
{
Mutex::Lock _l(_devices_m);
EthernetTap *t = new WindowsEthernetTap(_pathToHelpers.c_str(),mac,mtu,metric,nwid,desiredDevice,friendlyName,handler,arg);
_devices.push_back(t);
return t;
}
void WindowsEthernetTapFactory::close(EthernetTap *tap,bool destroyPersistentDevices)
{
if (!tap)
return;
std::string instanceId(((WindowsEthernetTap *)tap)->instanceId());
Mutex::Lock _l(_devices_m);
for(std::vector<EthernetTap *>::iterator d(_devices.begin());d!=_devices.end();++d) {
if (*d == tap) {
_devices.erase(d);
break;
}
}
delete tap;
if (destroyPersistentDevices)
_deletePersistentTapDevice(_pathToHelpers.c_str(),instanceId.c_str());
}
void WindowsEthernetTapFactory::destroyAllPersistentTapDevices(const char *pathToHelpers)
{
char subkeyName[4096];
char subkeyClass[4096];
char data[4096];
std::set<std::string> instanceIdPathsToRemove;
{
HKEY nwAdapters;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
return;
for(DWORD subkeyIndex=0;;++subkeyIndex) {
DWORD type;
DWORD dataLen;
DWORD subkeyNameLen = sizeof(subkeyName);
DWORD subkeyClassLen = sizeof(subkeyClass);
FILETIME lastWriteTime;
if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
type = 0;
dataLen = sizeof(data);
if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
data[dataLen] = '\0';
if (!strnicmp(data,"zttap",5)) {
std::string instanceIdPath;
type = 0;
dataLen = sizeof(data);
if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
instanceIdPath.assign(data,dataLen);
if (instanceIdPath.length() != 0)
instanceIdPathsToRemove.insert(instanceIdPath);
}
}
} else break; // end of list or failure
}
RegCloseKey(nwAdapters);
}
for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp)
_deletePersistentTapDevice(pathToHelpers,iidp->c_str());
}
void WindowsEthernetTapFactory::_deletePersistentTapDevice(const char *pathToHelpers,const char *instanceId)
{
HANDLE devconLog = CreateFileA((std::string(pathToHelpers) + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
STARTUPINFOA startupInfo;
startupInfo.cb = sizeof(startupInfo);
if (devconLog != INVALID_HANDLE_VALUE) {
SetFilePointer(devconLog,0,0,FILE_END);
startupInfo.hStdOutput = devconLog;
startupInfo.hStdError = devconLog;
}
PROCESS_INFORMATION processInfo;
memset(&startupInfo,0,sizeof(STARTUPINFOA));
memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
if (CreateProcessA(NULL,(LPSTR)(std::string("\"") + pathToHelpers + WINENV.devcon + "\" remove @" + instanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
WaitForSingleObject(processInfo.hProcess,INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
if (devconLog != INVALID_HANDLE_VALUE)
CloseHandle(devconLog);
}
} // namespace ZeroTier

View File

@ -1,90 +0,0 @@
/*
* 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_WINDOWSETHERNETTAPFACTORY_HPP
#define ZT_WINDOWSETHERNETTAPFACTORY_HPP
#include <vector>
#include <string>
#include "../node/EthernetTapFactory.hpp"
#include "../node/Mutex.hpp"
namespace ZeroTier {
class WindowsEthernetTapFactory : public EthernetTapFactory
{
public:
class Env
{
public:
Env();
BOOL is64Bit; // true if WIN64 or WoW64 (32-bit binary on 64-bit architecture)
const char *devcon; // name of devcon binary in pathToHelpers to use
const char *tapDriver; // relative path to driver under pathToHelpers to use
};
/**
* Constants related to Windows environment, computed on program start
*/
static const Env WINENV;
/**
* @param pathToHelpers Path to devcon32.exe, devcon64.exe, and other required helper binaries (ZeroTier running directory)
*/
WindowsEthernetTapFactory(const char *pathToHelpers);
virtual ~WindowsEthernetTapFactory();
virtual EthernetTap *open(
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *desiredDevice,
const char *friendlyName,
void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
void *arg);
virtual void close(EthernetTap *tap,bool destroyPersistentDevices);
/**
* Uninstalls all persistent tap devices in the system belonging to ZeroTier
*
* This is for uninstallation. Do not call this while tap devices are active.
*/
static void destroyAllPersistentTapDevices(const char *pathToHelpers);
private:
static void _deletePersistentTapDevice(const char *pathToHelpers,const char *instanceId);
std::string _pathToHelpers;
std::vector<EthernetTap *> _devices;
Mutex _devices_m;
};
} // namespace ZeroTier
#endif

View File

@ -1,887 +0,0 @@
/*
* 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/
*/
// Uncomment on Windows to assume -C and run in console instead of service
// Useful for Visual Studio debugging (launch VS as Administrator to run)
//#define ZT_WIN_RUN_IN_CONSOLE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <string>
#include <stdexcept>
#include "node/Constants.hpp"
#ifdef __WINDOWS__
#include <WinSock2.h>
#include <Windows.h>
#include <tchar.h>
#include <wchar.h>
#include <lmcons.h>
#include <newdev.h>
#include <atlbase.h>
#include "windows/ZeroTierOne/ServiceInstaller.h"
#include "windows/ZeroTierOne/ServiceBase.h"
#include "windows/ZeroTierOne/ZeroTierOneService.h"
#else
#include <unistd.h>
#include <pwd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#endif
#include "node/Constants.hpp"
#include "node/Defaults.hpp"
#include "node/Utils.hpp"
#include "node/Node.hpp"
#include "node/C25519.hpp"
#include "node/Identity.hpp"
#include "node/Thread.hpp"
#include "node/CertificateOfMembership.hpp"
#include "node/EthernetTapFactory.hpp"
#include "node/SocketManager.hpp"
#include "control/NodeControlClient.hpp"
#include "control/NodeControlService.hpp"
#include "osdep/NativeSocketManager.hpp"
#ifdef ZT_ENABLE_NETCONF_MASTER
#include "netconf/SqliteNetworkConfigMaster.hpp"
#endif // ZT_ENABLE_NETCONF_MASTER
#ifdef __WINDOWS__
#include "osdep/WindowsEthernetTapFactory.hpp"
#define ZTCreatePlatformEthernetTapFactory (new WindowsEthernetTapFactory(homeDir))
#endif // __WINDOWS__
#ifdef __LINUX__
#include "osdep/LinuxEthernetTapFactory.hpp"
#define ZTCreatePlatformEthernetTapFactory (new LinuxEthernetTapFactory())
#endif // __LINUX__
#ifdef __APPLE__
#include "osdep/OSXEthernetTapFactory.hpp"
#define ZTCreatePlatformEthernetTapFactory (new OSXEthernetTapFactory(homeDir,"tap.kext"))
#endif // __APPLE__
#ifndef ZTCreatePlatformEthernetTapFactory
#ifdef __BSD__
#include "osdep/BSDEthernetTapFactory.hpp"
#define ZTCreatePlatformEthernetTapFactory (new BSDEthernetTapFactory())
#else
#error Sorry, this platform has no osdep/ implementation yet. Fork me on GitHub and add one?
#endif // __BSD__
#endif // ZTCreatePlatformEthernetTapFactory
using namespace ZeroTier;
static Node *node = (Node *)0;
namespace ZeroTierCLI { // ---------------------------------------------------
static void printHelp(FILE *out,const char *cn)
{
fprintf(out,"Usage: %s <command> (use 'help' for help)"ZT_EOL_S,cn);
}
static void _CBresultHandler(void *arg,const char *line)
{
if (line) {
if ((line[0] == '.')&&(line[1] == (char)0)) {
fflush(stdout);
::exit(0); // terminate CLI on end of message
} else {
fprintf(stdout,"%s"ZT_EOL_S,line);
}
}
}
#ifdef __WINDOWS__
static int main(const char *homeDir,int argc,_TCHAR* argv[])
#else
static int main(const char *homeDir,int argc,char **argv)
#endif
{
if (argc < 2) {
printHelp(stdout,argv[0]);
return 1;
}
std::string query;
for(int i=1;i<argc;++i) {
if (argv[i][0] == '-') {
switch(argv[i][1]) {
case 'q': // ignore -q since it's used to invoke this
break;
case 'h':
default:
printHelp(stdout,argv[0]);
return 1;
}
} else if ((!homeDir)||(strcmp(homeDir,argv[i]))) {
if (query.length())
query.push_back(' ');
query.append(argv[i]);
}
}
if (!query.length()) {
printHelp(stdout,argv[0]);
return 1;
}
if (!homeDir)
homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
try {
std::string buf;
if (!Utils::readFile((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),buf)) {
fprintf(stderr,"%s: fatal error: unable to read node address from identity.public in home path"ZT_EOL_S,argv[0]);
return 1;
}
Identity id;
if (!id.fromString(buf)) {
fprintf(stderr,"%s: fatal error: unable to read node address from identity.public in home path"ZT_EOL_S,argv[0]);
return 1;
}
std::string authToken(NodeControlClient::getAuthToken((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),false));
if (!authToken.length())
authToken = NodeControlClient::getAuthToken(NodeControlClient::authTokenDefaultUserPath(),false);
if (!authToken.length()) {
fprintf(stderr,"%s: fatal error: unable to read authentication token from home path or user home"ZT_EOL_S,argv[0]);
return 1;
}
NodeControlClient client((std::string(ZT_IPC_ENDPOINT_BASE) + id.address().toString()).c_str(),authToken.c_str(),&_CBresultHandler,(void *)0);
const char *err = client.error();
if (err) {
fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (%s)"ZT_EOL_S,argv[0],err);
return 1;
}
client.send(query.c_str());
for(;;) { Thread::sleep(60000); } // exit() is called at end of message from handler
} catch (std::exception &exc) {
fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (%s)"ZT_EOL_S,argv[0],exc.what());
return 1;
} catch ( ... ) {
fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (unknown exception)"ZT_EOL_S,argv[0]);
return 1;
}
return 0;
}
} // namespace ZeroTierCLI ---------------------------------------------------
namespace ZeroTierIdTool { // ------------------------------------------------
static void printHelp(FILE *out,const char *pn)
{
fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
}
static Identity getIdFromArg(char *arg)
{
Identity id;
if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
if (id.fromString(arg))
return id;
} else { // identity is to be read from a file
std::string idser;
if (Utils::readFile(arg,idser)) {
if (id.fromString(idser))
return id;
}
}
return Identity();
}
#ifdef __WINDOWS__
static int main(int argc,_TCHAR* argv[])
#else
static int main(int argc,char **argv)
#endif
{
if (argc < 2) {
printHelp(stdout,argv[0]);
return 1;
}
if (!strcmp(argv[1],"generate")) {
Identity id;
id.generate();
std::string idser = id.toString(true);
if (argc >= 3) {
if (!Utils::writeFile(argv[2],idser)) {
fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
return 1;
} else printf("%s written"ZT_EOL_S,argv[2]);
if (argc >= 4) {
idser = id.toString(false);
if (!Utils::writeFile(argv[3],idser)) {
fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
return 1;
} else printf("%s written"ZT_EOL_S,argv[3]);
}
} else printf("%s",idser.c_str());
} else if (!strcmp(argv[1],"validate")) {
if (argc < 3) {
printHelp(stdout,argv[0]);
return 1;
}
Identity id = getIdFromArg(argv[2]);
if (!id) {
fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
return 1;
}
if (!id.locallyValidate()) {
fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
return 1;
} else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
} else if (!strcmp(argv[1],"getpublic")) {
if (argc < 3) {
printHelp(stdout,argv[0]);
return 1;
}
Identity id = getIdFromArg(argv[2]);
if (!id) {
fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
return 1;
}
printf("%s",id.toString(false).c_str());
} else if (!strcmp(argv[1],"sign")) {
if (argc < 4) {
printHelp(stdout,argv[0]);
return 1;
}
Identity id = getIdFromArg(argv[2]);
if (!id) {
fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
return 1;
}
if (!id.hasPrivate()) {
fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
return 1;
}
std::string inf;
if (!Utils::readFile(argv[3],inf)) {
fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
return 1;
}
C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
} else if (!strcmp(argv[1],"verify")) {
if (argc < 4) {
printHelp(stdout,argv[0]);
return 1;
}
Identity id = getIdFromArg(argv[2]);
if (!id) {
fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
return 1;
}
std::string inf;
if (!Utils::readFile(argv[3],inf)) {
fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
return 1;
}
std::string signature(Utils::unhex(argv[4]));
if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
printf("%s signature valid"ZT_EOL_S,argv[3]);
} else {
fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
return 1;
}
} else if (!strcmp(argv[1],"mkcom")) {
if (argc < 3) {
printHelp(stdout,argv[0]);
return 1;
}
Identity id = getIdFromArg(argv[2]);
if ((!id)||(!id.hasPrivate())) {
fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
return 1;
}
CertificateOfMembership com;
for(int a=3;a<argc;++a) {
std::vector<std::string> params(Utils::split(argv[a],",","",""));
if (params.size() == 3) {
uint64_t qId = Utils::hexStrToU64(params[0].c_str());
uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
com.setQualifier(qId,qValue,qMaxDelta);
}
}
if (!com.sign(id)) {
fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
return 1;
}
printf("%s",com.toString().c_str());
} else {
printHelp(stdout,argv[0]);
return 1;
}
return 0;
}
} // namespace ZeroTierIdTool ------------------------------------------------
#ifdef __UNIX_LIKE__
static void sighandlerHup(int sig)
{
Node *n = node;
if (n)
n->resync();
}
static void sighandlerQuit(int sig)
{
Node *n = node;
if (n)
n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
else exit(0);
}
#endif
#ifdef __WINDOWS__
// Console signal handler routine to allow CTRL+C to work, mostly for testing
static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
{
switch(dwCtrlType) {
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
Node *n = node;
if (n)
n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
return TRUE;
}
return FALSE;
}
// Pokes a hole in the Windows firewall (advfirewall) for the running program
static void _winPokeAHole()
{
char myPath[MAX_PATH];
DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
STARTUPINFOA startupInfo;
PROCESS_INFORMATION processInfo;
startupInfo.cb = sizeof(startupInfo);
memset(&startupInfo,0,sizeof(STARTUPINFOA));
memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall delete rule name=\"ZeroTier One\" program=\"") + myPath + "\"").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
WaitForSingleObject(processInfo.hProcess,INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
startupInfo.cb = sizeof(startupInfo);
memset(&startupInfo,0,sizeof(STARTUPINFOA));
memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=in action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
WaitForSingleObject(processInfo.hProcess,INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
startupInfo.cb = sizeof(startupInfo);
memset(&startupInfo,0,sizeof(STARTUPINFOA));
memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=out action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
WaitForSingleObject(processInfo.hProcess,INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
}
}
// Returns true if this is running as the local administrator
static BOOL IsCurrentUserLocalAdministrator(void)
{
BOOL fReturn = FALSE;
DWORD dwStatus;
DWORD dwAccessMask;
DWORD dwAccessDesired;
DWORD dwACLSize;
DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
PACL pACL = NULL;
PSID psidAdmin = NULL;
HANDLE hToken = NULL;
HANDLE hImpersonationToken = NULL;
PRIVILEGE_SET ps;
GENERIC_MAPPING GenericMapping;
PSECURITY_DESCRIPTOR psdAdmin = NULL;
SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
const DWORD ACCESS_READ = 1;
const DWORD ACCESS_WRITE = 2;
__try
{
if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
{
if (GetLastError() != ERROR_NO_TOKEN)
__leave;
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
__leave;
}
if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
__leave;
if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, &psidAdmin))
__leave;
psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if (psdAdmin == NULL)
__leave;
if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
__leave;
dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
if (pACL == NULL)
__leave;
if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
__leave;
dwAccessMask= ACCESS_READ | ACCESS_WRITE;
if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
__leave;
if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
__leave;
SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
if (!IsValidSecurityDescriptor(psdAdmin))
__leave;
dwAccessDesired = ACCESS_READ;
GenericMapping.GenericRead = ACCESS_READ;
GenericMapping.GenericWrite = ACCESS_WRITE;
GenericMapping.GenericExecute = 0;
GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
&GenericMapping, &ps, &dwStructureSize, &dwStatus,
&fReturn))
{
fReturn = FALSE;
__leave;
}
}
__finally
{
// Clean up.
if (pACL) LocalFree(pACL);
if (psdAdmin) LocalFree(psdAdmin);
if (psidAdmin) FreeSid(psidAdmin);
if (hImpersonationToken) CloseHandle (hImpersonationToken);
if (hToken) CloseHandle (hToken);
}
return fReturn;
}
#endif // __WINDOWS__
// ---------------------------------------------------------------------------
static void printHelp(const char *cn,FILE *out)
{
fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2014 ZeroTier Networks LLC"ZT_EOL_S,Node::versionMajor(),Node::versionMinor(),Node::versionRevision());
fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
#ifdef ZT_AUTO_UPDATE
fprintf(out,"Auto-update enabled build, will update from URL:"ZT_EOL_S);
fprintf(out," %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
fprintf(out,"Update authentication signing authorities: "ZT_EOL_S);
int no = 0;
for(std::map< Address,Identity >::const_iterator sa(ZT_DEFAULTS.updateAuthorities.begin());sa!=ZT_DEFAULTS.updateAuthorities.end();++sa) {
if (no == 0)
fprintf(out," %s",sa->first.toString().c_str());
else fprintf(out,", %s",sa->first.toString().c_str());
if (++no == 6) {
fprintf(out,ZT_EOL_S);
no = 0;
}
}
fprintf(out,ZT_EOL_S""ZT_EOL_S);
#else
fprintf(out,"Auto-updates not enabled on this build. You must update manually."ZT_EOL_S""ZT_EOL_S);
#endif
fprintf(out,"Usage: %s [-switches] [home directory] [-q <query>]"ZT_EOL_S""ZT_EOL_S,cn);
fprintf(out,"Available switches:"ZT_EOL_S);
fprintf(out," -h - Display this help"ZT_EOL_S);
fprintf(out," -v - Show version"ZT_EOL_S);
fprintf(out," -p<port> - Port for UDP (default: 9993)"ZT_EOL_S);
fprintf(out," -t<port> - Port for TCP (default: disabled)"ZT_EOL_S);
//fprintf(out," -T<path> - Override root topology, do not authenticate or update"ZT_EOL_S);
#ifdef __UNIX_LIKE__
fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
#endif
fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
#ifdef __WINDOWS__
fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
#endif
}
#ifdef __WINDOWS__
int _tmain(int argc, _TCHAR* argv[])
#else
int main(int argc,char **argv)
#endif
{
#ifdef __UNIX_LIKE__
signal(SIGHUP,&sighandlerHup);
signal(SIGPIPE,SIG_IGN);
signal(SIGUSR1,SIG_IGN);
signal(SIGUSR2,SIG_IGN);
signal(SIGALRM,SIG_IGN);
signal(SIGINT,&sighandlerQuit);
signal(SIGTERM,&sighandlerQuit);
signal(SIGQUIT,&sighandlerQuit);
/* Ensure that there are no inherited file descriptors open from a previous
* incarnation. This is a hack to ensure that GitHub issue #61 or variants
* of it do not return, and should not do anything otherwise bad. */
{
int mfd = STDIN_FILENO;
if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
for(int f=mfd+1;f<1024;++f)
::close(f);
}
#endif
#ifdef __WINDOWS__
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2),&wsaData);
#endif
if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
return ZeroTierCLI::main((const char *)0,argc,argv);
if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
return ZeroTierIdTool::main(argc,argv);
const char *homeDir = (const char *)0;
unsigned int udpPort = ZT_DEFAULT_UDP_PORT;
unsigned int tcpPort = 0;
std::string overrideRootTopology;
#ifdef __UNIX_LIKE__
bool runAsDaemon = false;
#endif
#ifdef __WINDOWS__
#ifdef ZT_WIN_RUN_IN_CONSOLE
bool winRunFromCommandLine = true;
#else
bool winRunFromCommandLine = false;
#endif
#endif // __WINDOWS__
for(int i=1;i<argc;++i) {
if (argv[i][0] == '-') {
switch(argv[i][1]) {
case 'p':
udpPort = Utils::strToUInt(argv[i] + 2);
if (udpPort > 65535) {
printHelp(argv[0],stdout);
return 1;
}
break;
case 't':
tcpPort = Utils::strToUInt(argv[i] + 2);
if (tcpPort > 65535) {
printHelp(argv[0],stdout);
return 1;
}
break;
#ifdef __UNIX_LIKE__
case 'd':
runAsDaemon = true;
break;
#endif
case 'T':
if (argv[i][2]) {
if (!Utils::readFile(argv[i] + 2,overrideRootTopology)) {
fprintf(stderr,"%s: cannot read root topology from %s"ZT_EOL_S,argv[0],argv[i] + 2);
return 1;
}
} else {
printHelp(argv[0],stdout);
return 1;
}
break;
case 'v':
printf("%s"ZT_EOL_S,Node::versionString());
return 0;
case 'q':
if (argv[i][2]) {
printHelp(argv[0],stdout);
return 0;
} else return ZeroTierCLI::main(homeDir,argc,argv);
case 'i':
if (argv[i][2]) {
printHelp(argv[0],stdout);
return 0;
} else return ZeroTierIdTool::main(argc,argv);
#ifdef __WINDOWS__
case 'C':
winRunFromCommandLine = true;
break;
case 'I': { // install self as service
if (IsCurrentUserLocalAdministrator() != TRUE) {
fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
return 1;
}
std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
if (ret.length()) {
fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
return 3;
}
return 0;
} break;
case 'R': { // uninstall self as service
if (IsCurrentUserLocalAdministrator() != TRUE) {
fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
return 1;
}
std::string ret(UninstallService(ZT_SERVICE_NAME));
if (ret.length()) {
fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
return 3;
}
return 0;
} break;
case 'D': { // install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
std::string pathToInf;
#ifdef _WIN64
pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
#else
pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
#endif
printf("Installing ZeroTier One virtual Ethernet port driver."ZT_EOL_S""ZT_EOL_S"NOTE: If you don't see a confirmation window to allow driver installation,"ZT_EOL_S"check to make sure it didn't appear under the installer."ZT_EOL_S);
BOOL needReboot = FALSE;
if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
printf("%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
return 0;
} else {
printf("%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
return 3;
}
} break;
#endif // __WINDOWS__
case 'h':
case '?':
default:
printHelp(argv[0],stdout);
return 0;
}
} else {
if (homeDir) {
printHelp(argv[0],stdout);
return 0;
} else homeDir = argv[i];
}
}
if ((!homeDir)||(strlen(homeDir) == 0))
homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
#ifdef __UNIX_LIKE__
if (getuid() != 0) {
fprintf(stderr,"%s: must be run as root (uid 0)\n",argv[0]);
return 1;
}
if (runAsDaemon) {
long p = (long)fork();
if (p < 0) {
fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
return 1;
} else if (p > 0)
return 0; // forked
// else p == 0, so we are daemonized
}
mkdir(homeDir,0755); // will fail if it already exists, but that's fine
{
// Write .pid file to home folder
char pidpath[4096];
Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
FILE *pf = fopen(pidpath,"w");
if (pf) {
fprintf(pf,"%ld",(long)getpid());
fclose(pf);
}
}
#endif // __UNIX_LIKE__
#ifdef __WINDOWS__
if (winRunFromCommandLine) {
// Running in "interactive" mode (mostly for debugging)
if (IsCurrentUserLocalAdministrator() != TRUE) {
fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
return 1;
}
_winPokeAHole();
SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
// continues on to ordinary command line execution code below...
} else {
// Running from service manager
_winPokeAHole();
ZeroTierOneService zt1Service;
if (CServiceBase::Run(zt1Service) == TRUE) {
return 0;
} else {
fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
return 1;
}
}
#endif // __WINDOWS__
int exitCode = 0;
bool needsReset = false;
EthernetTapFactory *tapFactory = (EthernetTapFactory *)0;
SocketManager *socketManager = (SocketManager *)0;
NodeControlService *controlService = (NodeControlService *)0;
NetworkConfigMaster *netconfMaster = (NetworkConfigMaster *)0;
try {
// Get or create authtoken.secret -- note that if this fails, authentication
// will always fail since an empty auth token won't work. This should always
// succeed unless something is wrong with the filesystem.
std::string authToken(NodeControlClient::getAuthToken((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),true));
tapFactory = ZTCreatePlatformEthernetTapFactory;
try {
socketManager = new NativeSocketManager(udpPort,tcpPort);
} catch ( ... ) {
fprintf(stderr,"%s: unable to bind to port: %u/UDP, %u/TCP (0 == disabled)"ZT_EOL_S,argv[0],udpPort,tcpPort);
throw;
}
node = new Node(homeDir,tapFactory,socketManager,netconfMaster,needsReset,(overrideRootTopology.length() > 0) ? overrideRootTopology.c_str() : (const char *)0);
controlService = new NodeControlService(node,authToken.c_str());
switch(node->run()) {
#ifdef __WINDOWS__
case Node::NODE_RESTART_FOR_UPGRADE: {
const char *upgPath = node->terminationMessage();
if (upgPath) {
if (!ZeroTierOneService::doStartUpgrade(std::string(upgPath))) {
exitCode = 3;
fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (doStartUpgrade failed)"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
}
} else {
exitCode = 3;
fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (no upgrade path provided)"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
}
} break;
#else // __UNIX_LIKE__
case Node::NODE_RESTART_FOR_UPGRADE: {
const char *upgPath = node->terminationMessage();
// On Unix-type OSes we exec() right into the upgrade. This in turn will
// end with us being re-launched either via the upgrade itself or something
// like OSX's launchd.
if (upgPath) {
Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
std::string updateLogPath(homeDir);
updateLogPath.append("/autoupdate.log");
Utils::rm(updateLogPath.c_str());
Utils::redirectUnixOutputs(updateLogPath.c_str(),(const char *)0);
::execl(upgPath,upgPath,(char *)0);
}
exitCode = 3;
fprintf(stderr,"%s: abnormal termination: unable to execute update at %s"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
} break;
#endif // __WINDOWS__ / __UNIX_LIKE__
case Node::NODE_UNRECOVERABLE_ERROR: {
exitCode = 3;
const char *termReason = node->terminationMessage();
fprintf(stderr,"%s: abnormal termination: %s"ZT_EOL_S,argv[0],(termReason) ? termReason : "(unknown reason)");
} break;
default:
break;
}
} catch ( std::exception &exc ) {
fprintf(stderr,"%s: unexpected exception: %s"ZT_EOL_S,argv[0],exc.what());
exitCode = 3;
} catch ( ... ) {
fprintf(stderr,"%s: unexpected exception: unknown exception"ZT_EOL_S,argv[0]);
exitCode = 3;
}
delete controlService;
delete node; node = (Node *)0;
delete socketManager;
delete tapFactory;
#ifdef __UNIX_LIKE__
Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
#endif
return exitCode;
}