| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752 | 
							- /*
 
-  * 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 <stdarg.h>
 
- #include <string.h>
 
- #include <stdint.h>
 
- #include "../version.h"
 
- #include "Constants.hpp"
 
- #include "Node.hpp"
 
- #include "RuntimeEnvironment.hpp"
 
- #include "NetworkController.hpp"
 
- #include "Switch.hpp"
 
- #include "Multicaster.hpp"
 
- #include "AntiRecursion.hpp"
 
- #include "Topology.hpp"
 
- #include "Buffer.hpp"
 
- #include "Packet.hpp"
 
- #include "Address.hpp"
 
- #include "Identity.hpp"
 
- #include "SelfAwareness.hpp"
 
- #include "Defaults.hpp"
 
- const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
 
- namespace ZeroTier {
 
- /****************************************************************************/
 
- /* Public Node interface (C++, exposed via CAPI bindings)                   */
 
- /****************************************************************************/
 
- Node::Node(
 
- 	uint64_t now,
 
- 	void *uptr,
 
- 	ZT_DataStoreGetFunction dataStoreGetFunction,
 
- 	ZT_DataStorePutFunction dataStorePutFunction,
 
- 	ZT_WirePacketSendFunction wirePacketSendFunction,
 
- 	ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
 
- 	ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
 
- 	ZT_EventCallback eventCallback,
 
- 	const char *overrideRootTopology) :
 
- 	_RR(this),
 
- 	RR(&_RR),
 
- 	_uPtr(uptr),
 
- 	_dataStoreGetFunction(dataStoreGetFunction),
 
- 	_dataStorePutFunction(dataStorePutFunction),
 
- 	_wirePacketSendFunction(wirePacketSendFunction),
 
- 	_virtualNetworkFrameFunction(virtualNetworkFrameFunction),
 
- 	_virtualNetworkConfigFunction(virtualNetworkConfigFunction),
 
- 	_eventCallback(eventCallback),
 
- 	_networks(),
 
- 	_networks_m(),
 
- 	_prngStreamPtr(0),
 
- 	_now(now),
 
- 	_lastPingCheck(0),
 
- 	_lastHousekeepingRun(0)
 
- {
 
- 	_newestVersionSeen[0] = ZEROTIER_ONE_VERSION_MAJOR;
 
- 	_newestVersionSeen[1] = ZEROTIER_ONE_VERSION_MINOR;
 
- 	_newestVersionSeen[2] = ZEROTIER_ONE_VERSION_REVISION;
 
- 	_online = false;
 
- 	// Use Salsa20 alone as a high-quality non-crypto PRNG
 
- 	{
 
- 		char foo[32];
 
- 		Utils::getSecureRandom(foo,32);
 
- 		_prng.init(foo,256,foo,8);
 
- 		memset(_prngStream,0,sizeof(_prngStream));
 
- 		_prng.encrypt(_prngStream,_prngStream,sizeof(_prngStream));
 
- 	}
 
- 	std::string idtmp(dataStoreGet("identity.secret"));
 
- 	if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
 
- 		TRACE("identity.secret not found, generating...");
 
- 		RR->identity.generate();
 
- 		idtmp = RR->identity.toString(true);
 
- 		if (!dataStorePut("identity.secret",idtmp,true))
 
- 			throw std::runtime_error("unable to write identity.secret");
 
- 	}
 
- 	RR->publicIdentityStr = RR->identity.toString(false);
 
- 	RR->secretIdentityStr = RR->identity.toString(true);
 
- 	idtmp = dataStoreGet("identity.public");
 
- 	if (idtmp != RR->publicIdentityStr) {
 
- 		if (!dataStorePut("identity.public",RR->publicIdentityStr,false))
 
- 			throw std::runtime_error("unable to write identity.public");
 
- 	}
 
- 	try {
 
- 		RR->sw = new Switch(RR);
 
- 		RR->mc = new Multicaster(RR);
 
- 		RR->antiRec = new AntiRecursion();
 
- 		RR->topology = new Topology(RR);
 
- 		RR->sa = new SelfAwareness(RR);
 
- 	} catch ( ... ) {
 
- 		delete RR->sa;
 
- 		delete RR->topology;
 
- 		delete RR->antiRec;
 
- 		delete RR->mc;
 
- 		delete RR->sw;
 
- 		throw;
 
- 	}
 
- 	Dictionary rt;
 
- 	if (overrideRootTopology) {
 
- 		rt.fromString(std::string(overrideRootTopology));
 
- 	} else {
 
- 		std::string rttmp(dataStoreGet("root-topology"));
 
- 		if (rttmp.length() > 0) {
 
- 			rt.fromString(rttmp);
 
- 			if (!Topology::authenticateRootTopology(rt))
 
- 				rt.clear();
 
- 		}
 
- 		if ((!rt.size())||(!rt.contains("rootservers")))
 
- 			rt.fromString(ZT_DEFAULTS.defaultRootTopology);
 
- 	}
 
- 	RR->topology->setRootServers(Dictionary(rt.get("rootservers","")));
 
- 	postEvent(ZT_EVENT_UP);
 
- }
 
- Node::~Node()
 
- {
 
- 	Mutex::Lock _l(_networks_m);
 
- 	_networks.clear(); // ensure that networks are destroyed before shutdown
 
- 	delete RR->sa;
 
- 	delete RR->topology;
 
- 	delete RR->antiRec;
 
- 	delete RR->mc;
 
- 	delete RR->sw;
 
- }
 
- ZT_ResultCode Node::processWirePacket(
 
- 	uint64_t now,
 
- 	const struct sockaddr_storage *localAddress,
 
- 	const struct sockaddr_storage *remoteAddress,
 
- 	const void *packetData,
 
- 	unsigned int packetLength,
 
- 	volatile uint64_t *nextBackgroundTaskDeadline)
 
- {
 
- 	_now = now;
 
- 	RR->sw->onRemotePacket(*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
 
- 	return ZT_RESULT_OK;
 
- }
 
- ZT_ResultCode Node::processVirtualNetworkFrame(
 
- 	uint64_t now,
 
- 	uint64_t nwid,
 
- 	uint64_t sourceMac,
 
- 	uint64_t destMac,
 
- 	unsigned int etherType,
 
- 	unsigned int vlanId,
 
- 	const void *frameData,
 
- 	unsigned int frameLength,
 
- 	volatile uint64_t *nextBackgroundTaskDeadline)
 
- {
 
- 	_now = now;
 
- 	SharedPtr<Network> nw(this->network(nwid));
 
- 	if (nw) {
 
- 		RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
 
- 		return ZT_RESULT_OK;
 
- 	} else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
 
- }
 
- class _PingPeersThatNeedPing
 
- {
 
- public:
 
- 	_PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now,const std::vector< std::pair<Address,InetAddress> > &relays) :
 
- 		lastReceiveFromUpstream(0),
 
- 		RR(renv),
 
- 		_now(now),
 
- 		_relays(relays),
 
- 		_rootAddresses(RR->topology->rootAddresses())
 
- 	{
 
- 	}
 
- 	uint64_t lastReceiveFromUpstream;
 
- 	inline void operator()(Topology &t,const SharedPtr<Peer> &p)
 
- 	{
 
- 		bool isRelay = false;
 
- 		for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(_relays.begin());r!=_relays.end();++r) {
 
- 			if (r->first == p->address()) {
 
- 				isRelay = true;
 
- 				break;
 
- 			}
 
- 		}
 
- 		if ((isRelay)||(std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end())) {
 
- 			p->doPingAndKeepalive(RR,_now);
 
- 			if (p->lastReceive() > lastReceiveFromUpstream)
 
- 				lastReceiveFromUpstream = p->lastReceive();
 
- 		} else {
 
- 			if (p->alive(_now))
 
- 				p->doPingAndKeepalive(RR,_now);
 
- 		}
 
- 	}
 
- private:
 
- 	const RuntimeEnvironment *RR;
 
- 	uint64_t _now;
 
- 	const std::vector< std::pair<Address,InetAddress> > &_relays;
 
- 	std::vector<Address> _rootAddresses;
 
- };
 
- ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
 
- {
 
- 	_now = now;
 
- 	Mutex::Lock bl(_backgroundTasksLock);
 
- 	unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
 
- 	const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
 
- 	if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
 
- 		try {
 
- 			_lastPingCheck = now;
 
- 			// Get relays and networks that need config without leaving the mutex locked
 
- 			std::vector< std::pair<Address,InetAddress> > networkRelays;
 
- 			std::vector< SharedPtr<Network> > needConfig;
 
- 			{
 
- 				Mutex::Lock _l(_networks_m);
 
- 				for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
 
- 					SharedPtr<NetworkConfig> nc(n->second->config2());
 
- 					if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!nc))
 
- 						needConfig.push_back(n->second);
 
- 					if (nc)
 
- 						networkRelays.insert(networkRelays.end(),nc->relays().begin(),nc->relays().end());
 
- 				}
 
- 			}
 
- 			// Request updated configuration for networks that need it
 
- 			for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
 
- 				(*n)->requestConfiguration();
 
- 			// Attempt to contact network preferred relays that we don't have direct links to
 
- 			std::sort(networkRelays.begin(),networkRelays.end());
 
- 			networkRelays.erase(std::unique(networkRelays.begin(),networkRelays.end()),networkRelays.end());
 
- 			for(std::vector< std::pair<Address,InetAddress> >::const_iterator nr(networkRelays.begin());nr!=networkRelays.end();++nr) {
 
- 				if (nr->second) {
 
- 					SharedPtr<Peer> rp(RR->topology->getPeer(nr->first));
 
- 					if ((rp)&&(!rp->hasActiveDirectPath(now)))
 
- 						rp->attemptToContactAt(RR,InetAddress(),nr->second,now);
 
- 				}
 
- 			}
 
- 			// Ping living or root server/relay peers
 
- 			_PingPeersThatNeedPing pfunc(RR,now,networkRelays);
 
- 			RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
 
- 			// Update online status, post status change as event
 
- 			bool oldOnline = _online;
 
- 			_online = ((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT);
 
- 			if (oldOnline != _online)
 
- 				postEvent(_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
 
- 		} catch ( ... ) {
 
- 			return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 		}
 
- 	} else {
 
- 		timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
 
- 	}
 
- 	if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
 
- 		try {
 
- 			_lastHousekeepingRun = now;
 
- 			RR->topology->clean(now);
 
- 			RR->sa->clean(now);
 
- 			RR->mc->clean(now);
 
- 		} catch ( ... ) {
 
- 			return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 		}
 
- 	}
 
- 	try {
 
- 		*nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- 	return ZT_RESULT_OK;
 
- }
 
- ZT_ResultCode Node::join(uint64_t nwid)
 
- {
 
- 	Mutex::Lock _l(_networks_m);
 
- 	SharedPtr<Network> nw = _network(nwid);
 
- 	if(!nw)
 
- 		_networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid))));
 
- 	std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
 
- 	return ZT_RESULT_OK;
 
- }
 
- ZT_ResultCode Node::leave(uint64_t nwid)
 
- {
 
- 	std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
 
- 	Mutex::Lock _l(_networks_m);
 
- 	for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
 
- 		if (n->first != nwid)
 
- 			newn.push_back(*n);
 
- 		else n->second->destroy();
 
- 	}
 
- 	_networks.swap(newn);
 
- 	return ZT_RESULT_OK;
 
- }
 
- ZT_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
 
- {
 
- 	SharedPtr<Network> nw(this->network(nwid));
 
- 	if (nw) {
 
- 		nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
 
- 		return ZT_RESULT_OK;
 
- 	} else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
 
- }
 
- ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
 
- {
 
- 	SharedPtr<Network> nw(this->network(nwid));
 
- 	if (nw) {
 
- 		nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
 
- 		return ZT_RESULT_OK;
 
- 	} else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
 
- }
 
- uint64_t Node::address() const
 
- {
 
- 	return RR->identity.address().toInt();
 
- }
 
- void Node::status(ZT_NodeStatus *status) const
 
- {
 
- 	status->address = RR->identity.address().toInt();
 
- 	status->publicIdentity = RR->publicIdentityStr.c_str();
 
- 	status->secretIdentity = RR->secretIdentityStr.c_str();
 
- 	status->online = _online ? 1 : 0;
 
- }
 
- ZT_PeerList *Node::peers() const
 
- {
 
- 	std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
 
- 	std::sort(peers.begin(),peers.end());
 
- 	char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
 
- 	if (!buf)
 
- 		return (ZT_PeerList *)0;
 
- 	ZT_PeerList *pl = (ZT_PeerList *)buf;
 
- 	pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
 
- 	pl->peerCount = 0;
 
- 	for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
 
- 		ZT_Peer *p = &(pl->peers[pl->peerCount++]);
 
- 		p->address = pi->second->address().toInt();
 
- 		p->lastUnicastFrame = pi->second->lastUnicastFrame();
 
- 		p->lastMulticastFrame = pi->second->lastMulticastFrame();
 
- 		if (pi->second->remoteVersionKnown()) {
 
- 			p->versionMajor = pi->second->remoteVersionMajor();
 
- 			p->versionMinor = pi->second->remoteVersionMinor();
 
- 			p->versionRev = pi->second->remoteVersionRevision();
 
- 		} else {
 
- 			p->versionMajor = -1;
 
- 			p->versionMinor = -1;
 
- 			p->versionRev = -1;
 
- 		}
 
- 		p->latency = pi->second->latency();
 
- 		p->role = RR->topology->isRoot(pi->second->identity()) ? ZT_PEER_ROLE_ROOT : ZT_PEER_ROLE_LEAF;
 
- 		std::vector<RemotePath> paths(pi->second->paths());
 
- 		RemotePath *bestPath = pi->second->getBestPath(_now);
 
- 		p->pathCount = 0;
 
- 		for(std::vector<RemotePath>::iterator path(paths.begin());path!=paths.end();++path) {
 
- 			memcpy(&(p->paths[p->pathCount].address),&(path->address()),sizeof(struct sockaddr_storage));
 
- 			p->paths[p->pathCount].lastSend = path->lastSend();
 
- 			p->paths[p->pathCount].lastReceive = path->lastReceived();
 
- 			p->paths[p->pathCount].fixed = path->fixed() ? 1 : 0;
 
- 			p->paths[p->pathCount].active = path->active(_now) ? 1 : 0;
 
- 			p->paths[p->pathCount].preferred = ((bestPath)&&(*path == *bestPath)) ? 1 : 0;
 
- 			++p->pathCount;
 
- 		}
 
- 	}
 
- 	return pl;
 
- }
 
- ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
 
- {
 
- 	Mutex::Lock _l(_networks_m);
 
- 	SharedPtr<Network> nw = _network(nwid);
 
- 	if(nw) {
 
- 		ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
 
- 		nw->externalConfig(nc);
 
- 		return nc;
 
- 	}
 
- 	return (ZT_VirtualNetworkConfig *)0;
 
- }
 
- ZT_VirtualNetworkList *Node::networks() const
 
- {
 
- 	Mutex::Lock _l(_networks_m);
 
- 	char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
 
- 	if (!buf)
 
- 		return (ZT_VirtualNetworkList *)0;
 
- 	ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
 
- 	nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
 
- 	nl->networkCount = 0;
 
- 	for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
 
- 		n->second->externalConfig(&(nl->networks[nl->networkCount++]));
 
- 	return nl;
 
- }
 
- void Node::freeQueryResult(void *qr)
 
- {
 
- 	if (qr)
 
- 		::free(qr);
 
- }
 
- int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr,int metric,ZT_LocalInterfaceAddressTrust trust)
 
- {
 
- 	if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
 
- 		Mutex::Lock _l(_directPaths_m);
 
- 		_directPaths.push_back(Path(*(reinterpret_cast<const InetAddress *>(addr)),metric,(Path::Trust)trust));
 
- 		std::sort(_directPaths.begin(),_directPaths.end());
 
- 		_directPaths.erase(std::unique(_directPaths.begin(),_directPaths.end()),_directPaths.end());
 
- 		return 1;
 
- 	}
 
- 	return 0;
 
- }
 
- void Node::clearLocalInterfaceAddresses()
 
- {
 
- 	Mutex::Lock _l(_directPaths_m);
 
- 	_directPaths.clear();
 
- }
 
- void Node::setNetconfMaster(void *networkControllerInstance)
 
- {
 
- 	RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
 
- }
 
- /****************************************************************************/
 
- /* Node methods used only within node/                                      */
 
- /****************************************************************************/
 
- std::string Node::dataStoreGet(const char *name)
 
- {
 
- 	char buf[16384];
 
- 	std::string r;
 
- 	unsigned long olen = 0;
 
- 	do {
 
- 		long n = _dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
 
- 		if (n <= 0)
 
- 			return std::string();
 
- 		r.append(buf,n);
 
- 	} while (r.length() < olen);
 
- 	return r;
 
- }
 
- void Node::postNewerVersionIfNewer(unsigned int major,unsigned int minor,unsigned int rev)
 
- {
 
- 	if (Utils::compareVersion(major,minor,rev,_newestVersionSeen[0],_newestVersionSeen[1],_newestVersionSeen[2]) > 0) {
 
- 		_newestVersionSeen[0] = major;
 
- 		_newestVersionSeen[1] = minor;
 
- 		_newestVersionSeen[2] = rev;
 
- 		this->postEvent(ZT_EVENT_SAW_MORE_RECENT_VERSION,(const void *)_newestVersionSeen);
 
- 	}
 
- }
 
- #ifdef ZT_TRACE
 
- void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
 
- {
 
- 	static Mutex traceLock;
 
- 	va_list ap;
 
- 	char tmp1[1024],tmp2[1024],tmp3[256];
 
- 	Mutex::Lock _l(traceLock);
 
- 	time_t now = (time_t)(_now / 1000ULL);
 
- #ifdef __WINDOWS__
 
- 	ctime_s(tmp3,sizeof(tmp3),&now);
 
- 	char *nowstr = tmp3;
 
- #else
 
- 	char *nowstr = ctime_r(&now,tmp3);
 
- #endif
 
- 	unsigned long nowstrlen = (unsigned long)strlen(nowstr);
 
- 	if (nowstr[nowstrlen-1] == '\n')
 
- 		nowstr[--nowstrlen] = (char)0;
 
- 	if (nowstr[nowstrlen-1] == '\r')
 
- 		nowstr[--nowstrlen] = (char)0;
 
- 	va_start(ap,fmt);
 
- 	vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
 
- 	va_end(ap);
 
- 	tmp2[sizeof(tmp2)-1] = (char)0;
 
- 	Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
 
- 	postEvent(ZT_EVENT_TRACE,tmp1);
 
- }
 
- #endif // ZT_TRACE
 
- uint64_t Node::prng()
 
- {
 
- 	unsigned int p = (++_prngStreamPtr % (sizeof(_prngStream) / sizeof(uint64_t)));
 
- 	if (!p)
 
- 		_prng.encrypt(_prngStream,_prngStream,sizeof(_prngStream));
 
- 	return _prngStream[p];
 
- }
 
- } // namespace ZeroTier
 
- /****************************************************************************/
 
- /* CAPI bindings                                                            */
 
- /****************************************************************************/
 
- extern "C" {
 
- enum ZT_ResultCode ZT_Node_new(
 
- 	ZT_Node **node,
 
- 	void *uptr,
 
- 	uint64_t now,
 
- 	ZT_DataStoreGetFunction dataStoreGetFunction,
 
- 	ZT_DataStorePutFunction dataStorePutFunction,
 
- 	ZT_WirePacketSendFunction wirePacketSendFunction,
 
- 	ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
 
- 	ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
 
- 	ZT_EventCallback eventCallback,
 
- 	const char *overrideRootTopology)
 
- {
 
- 	*node = (ZT_Node *)0;
 
- 	try {
 
- 		*node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,eventCallback,overrideRootTopology));
 
- 		return ZT_RESULT_OK;
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch (std::runtime_error &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- }
 
- void ZT_Node_delete(ZT_Node *node)
 
- {
 
- 	try {
 
- 		delete (reinterpret_cast<ZeroTier::Node *>(node));
 
- 	} catch ( ... ) {}
 
- }
 
- enum ZT_ResultCode ZT_Node_processWirePacket(
 
- 	ZT_Node *node,
 
- 	uint64_t now,
 
- 	const struct sockaddr_storage *localAddress,
 
- 	const struct sockaddr_storage *remoteAddress,
 
- 	const void *packetData,
 
- 	unsigned int packetLength,
 
- 	volatile uint64_t *nextBackgroundTaskDeadline)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch ( ... ) {
 
- 		reinterpret_cast<ZeroTier::Node *>(node)->postEvent(ZT_EVENT_INVALID_PACKET,(const void *)remoteAddress);
 
- 		return ZT_RESULT_OK;
 
- 	}
 
- }
 
- enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
 
- 	ZT_Node *node,
 
- 	uint64_t now,
 
- 	uint64_t nwid,
 
- 	uint64_t sourceMac,
 
- 	uint64_t destMac,
 
- 	unsigned int etherType,
 
- 	unsigned int vlanId,
 
- 	const void *frameData,
 
- 	unsigned int frameLength,
 
- 	volatile uint64_t *nextBackgroundTaskDeadline)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- }
 
- enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- }
 
- enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid);
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- }
 
- enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid);
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- }
 
- enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- }
 
- enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
 
- 	} catch (std::bad_alloc &exc) {
 
- 		return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
 
- 	} catch ( ... ) {
 
- 		return ZT_RESULT_FATAL_ERROR_INTERNAL;
 
- 	}
 
- }
 
- uint64_t ZT_Node_address(ZT_Node *node)
 
- {
 
- 	return reinterpret_cast<ZeroTier::Node *>(node)->address();
 
- }
 
- void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
 
- {
 
- 	try {
 
- 		reinterpret_cast<ZeroTier::Node *>(node)->status(status);
 
- 	} catch ( ... ) {}
 
- }
 
- ZT_PeerList *ZT_Node_peers(ZT_Node *node)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->peers();
 
- 	} catch ( ... ) {
 
- 		return (ZT_PeerList *)0;
 
- 	}
 
- }
 
- ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
 
- 	} catch ( ... ) {
 
- 		return (ZT_VirtualNetworkConfig *)0;
 
- 	}
 
- }
 
- ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->networks();
 
- 	} catch ( ... ) {
 
- 		return (ZT_VirtualNetworkList *)0;
 
- 	}
 
- }
 
- void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
 
- {
 
- 	try {
 
- 		reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
 
- 	} catch ( ... ) {}
 
- }
 
- void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
 
- {
 
- 	try {
 
- 		reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
 
- 	} catch ( ... ) {}
 
- }
 
- int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr,int metric,ZT_LocalInterfaceAddressTrust trust)
 
- {
 
- 	try {
 
- 		return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr,metric,trust);
 
- 	} catch ( ... ) {
 
- 		return 0;
 
- 	}
 
- }
 
- void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
 
- {
 
- 	try {
 
- 		reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
 
- 	} catch ( ... ) {}
 
- }
 
- void ZT_version(int *major,int *minor,int *revision,unsigned long *featureFlags)
 
- {
 
- 	if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
 
- 	if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
 
- 	if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
 
- 	if (featureFlags) {
 
- 		*featureFlags = (
 
- 			ZT_FEATURE_FLAG_THREAD_SAFE
 
- 		);
 
- 	}
 
- }
 
- } // extern "C"
 
 
  |