Node.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <stdarg.h>
  30. #include <string.h>
  31. #include <stdint.h>
  32. #include "../version.h"
  33. #include "Constants.hpp"
  34. #include "Node.hpp"
  35. #include "RuntimeEnvironment.hpp"
  36. #include "NetworkController.hpp"
  37. #include "Switch.hpp"
  38. #include "Multicaster.hpp"
  39. #include "AntiRecursion.hpp"
  40. #include "Topology.hpp"
  41. #include "Buffer.hpp"
  42. #include "Packet.hpp"
  43. #include "Address.hpp"
  44. #include "Identity.hpp"
  45. #include "SelfAwareness.hpp"
  46. #include "Cluster.hpp"
  47. const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
  48. namespace ZeroTier {
  49. /****************************************************************************/
  50. /* Public Node interface (C++, exposed via CAPI bindings) */
  51. /****************************************************************************/
  52. Node::Node(
  53. uint64_t now,
  54. void *uptr,
  55. ZT_DataStoreGetFunction dataStoreGetFunction,
  56. ZT_DataStorePutFunction dataStorePutFunction,
  57. ZT_WirePacketSendFunction wirePacketSendFunction,
  58. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  59. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  60. ZT_EventCallback eventCallback) :
  61. _RR(this),
  62. RR(&_RR),
  63. _uPtr(uptr),
  64. _dataStoreGetFunction(dataStoreGetFunction),
  65. _dataStorePutFunction(dataStorePutFunction),
  66. _wirePacketSendFunction(wirePacketSendFunction),
  67. _virtualNetworkFrameFunction(virtualNetworkFrameFunction),
  68. _virtualNetworkConfigFunction(virtualNetworkConfigFunction),
  69. _eventCallback(eventCallback),
  70. _networks(),
  71. _networks_m(),
  72. _prngStreamPtr(0),
  73. _now(now),
  74. _lastPingCheck(0),
  75. _lastHousekeepingRun(0)
  76. {
  77. _online = false;
  78. // Use Salsa20 alone as a high-quality non-crypto PRNG
  79. {
  80. char foo[32];
  81. Utils::getSecureRandom(foo,32);
  82. _prng.init(foo,256,foo);
  83. memset(_prngStream,0,sizeof(_prngStream));
  84. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  85. }
  86. std::string idtmp(dataStoreGet("identity.secret"));
  87. if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
  88. TRACE("identity.secret not found, generating...");
  89. RR->identity.generate();
  90. idtmp = RR->identity.toString(true);
  91. if (!dataStorePut("identity.secret",idtmp,true))
  92. throw std::runtime_error("unable to write identity.secret");
  93. }
  94. RR->publicIdentityStr = RR->identity.toString(false);
  95. RR->secretIdentityStr = RR->identity.toString(true);
  96. idtmp = dataStoreGet("identity.public");
  97. if (idtmp != RR->publicIdentityStr) {
  98. if (!dataStorePut("identity.public",RR->publicIdentityStr,false))
  99. throw std::runtime_error("unable to write identity.public");
  100. }
  101. try {
  102. RR->sw = new Switch(RR);
  103. RR->mc = new Multicaster(RR);
  104. RR->antiRec = new AntiRecursion();
  105. RR->topology = new Topology(RR);
  106. RR->sa = new SelfAwareness(RR);
  107. } catch ( ... ) {
  108. delete RR->sa;
  109. delete RR->topology;
  110. delete RR->antiRec;
  111. delete RR->mc;
  112. delete RR->sw;
  113. throw;
  114. }
  115. postEvent(ZT_EVENT_UP);
  116. }
  117. Node::~Node()
  118. {
  119. Mutex::Lock _l(_networks_m);
  120. _networks.clear(); // ensure that networks are destroyed before shutdown
  121. delete RR->sa;
  122. delete RR->topology;
  123. delete RR->antiRec;
  124. delete RR->mc;
  125. delete RR->sw;
  126. #ifdef ZT_ENABLE_CLUSTER
  127. delete RR->cluster;
  128. #endif
  129. }
  130. ZT_ResultCode Node::processWirePacket(
  131. uint64_t now,
  132. const struct sockaddr_storage *localAddress,
  133. const struct sockaddr_storage *remoteAddress,
  134. const void *packetData,
  135. unsigned int packetLength,
  136. volatile uint64_t *nextBackgroundTaskDeadline)
  137. {
  138. _now = now;
  139. RR->sw->onRemotePacket(*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  140. return ZT_RESULT_OK;
  141. }
  142. ZT_ResultCode Node::processVirtualNetworkFrame(
  143. uint64_t now,
  144. uint64_t nwid,
  145. uint64_t sourceMac,
  146. uint64_t destMac,
  147. unsigned int etherType,
  148. unsigned int vlanId,
  149. const void *frameData,
  150. unsigned int frameLength,
  151. volatile uint64_t *nextBackgroundTaskDeadline)
  152. {
  153. _now = now;
  154. SharedPtr<Network> nw(this->network(nwid));
  155. if (nw) {
  156. RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  157. return ZT_RESULT_OK;
  158. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  159. }
  160. class _PingPeersThatNeedPing
  161. {
  162. public:
  163. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now,const std::vector< std::pair<Address,InetAddress> > &relays) :
  164. lastReceiveFromUpstream(0),
  165. RR(renv),
  166. _now(now),
  167. _relays(relays),
  168. _world(RR->topology->world())
  169. {
  170. }
  171. uint64_t lastReceiveFromUpstream; // tracks last time we got a packet from an 'upstream' peer like a root or a relay
  172. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  173. {
  174. bool upstream = false;
  175. InetAddress stableEndpoint4,stableEndpoint6;
  176. // If this is a world root, pick (if possible) both an IPv4 and an IPv6 stable endpoint to use if link isn't currently alive.
  177. for(std::vector<World::Root>::const_iterator r(_world.roots().begin());r!=_world.roots().end();++r) {
  178. if (r->identity.address() == p->address()) {
  179. upstream = true;
  180. for(unsigned long k=0,ptr=RR->node->prng();k<r->stableEndpoints.size();++k) {
  181. const InetAddress &addr = r->stableEndpoints[ptr++ % r->stableEndpoints.size()];
  182. if (!stableEndpoint4) {
  183. if (addr.ss_family == AF_INET)
  184. stableEndpoint4 = addr;
  185. }
  186. if (!stableEndpoint6) {
  187. if (addr.ss_family == AF_INET6)
  188. stableEndpoint6 = addr;
  189. }
  190. }
  191. break;
  192. }
  193. }
  194. // If this is a network preferred relay, also always ping and if a stable endpoint is specified use that if not alive
  195. if (!upstream) {
  196. for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(_relays.begin());r!=_relays.end();++r) {
  197. if (r->first == p->address()) {
  198. if (r->second.ss_family == AF_INET)
  199. stableEndpoint4 = r->second;
  200. else if (r->second.ss_family == AF_INET6)
  201. stableEndpoint6 = r->second;
  202. upstream = true;
  203. break;
  204. }
  205. }
  206. }
  207. if (upstream) {
  208. // "Upstream" devices are roots and relays and get special treatment -- they stay alive
  209. // forever and we try to keep (if available) both IPv4 and IPv6 channels open to them.
  210. bool needToContactIndirect = true;
  211. if (!p->doPingAndKeepalive(RR,_now,AF_INET)) {
  212. if (stableEndpoint4) {
  213. needToContactIndirect = false;
  214. p->attemptToContactAt(RR,InetAddress(),stableEndpoint4,_now);
  215. }
  216. } else needToContactIndirect = false;
  217. if (!p->doPingAndKeepalive(RR,_now,AF_INET6)) {
  218. if (stableEndpoint6) {
  219. needToContactIndirect = false;
  220. p->attemptToContactAt(RR,InetAddress(),stableEndpoint6,_now);
  221. }
  222. } else needToContactIndirect = false;
  223. if (needToContactIndirect) {
  224. // If this is an upstream and we have no stable endpoint for either IPv4 or IPv6,
  225. // send a NOP indirectly if possible to see if we can get to this peer in any
  226. // way whatsoever. This will e.g. find network preferred relays that lack
  227. // stable endpoints by using root servers.
  228. Packet outp(p->address(),RR->identity.address(),Packet::VERB_NOP);
  229. RR->sw->send(outp,true,0);
  230. }
  231. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  232. } else if (p->alive(_now)) {
  233. // Normal nodes get their preferred link kept alive if the node has generated frame traffic recently
  234. p->doPingAndKeepalive(RR,_now,0);
  235. }
  236. }
  237. private:
  238. const RuntimeEnvironment *RR;
  239. uint64_t _now;
  240. const std::vector< std::pair<Address,InetAddress> > &_relays;
  241. World _world;
  242. };
  243. ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  244. {
  245. _now = now;
  246. Mutex::Lock bl(_backgroundTasksLock);
  247. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  248. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  249. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  250. try {
  251. _lastPingCheck = now;
  252. // Get relays and networks that need config without leaving the mutex locked
  253. std::vector< std::pair<Address,InetAddress> > networkRelays;
  254. std::vector< SharedPtr<Network> > needConfig;
  255. {
  256. Mutex::Lock _l(_networks_m);
  257. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  258. SharedPtr<NetworkConfig> nc(n->second->config2());
  259. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!nc))
  260. needConfig.push_back(n->second);
  261. if (nc)
  262. networkRelays.insert(networkRelays.end(),nc->relays().begin(),nc->relays().end());
  263. }
  264. }
  265. // Request updated configuration for networks that need it
  266. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  267. (*n)->requestConfiguration();
  268. // Attempt to contact network preferred relays that we don't have direct links to
  269. std::sort(networkRelays.begin(),networkRelays.end());
  270. networkRelays.erase(std::unique(networkRelays.begin(),networkRelays.end()),networkRelays.end());
  271. for(std::vector< std::pair<Address,InetAddress> >::const_iterator nr(networkRelays.begin());nr!=networkRelays.end();++nr) {
  272. if (nr->second) {
  273. SharedPtr<Peer> rp(RR->topology->getPeer(nr->first));
  274. if ((rp)&&(!rp->hasActiveDirectPath(now)))
  275. rp->attemptToContactAt(RR,InetAddress(),nr->second,now);
  276. }
  277. }
  278. // Ping living or root server/relay peers
  279. _PingPeersThatNeedPing pfunc(RR,now,networkRelays);
  280. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  281. // Update online status, post status change as event
  282. bool oldOnline = _online;
  283. _online = ((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT);
  284. if (oldOnline != _online)
  285. postEvent(_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  286. } catch ( ... ) {
  287. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  288. }
  289. } else {
  290. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  291. }
  292. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  293. try {
  294. _lastHousekeepingRun = now;
  295. RR->topology->clean(now);
  296. RR->sa->clean(now);
  297. RR->mc->clean(now);
  298. } catch ( ... ) {
  299. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  300. }
  301. }
  302. try {
  303. #ifdef ZT_ENABLE_CLUSTER
  304. // If clustering is enabled we have to call cluster->doPeriodicTasks() very often, so we override normal timer deadline behavior
  305. if (RR->cluster) {
  306. RR->sw->doTimerTasks(now);
  307. RR->cluster->doPeriodicTasks();
  308. *nextBackgroundTaskDeadline = now + ZT_CLUSTER_PERIODIC_TASK_PERIOD; // this is really short so just tick at this rate
  309. } else {
  310. #endif
  311. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  312. #ifdef ZT_ENABLE_CLUSTER
  313. }
  314. #endif
  315. } catch ( ... ) {
  316. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  317. }
  318. return ZT_RESULT_OK;
  319. }
  320. ZT_ResultCode Node::join(uint64_t nwid)
  321. {
  322. Mutex::Lock _l(_networks_m);
  323. SharedPtr<Network> nw = _network(nwid);
  324. if(!nw)
  325. _networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid))));
  326. std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
  327. return ZT_RESULT_OK;
  328. }
  329. ZT_ResultCode Node::leave(uint64_t nwid)
  330. {
  331. std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
  332. Mutex::Lock _l(_networks_m);
  333. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  334. if (n->first != nwid)
  335. newn.push_back(*n);
  336. else n->second->destroy();
  337. }
  338. _networks.swap(newn);
  339. return ZT_RESULT_OK;
  340. }
  341. ZT_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  342. {
  343. SharedPtr<Network> nw(this->network(nwid));
  344. if (nw) {
  345. nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  346. return ZT_RESULT_OK;
  347. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  348. }
  349. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  350. {
  351. SharedPtr<Network> nw(this->network(nwid));
  352. if (nw) {
  353. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  354. return ZT_RESULT_OK;
  355. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  356. }
  357. uint64_t Node::address() const
  358. {
  359. return RR->identity.address().toInt();
  360. }
  361. void Node::status(ZT_NodeStatus *status) const
  362. {
  363. status->address = RR->identity.address().toInt();
  364. status->worldId = RR->topology->worldId();
  365. status->worldTimestamp = RR->topology->worldTimestamp();
  366. status->publicIdentity = RR->publicIdentityStr.c_str();
  367. status->secretIdentity = RR->secretIdentityStr.c_str();
  368. status->online = _online ? 1 : 0;
  369. }
  370. ZT_PeerList *Node::peers() const
  371. {
  372. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  373. std::sort(peers.begin(),peers.end());
  374. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  375. if (!buf)
  376. return (ZT_PeerList *)0;
  377. ZT_PeerList *pl = (ZT_PeerList *)buf;
  378. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  379. pl->peerCount = 0;
  380. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  381. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  382. p->address = pi->second->address().toInt();
  383. p->lastUnicastFrame = pi->second->lastUnicastFrame();
  384. p->lastMulticastFrame = pi->second->lastMulticastFrame();
  385. if (pi->second->remoteVersionKnown()) {
  386. p->versionMajor = pi->second->remoteVersionMajor();
  387. p->versionMinor = pi->second->remoteVersionMinor();
  388. p->versionRev = pi->second->remoteVersionRevision();
  389. } else {
  390. p->versionMajor = -1;
  391. p->versionMinor = -1;
  392. p->versionRev = -1;
  393. }
  394. p->latency = pi->second->latency();
  395. p->role = RR->topology->isRoot(pi->second->identity()) ? ZT_PEER_ROLE_ROOT : ZT_PEER_ROLE_LEAF;
  396. std::vector<RemotePath> paths(pi->second->paths());
  397. RemotePath *bestPath = pi->second->getBestPath(_now);
  398. p->pathCount = 0;
  399. for(std::vector<RemotePath>::iterator path(paths.begin());path!=paths.end();++path) {
  400. memcpy(&(p->paths[p->pathCount].address),&(path->address()),sizeof(struct sockaddr_storage));
  401. p->paths[p->pathCount].lastSend = path->lastSend();
  402. p->paths[p->pathCount].lastReceive = path->lastReceived();
  403. p->paths[p->pathCount].active = path->active(_now) ? 1 : 0;
  404. p->paths[p->pathCount].preferred = ((bestPath)&&(*path == *bestPath)) ? 1 : 0;
  405. ++p->pathCount;
  406. }
  407. }
  408. return pl;
  409. }
  410. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  411. {
  412. Mutex::Lock _l(_networks_m);
  413. SharedPtr<Network> nw = _network(nwid);
  414. if(nw) {
  415. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  416. nw->externalConfig(nc);
  417. return nc;
  418. }
  419. return (ZT_VirtualNetworkConfig *)0;
  420. }
  421. ZT_VirtualNetworkList *Node::networks() const
  422. {
  423. Mutex::Lock _l(_networks_m);
  424. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  425. if (!buf)
  426. return (ZT_VirtualNetworkList *)0;
  427. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  428. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  429. nl->networkCount = 0;
  430. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  431. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  432. return nl;
  433. }
  434. void Node::freeQueryResult(void *qr)
  435. {
  436. if (qr)
  437. ::free(qr);
  438. }
  439. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr,int metric,ZT_LocalInterfaceAddressTrust trust)
  440. {
  441. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  442. Mutex::Lock _l(_directPaths_m);
  443. _directPaths.push_back(Path(*(reinterpret_cast<const InetAddress *>(addr)),metric,(Path::Trust)trust));
  444. std::sort(_directPaths.begin(),_directPaths.end());
  445. _directPaths.erase(std::unique(_directPaths.begin(),_directPaths.end()),_directPaths.end());
  446. return 1;
  447. }
  448. return 0;
  449. }
  450. void Node::clearLocalInterfaceAddresses()
  451. {
  452. Mutex::Lock _l(_directPaths_m);
  453. _directPaths.clear();
  454. }
  455. void Node::setNetconfMaster(void *networkControllerInstance)
  456. {
  457. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  458. }
  459. ZT_ResultCode Node::circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  460. {
  461. if (test->hopCount > 0) {
  462. try {
  463. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  464. RR->identity.address().appendTo(outp);
  465. outp.append((uint16_t)((test->reportAtEveryHop != 0) ? 0x03 : 0x02));
  466. outp.append((uint64_t)test->timestamp);
  467. outp.append((uint64_t)test->testId);
  468. outp.append((uint16_t)0); // originator credential length, updated later
  469. if (test->credentialNetworkId) {
  470. outp.append((uint8_t)0x01);
  471. outp.append((uint64_t)test->credentialNetworkId);
  472. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23,(uint16_t)9);
  473. }
  474. outp.append((uint16_t)0);
  475. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const char *>(outp.data()) + ZT_PACKET_IDX_PAYLOAD,outp.size() - ZT_PACKET_IDX_PAYLOAD));
  476. outp.append((uint16_t)sig.size());
  477. outp.append(sig.data,sig.size());
  478. outp.append((uint16_t)0); // originator doesn't need an extra credential, since it's the originator
  479. for(unsigned int h=1;h<test->hopCount;++h) {
  480. outp.append((uint8_t)0);
  481. outp.append((uint8_t)(test->hops[h].breadth & 0xff));
  482. for(unsigned int a=0;a<test->hops[h].breadth;++a)
  483. Address(test->hops[h].addresses[a]).appendTo(outp);
  484. }
  485. for(unsigned int a=0;a<test->hops[0].breadth;++a) {
  486. outp.newInitializationVector();
  487. outp.setDestination(Address(test->hops[0].addresses[a]));
  488. RR->sw->send(outp,true,0);
  489. }
  490. } catch ( ... ) {
  491. return ZT_RESULT_FATAL_ERROR_INTERNAL; // probably indicates FIFO too big for packet
  492. }
  493. }
  494. {
  495. test->_internalPtr = reinterpret_cast<void *>(reportCallback);
  496. Mutex::Lock _l(_circuitTests_m);
  497. if (std::find(_circuitTests.begin(),_circuitTests.end(),test) == _circuitTests.end())
  498. _circuitTests.push_back(test);
  499. }
  500. return ZT_RESULT_OK;
  501. }
  502. void Node::circuitTestEnd(ZT_CircuitTest *test)
  503. {
  504. Mutex::Lock _l(_circuitTests_m);
  505. for(;;) {
  506. std::vector< ZT_CircuitTest * >::iterator ct(std::find(_circuitTests.begin(),_circuitTests.end(),test));
  507. if (ct == _circuitTests.end())
  508. break;
  509. else _circuitTests.erase(ct);
  510. }
  511. }
  512. ZT_ResultCode Node::clusterInit(
  513. unsigned int myId,
  514. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  515. unsigned int numZeroTierPhysicalEndpoints,
  516. int x,
  517. int y,
  518. int z,
  519. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  520. void *sendFunctionArg,
  521. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  522. void *addressToLocationFunctionArg)
  523. {
  524. #ifdef ZT_ENABLE_CLUSTER
  525. if (RR->cluster)
  526. return ZT_RESULT_ERROR_BAD_PARAMETER;
  527. std::vector<InetAddress> eps;
  528. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  529. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  530. std::sort(eps.begin(),eps.end());
  531. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  532. return ZT_RESULT_OK;
  533. #else
  534. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  535. #endif
  536. }
  537. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  538. {
  539. #ifdef ZT_ENABLE_CLUSTER
  540. if (!RR->cluster)
  541. return ZT_RESULT_ERROR_BAD_PARAMETER;
  542. RR->cluster->addMember((uint16_t)memberId);
  543. return ZT_RESULT_OK;
  544. #else
  545. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  546. #endif
  547. }
  548. void Node::clusterRemoveMember(unsigned int memberId)
  549. {
  550. #ifdef ZT_ENABLE_CLUSTER
  551. if (RR->cluster)
  552. RR->cluster->removeMember((uint16_t)memberId);
  553. #endif
  554. }
  555. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  556. {
  557. #ifdef ZT_ENABLE_CLUSTER
  558. if (RR->cluster)
  559. RR->cluster->handleIncomingStateMessage(msg,len);
  560. #endif
  561. }
  562. /****************************************************************************/
  563. /* Node methods used only within node/ */
  564. /****************************************************************************/
  565. std::string Node::dataStoreGet(const char *name)
  566. {
  567. char buf[16384];
  568. std::string r;
  569. unsigned long olen = 0;
  570. do {
  571. long n = _dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  572. if (n <= 0)
  573. return std::string();
  574. r.append(buf,n);
  575. } while (r.length() < olen);
  576. return r;
  577. }
  578. #ifdef ZT_TRACE
  579. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  580. {
  581. static Mutex traceLock;
  582. va_list ap;
  583. char tmp1[1024],tmp2[1024],tmp3[256];
  584. Mutex::Lock _l(traceLock);
  585. time_t now = (time_t)(_now / 1000ULL);
  586. #ifdef __WINDOWS__
  587. ctime_s(tmp3,sizeof(tmp3),&now);
  588. char *nowstr = tmp3;
  589. #else
  590. char *nowstr = ctime_r(&now,tmp3);
  591. #endif
  592. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  593. if (nowstr[nowstrlen-1] == '\n')
  594. nowstr[--nowstrlen] = (char)0;
  595. if (nowstr[nowstrlen-1] == '\r')
  596. nowstr[--nowstrlen] = (char)0;
  597. va_start(ap,fmt);
  598. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  599. va_end(ap);
  600. tmp2[sizeof(tmp2)-1] = (char)0;
  601. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  602. postEvent(ZT_EVENT_TRACE,tmp1);
  603. }
  604. #endif // ZT_TRACE
  605. uint64_t Node::prng()
  606. {
  607. unsigned int p = (++_prngStreamPtr % (sizeof(_prngStream) / sizeof(uint64_t)));
  608. if (!p)
  609. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  610. return _prngStream[p];
  611. }
  612. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  613. {
  614. std::vector< ZT_CircuitTest * > toNotify;
  615. {
  616. Mutex::Lock _l(_circuitTests_m);
  617. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  618. if ((*i)->testId == report->testId)
  619. toNotify.push_back(*i);
  620. }
  621. }
  622. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  623. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  624. }
  625. } // namespace ZeroTier
  626. /****************************************************************************/
  627. /* CAPI bindings */
  628. /****************************************************************************/
  629. extern "C" {
  630. enum ZT_ResultCode ZT_Node_new(
  631. ZT_Node **node,
  632. void *uptr,
  633. uint64_t now,
  634. ZT_DataStoreGetFunction dataStoreGetFunction,
  635. ZT_DataStorePutFunction dataStorePutFunction,
  636. ZT_WirePacketSendFunction wirePacketSendFunction,
  637. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  638. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  639. ZT_EventCallback eventCallback)
  640. {
  641. *node = (ZT_Node *)0;
  642. try {
  643. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,eventCallback));
  644. return ZT_RESULT_OK;
  645. } catch (std::bad_alloc &exc) {
  646. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  647. } catch (std::runtime_error &exc) {
  648. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  649. } catch ( ... ) {
  650. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  651. }
  652. }
  653. void ZT_Node_delete(ZT_Node *node)
  654. {
  655. try {
  656. delete (reinterpret_cast<ZeroTier::Node *>(node));
  657. } catch ( ... ) {}
  658. }
  659. enum ZT_ResultCode ZT_Node_processWirePacket(
  660. ZT_Node *node,
  661. uint64_t now,
  662. const struct sockaddr_storage *localAddress,
  663. const struct sockaddr_storage *remoteAddress,
  664. const void *packetData,
  665. unsigned int packetLength,
  666. volatile uint64_t *nextBackgroundTaskDeadline)
  667. {
  668. try {
  669. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  670. } catch (std::bad_alloc &exc) {
  671. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  672. } catch ( ... ) {
  673. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  674. }
  675. }
  676. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  677. ZT_Node *node,
  678. uint64_t now,
  679. uint64_t nwid,
  680. uint64_t sourceMac,
  681. uint64_t destMac,
  682. unsigned int etherType,
  683. unsigned int vlanId,
  684. const void *frameData,
  685. unsigned int frameLength,
  686. volatile uint64_t *nextBackgroundTaskDeadline)
  687. {
  688. try {
  689. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  690. } catch (std::bad_alloc &exc) {
  691. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  692. } catch ( ... ) {
  693. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  694. }
  695. }
  696. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  697. {
  698. try {
  699. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  700. } catch (std::bad_alloc &exc) {
  701. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  702. } catch ( ... ) {
  703. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  704. }
  705. }
  706. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid)
  707. {
  708. try {
  709. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid);
  710. } catch (std::bad_alloc &exc) {
  711. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  712. } catch ( ... ) {
  713. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  714. }
  715. }
  716. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid)
  717. {
  718. try {
  719. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid);
  720. } catch (std::bad_alloc &exc) {
  721. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  722. } catch ( ... ) {
  723. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  724. }
  725. }
  726. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  727. {
  728. try {
  729. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  730. } catch (std::bad_alloc &exc) {
  731. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  732. } catch ( ... ) {
  733. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  734. }
  735. }
  736. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  737. {
  738. try {
  739. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  740. } catch (std::bad_alloc &exc) {
  741. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  742. } catch ( ... ) {
  743. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  744. }
  745. }
  746. uint64_t ZT_Node_address(ZT_Node *node)
  747. {
  748. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  749. }
  750. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  751. {
  752. try {
  753. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  754. } catch ( ... ) {}
  755. }
  756. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  757. {
  758. try {
  759. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  760. } catch ( ... ) {
  761. return (ZT_PeerList *)0;
  762. }
  763. }
  764. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  765. {
  766. try {
  767. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  768. } catch ( ... ) {
  769. return (ZT_VirtualNetworkConfig *)0;
  770. }
  771. }
  772. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  773. {
  774. try {
  775. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  776. } catch ( ... ) {
  777. return (ZT_VirtualNetworkList *)0;
  778. }
  779. }
  780. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  781. {
  782. try {
  783. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  784. } catch ( ... ) {}
  785. }
  786. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr,int metric, enum ZT_LocalInterfaceAddressTrust trust)
  787. {
  788. try {
  789. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr,metric,trust);
  790. } catch ( ... ) {
  791. return 0;
  792. }
  793. }
  794. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  795. {
  796. try {
  797. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  798. } catch ( ... ) {}
  799. }
  800. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  801. {
  802. try {
  803. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  804. } catch ( ... ) {}
  805. }
  806. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  807. {
  808. try {
  809. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(test,reportCallback);
  810. } catch ( ... ) {
  811. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  812. }
  813. }
  814. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  815. {
  816. try {
  817. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  818. } catch ( ... ) {}
  819. }
  820. enum ZT_ResultCode ZT_Node_clusterInit(
  821. ZT_Node *node,
  822. unsigned int myId,
  823. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  824. unsigned int numZeroTierPhysicalEndpoints,
  825. int x,
  826. int y,
  827. int z,
  828. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  829. void *sendFunctionArg,
  830. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  831. void *addressToLocationFunctionArg)
  832. {
  833. try {
  834. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  835. } catch ( ... ) {
  836. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  837. }
  838. }
  839. /**
  840. * Add a member to this cluster
  841. *
  842. * Calling this without having called clusterInit() will do nothing.
  843. *
  844. * @param node Node instance
  845. * @param memberId Member ID (must be less than or equal to ZT_CLUSTER_MAX_MEMBERS)
  846. * @return OK or error if clustering is disabled, ID invalid, etc.
  847. */
  848. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  849. {
  850. try {
  851. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  852. } catch ( ... ) {
  853. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  854. }
  855. }
  856. /**
  857. * Remove a member from this cluster
  858. *
  859. * Calling this without having called clusterInit() will do nothing.
  860. *
  861. * @param node Node instance
  862. * @param memberId Member ID to remove (nothing happens if not present)
  863. */
  864. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  865. {
  866. try {
  867. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  868. } catch ( ... ) {}
  869. }
  870. /**
  871. * Handle an incoming cluster state message
  872. *
  873. * The message itself contains cluster member IDs, and invalid or badly
  874. * addressed messages will be silently discarded.
  875. *
  876. * Calling this without having called clusterInit() will do nothing.
  877. *
  878. * @param node Node instance
  879. * @param msg Cluster message
  880. * @param len Length of cluster message
  881. */
  882. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  883. {
  884. try {
  885. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  886. } catch ( ... ) {}
  887. }
  888. void ZT_version(int *major,int *minor,int *revision,unsigned long *featureFlags)
  889. {
  890. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  891. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  892. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  893. if (featureFlags) {
  894. *featureFlags = (
  895. ZT_FEATURE_FLAG_THREAD_SAFE
  896. );
  897. }
  898. }
  899. } // extern "C"