Node.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <stdarg.h>
  21. #include <string.h>
  22. #include <stdint.h>
  23. #include "../version.h"
  24. #include "Constants.hpp"
  25. #include "Node.hpp"
  26. #include "RuntimeEnvironment.hpp"
  27. #include "NetworkController.hpp"
  28. #include "Switch.hpp"
  29. #include "Multicaster.hpp"
  30. #include "Topology.hpp"
  31. #include "Buffer.hpp"
  32. #include "Packet.hpp"
  33. #include "Address.hpp"
  34. #include "Identity.hpp"
  35. #include "SelfAwareness.hpp"
  36. #include "Cluster.hpp"
  37. #include "DeferredPackets.hpp"
  38. const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
  39. namespace ZeroTier {
  40. /****************************************************************************/
  41. /* Public Node interface (C++, exposed via CAPI bindings) */
  42. /****************************************************************************/
  43. Node::Node(
  44. uint64_t now,
  45. void *uptr,
  46. ZT_DataStoreGetFunction dataStoreGetFunction,
  47. ZT_DataStorePutFunction dataStorePutFunction,
  48. ZT_WirePacketSendFunction wirePacketSendFunction,
  49. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  50. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  51. ZT_PathCheckFunction pathCheckFunction,
  52. ZT_EventCallback eventCallback) :
  53. _RR(this),
  54. RR(&_RR),
  55. _uPtr(uptr),
  56. _dataStoreGetFunction(dataStoreGetFunction),
  57. _dataStorePutFunction(dataStorePutFunction),
  58. _wirePacketSendFunction(wirePacketSendFunction),
  59. _virtualNetworkFrameFunction(virtualNetworkFrameFunction),
  60. _virtualNetworkConfigFunction(virtualNetworkConfigFunction),
  61. _pathCheckFunction(pathCheckFunction),
  62. _eventCallback(eventCallback),
  63. _networks(),
  64. _networks_m(),
  65. _prngStreamPtr(0),
  66. _now(now),
  67. _lastPingCheck(0),
  68. _lastHousekeepingRun(0)
  69. {
  70. _online = false;
  71. // Use Salsa20 alone as a high-quality non-crypto PRNG
  72. {
  73. char foo[32];
  74. Utils::getSecureRandom(foo,32);
  75. _prng.init(foo,256,foo);
  76. memset(_prngStream,0,sizeof(_prngStream));
  77. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  78. }
  79. {
  80. std::string idtmp(dataStoreGet("identity.secret"));
  81. if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
  82. TRACE("identity.secret not found, generating...");
  83. RR->identity.generate();
  84. idtmp = RR->identity.toString(true);
  85. if (!dataStorePut("identity.secret",idtmp,true))
  86. throw std::runtime_error("unable to write identity.secret");
  87. }
  88. RR->publicIdentityStr = RR->identity.toString(false);
  89. RR->secretIdentityStr = RR->identity.toString(true);
  90. idtmp = dataStoreGet("identity.public");
  91. if (idtmp != RR->publicIdentityStr) {
  92. if (!dataStorePut("identity.public",RR->publicIdentityStr,false))
  93. throw std::runtime_error("unable to write identity.public");
  94. }
  95. }
  96. try {
  97. RR->sw = new Switch(RR);
  98. RR->mc = new Multicaster(RR);
  99. RR->topology = new Topology(RR);
  100. RR->sa = new SelfAwareness(RR);
  101. RR->dp = new DeferredPackets(RR);
  102. } catch ( ... ) {
  103. delete RR->dp;
  104. delete RR->sa;
  105. delete RR->topology;
  106. delete RR->mc;
  107. delete RR->sw;
  108. throw;
  109. }
  110. postEvent(ZT_EVENT_UP);
  111. }
  112. Node::~Node()
  113. {
  114. Mutex::Lock _l(_networks_m);
  115. _networks.clear(); // ensure that networks are destroyed before shutdow
  116. RR->dpEnabled = 0;
  117. delete RR->dp;
  118. delete RR->sa;
  119. delete RR->topology;
  120. delete RR->mc;
  121. delete RR->sw;
  122. #ifdef ZT_ENABLE_CLUSTER
  123. delete RR->cluster;
  124. #endif
  125. }
  126. ZT_ResultCode Node::processWirePacket(
  127. uint64_t now,
  128. const struct sockaddr_storage *localAddress,
  129. const struct sockaddr_storage *remoteAddress,
  130. const void *packetData,
  131. unsigned int packetLength,
  132. volatile uint64_t *nextBackgroundTaskDeadline)
  133. {
  134. _now = now;
  135. RR->sw->onRemotePacket(*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  136. return ZT_RESULT_OK;
  137. }
  138. ZT_ResultCode Node::processVirtualNetworkFrame(
  139. uint64_t now,
  140. uint64_t nwid,
  141. uint64_t sourceMac,
  142. uint64_t destMac,
  143. unsigned int etherType,
  144. unsigned int vlanId,
  145. const void *frameData,
  146. unsigned int frameLength,
  147. volatile uint64_t *nextBackgroundTaskDeadline)
  148. {
  149. _now = now;
  150. SharedPtr<Network> nw(this->network(nwid));
  151. if (nw) {
  152. RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  153. return ZT_RESULT_OK;
  154. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  155. }
  156. class _PingPeersThatNeedPing
  157. {
  158. public:
  159. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now,const std::vector< std::pair<Address,InetAddress> > &relays) :
  160. lastReceiveFromUpstream(0),
  161. RR(renv),
  162. _now(now),
  163. _relays(relays),
  164. _world(RR->topology->world())
  165. {
  166. }
  167. uint64_t lastReceiveFromUpstream; // tracks last time we got a packet from an 'upstream' peer like a root or a relay
  168. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  169. {
  170. bool upstream = false;
  171. InetAddress stableEndpoint4,stableEndpoint6;
  172. // 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.
  173. for(std::vector<World::Root>::const_iterator r(_world.roots().begin());r!=_world.roots().end();++r) {
  174. if (r->identity.address() == p->address()) {
  175. upstream = true;
  176. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)r->stableEndpoints.size();++k) {
  177. const InetAddress &addr = r->stableEndpoints[ptr++ % r->stableEndpoints.size()];
  178. if (!stableEndpoint4) {
  179. if (addr.ss_family == AF_INET)
  180. stableEndpoint4 = addr;
  181. }
  182. if (!stableEndpoint6) {
  183. if (addr.ss_family == AF_INET6)
  184. stableEndpoint6 = addr;
  185. }
  186. }
  187. break;
  188. }
  189. }
  190. if (!upstream) {
  191. // If I am a root server, only ping other root servers -- roots don't ping "down"
  192. // since that would just be a waste of bandwidth and could potentially cause route
  193. // flapping in Cluster mode.
  194. if (RR->topology->amRoot())
  195. return;
  196. // Check for network preferred relays, also considered 'upstream' and thus always
  197. // pinged to keep links up. If they have stable addresses we will try them there.
  198. for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(_relays.begin());r!=_relays.end();++r) {
  199. if (r->first == p->address()) {
  200. if (r->second.ss_family == AF_INET)
  201. stableEndpoint4 = r->second;
  202. else if (r->second.ss_family == AF_INET6)
  203. stableEndpoint6 = r->second;
  204. upstream = true;
  205. break;
  206. }
  207. }
  208. }
  209. if (upstream) {
  210. // "Upstream" devices are roots and relays and get special treatment -- they stay alive
  211. // forever and we try to keep (if available) both IPv4 and IPv6 channels open to them.
  212. bool needToContactIndirect = true;
  213. if (p->doPingAndKeepalive(_now,AF_INET)) {
  214. needToContactIndirect = false;
  215. } else {
  216. if (stableEndpoint4) {
  217. needToContactIndirect = false;
  218. p->sendHELLO(InetAddress(),stableEndpoint4,_now);
  219. }
  220. }
  221. if (p->doPingAndKeepalive(_now,AF_INET6)) {
  222. needToContactIndirect = false;
  223. } else {
  224. if (stableEndpoint6) {
  225. needToContactIndirect = false;
  226. p->sendHELLO(InetAddress(),stableEndpoint6,_now);
  227. }
  228. }
  229. if (needToContactIndirect) {
  230. // If this is an upstream and we have no stable endpoint for either IPv4 or IPv6,
  231. // send a NOP indirectly if possible to see if we can get to this peer in any
  232. // way whatsoever. This will e.g. find network preferred relays that lack
  233. // stable endpoints by using root servers.
  234. Packet outp(p->address(),RR->identity.address(),Packet::VERB_NOP);
  235. RR->sw->send(outp,true,0);
  236. }
  237. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  238. } else if (p->activelyTransferringFrames(_now)) {
  239. // Normal nodes get their preferred link kept alive if the node has generated frame traffic recently
  240. p->doPingAndKeepalive(_now,0);
  241. }
  242. }
  243. private:
  244. const RuntimeEnvironment *RR;
  245. uint64_t _now;
  246. const std::vector< std::pair<Address,InetAddress> > &_relays;
  247. World _world;
  248. };
  249. ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  250. {
  251. _now = now;
  252. Mutex::Lock bl(_backgroundTasksLock);
  253. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  254. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  255. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  256. try {
  257. _lastPingCheck = now;
  258. // Get relays and networks that need config without leaving the mutex locked
  259. std::vector< std::pair<Address,InetAddress> > networkRelays;
  260. std::vector< SharedPtr<Network> > needConfig;
  261. {
  262. Mutex::Lock _l(_networks_m);
  263. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  264. SharedPtr<NetworkConfig> nc(n->second->config2());
  265. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!nc))
  266. needConfig.push_back(n->second);
  267. if (nc)
  268. networkRelays.insert(networkRelays.end(),nc->relays().begin(),nc->relays().end());
  269. }
  270. }
  271. // Request updated configuration for networks that need it
  272. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  273. (*n)->requestConfiguration();
  274. // Do pings and keepalives
  275. _PingPeersThatNeedPing pfunc(RR,now,networkRelays);
  276. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  277. // Update online status, post status change as event
  278. const bool oldOnline = _online;
  279. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  280. if (oldOnline != _online)
  281. postEvent(_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  282. } catch ( ... ) {
  283. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  284. }
  285. } else {
  286. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  287. }
  288. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  289. try {
  290. _lastHousekeepingRun = now;
  291. RR->topology->clean(now);
  292. RR->sa->clean(now);
  293. RR->mc->clean(now);
  294. } catch ( ... ) {
  295. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  296. }
  297. }
  298. try {
  299. #ifdef ZT_ENABLE_CLUSTER
  300. // If clustering is enabled we have to call cluster->doPeriodicTasks() very often, so we override normal timer deadline behavior
  301. if (RR->cluster) {
  302. RR->sw->doTimerTasks(now);
  303. RR->cluster->doPeriodicTasks();
  304. *nextBackgroundTaskDeadline = now + ZT_CLUSTER_PERIODIC_TASK_PERIOD; // this is really short so just tick at this rate
  305. } else {
  306. #endif
  307. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  308. #ifdef ZT_ENABLE_CLUSTER
  309. }
  310. #endif
  311. } catch ( ... ) {
  312. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  313. }
  314. return ZT_RESULT_OK;
  315. }
  316. ZT_ResultCode Node::join(uint64_t nwid,void *uptr)
  317. {
  318. Mutex::Lock _l(_networks_m);
  319. SharedPtr<Network> nw = _network(nwid);
  320. if(!nw)
  321. _networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid,uptr))));
  322. std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
  323. return ZT_RESULT_OK;
  324. }
  325. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr)
  326. {
  327. std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
  328. Mutex::Lock _l(_networks_m);
  329. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  330. if (n->first != nwid)
  331. newn.push_back(*n);
  332. else {
  333. if (uptr)
  334. *uptr = n->second->userPtr();
  335. n->second->destroy();
  336. }
  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<Path> paths(pi->second->paths());
  397. Path *bestPath = pi->second->getBestPath(_now);
  398. p->pathCount = 0;
  399. for(std::vector<Path>::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)
  440. {
  441. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  442. Mutex::Lock _l(_directPaths_m);
  443. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  444. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  445. return 1;
  446. }
  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,(unsigned int)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. void Node::clusterStatus(ZT_ClusterStatus *cs)
  563. {
  564. if (!cs)
  565. return;
  566. #ifdef ZT_ENABLE_CLUSTER
  567. if (RR->cluster)
  568. RR->cluster->status(*cs);
  569. else
  570. #endif
  571. memset(cs,0,sizeof(ZT_ClusterStatus));
  572. }
  573. void Node::backgroundThreadMain()
  574. {
  575. ++RR->dpEnabled;
  576. for(;;) {
  577. try {
  578. if (RR->dp->process() < 0)
  579. break;
  580. } catch ( ... ) {} // sanity check -- should not throw
  581. }
  582. --RR->dpEnabled;
  583. }
  584. /****************************************************************************/
  585. /* Node methods used only within node/ */
  586. /****************************************************************************/
  587. std::string Node::dataStoreGet(const char *name)
  588. {
  589. char buf[1024];
  590. std::string r;
  591. unsigned long olen = 0;
  592. do {
  593. long n = _dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  594. if (n <= 0)
  595. return std::string();
  596. r.append(buf,n);
  597. } while (r.length() < olen);
  598. return r;
  599. }
  600. bool Node::shouldUsePathForZeroTierTraffic(const InetAddress &localAddress,const InetAddress &remoteAddress)
  601. {
  602. if (!Path::isAddressValidForPath(remoteAddress))
  603. return false;
  604. {
  605. Mutex::Lock _l(_networks_m);
  606. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  607. SharedPtr<NetworkConfig> nc(i->second->config2());
  608. if (nc) {
  609. for(std::vector<InetAddress>::const_iterator a(nc->staticIps().begin());a!=nc->staticIps().end();++a) {
  610. if (a->containsAddress(remoteAddress)) {
  611. return false;
  612. }
  613. }
  614. }
  615. }
  616. }
  617. if (_pathCheckFunction)
  618. return (_pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,reinterpret_cast<const struct sockaddr_storage *>(&localAddress),reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  619. else return true;
  620. }
  621. #ifdef ZT_TRACE
  622. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  623. {
  624. static Mutex traceLock;
  625. va_list ap;
  626. char tmp1[1024],tmp2[1024],tmp3[256];
  627. Mutex::Lock _l(traceLock);
  628. time_t now = (time_t)(_now / 1000ULL);
  629. #ifdef __WINDOWS__
  630. ctime_s(tmp3,sizeof(tmp3),&now);
  631. char *nowstr = tmp3;
  632. #else
  633. char *nowstr = ctime_r(&now,tmp3);
  634. #endif
  635. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  636. if (nowstr[nowstrlen-1] == '\n')
  637. nowstr[--nowstrlen] = (char)0;
  638. if (nowstr[nowstrlen-1] == '\r')
  639. nowstr[--nowstrlen] = (char)0;
  640. va_start(ap,fmt);
  641. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  642. va_end(ap);
  643. tmp2[sizeof(tmp2)-1] = (char)0;
  644. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  645. postEvent(ZT_EVENT_TRACE,tmp1);
  646. }
  647. #endif // ZT_TRACE
  648. uint64_t Node::prng()
  649. {
  650. unsigned int p = (++_prngStreamPtr % (sizeof(_prngStream) / sizeof(uint64_t)));
  651. if (!p)
  652. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  653. return _prngStream[p];
  654. }
  655. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  656. {
  657. std::vector< ZT_CircuitTest * > toNotify;
  658. {
  659. Mutex::Lock _l(_circuitTests_m);
  660. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  661. if ((*i)->testId == report->testId)
  662. toNotify.push_back(*i);
  663. }
  664. }
  665. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  666. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  667. }
  668. } // namespace ZeroTier
  669. /****************************************************************************/
  670. /* CAPI bindings */
  671. /****************************************************************************/
  672. extern "C" {
  673. enum ZT_ResultCode ZT_Node_new(
  674. ZT_Node **node,
  675. void *uptr,
  676. uint64_t now,
  677. ZT_DataStoreGetFunction dataStoreGetFunction,
  678. ZT_DataStorePutFunction dataStorePutFunction,
  679. ZT_WirePacketSendFunction wirePacketSendFunction,
  680. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  681. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  682. ZT_PathCheckFunction pathCheckFunction,
  683. ZT_EventCallback eventCallback)
  684. {
  685. *node = (ZT_Node *)0;
  686. try {
  687. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,pathCheckFunction,eventCallback));
  688. return ZT_RESULT_OK;
  689. } catch (std::bad_alloc &exc) {
  690. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  691. } catch (std::runtime_error &exc) {
  692. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  693. } catch ( ... ) {
  694. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  695. }
  696. }
  697. void ZT_Node_delete(ZT_Node *node)
  698. {
  699. try {
  700. delete (reinterpret_cast<ZeroTier::Node *>(node));
  701. } catch ( ... ) {}
  702. }
  703. enum ZT_ResultCode ZT_Node_processWirePacket(
  704. ZT_Node *node,
  705. uint64_t now,
  706. const struct sockaddr_storage *localAddress,
  707. const struct sockaddr_storage *remoteAddress,
  708. const void *packetData,
  709. unsigned int packetLength,
  710. volatile uint64_t *nextBackgroundTaskDeadline)
  711. {
  712. try {
  713. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  714. } catch (std::bad_alloc &exc) {
  715. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  716. } catch ( ... ) {
  717. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  718. }
  719. }
  720. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  721. ZT_Node *node,
  722. uint64_t now,
  723. uint64_t nwid,
  724. uint64_t sourceMac,
  725. uint64_t destMac,
  726. unsigned int etherType,
  727. unsigned int vlanId,
  728. const void *frameData,
  729. unsigned int frameLength,
  730. volatile uint64_t *nextBackgroundTaskDeadline)
  731. {
  732. try {
  733. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  734. } catch (std::bad_alloc &exc) {
  735. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  736. } catch ( ... ) {
  737. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  738. }
  739. }
  740. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  741. {
  742. try {
  743. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  744. } catch (std::bad_alloc &exc) {
  745. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  746. } catch ( ... ) {
  747. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  748. }
  749. }
  750. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr)
  751. {
  752. try {
  753. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr);
  754. } catch (std::bad_alloc &exc) {
  755. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  756. } catch ( ... ) {
  757. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  758. }
  759. }
  760. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr)
  761. {
  762. try {
  763. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr);
  764. } catch (std::bad_alloc &exc) {
  765. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  766. } catch ( ... ) {
  767. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  768. }
  769. }
  770. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  771. {
  772. try {
  773. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  774. } catch (std::bad_alloc &exc) {
  775. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  776. } catch ( ... ) {
  777. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  778. }
  779. }
  780. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  781. {
  782. try {
  783. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  784. } catch (std::bad_alloc &exc) {
  785. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  786. } catch ( ... ) {
  787. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  788. }
  789. }
  790. uint64_t ZT_Node_address(ZT_Node *node)
  791. {
  792. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  793. }
  794. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  795. {
  796. try {
  797. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  798. } catch ( ... ) {}
  799. }
  800. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  801. {
  802. try {
  803. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  804. } catch ( ... ) {
  805. return (ZT_PeerList *)0;
  806. }
  807. }
  808. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  809. {
  810. try {
  811. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  812. } catch ( ... ) {
  813. return (ZT_VirtualNetworkConfig *)0;
  814. }
  815. }
  816. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  817. {
  818. try {
  819. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  820. } catch ( ... ) {
  821. return (ZT_VirtualNetworkList *)0;
  822. }
  823. }
  824. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  825. {
  826. try {
  827. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  828. } catch ( ... ) {}
  829. }
  830. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  831. {
  832. try {
  833. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  834. } catch ( ... ) {
  835. return 0;
  836. }
  837. }
  838. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  839. {
  840. try {
  841. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  842. } catch ( ... ) {}
  843. }
  844. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  845. {
  846. try {
  847. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  848. } catch ( ... ) {}
  849. }
  850. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  851. {
  852. try {
  853. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(test,reportCallback);
  854. } catch ( ... ) {
  855. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  856. }
  857. }
  858. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  859. {
  860. try {
  861. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  862. } catch ( ... ) {}
  863. }
  864. enum ZT_ResultCode ZT_Node_clusterInit(
  865. ZT_Node *node,
  866. unsigned int myId,
  867. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  868. unsigned int numZeroTierPhysicalEndpoints,
  869. int x,
  870. int y,
  871. int z,
  872. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  873. void *sendFunctionArg,
  874. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  875. void *addressToLocationFunctionArg)
  876. {
  877. try {
  878. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  879. } catch ( ... ) {
  880. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  881. }
  882. }
  883. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  884. {
  885. try {
  886. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  887. } catch ( ... ) {
  888. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  889. }
  890. }
  891. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  892. {
  893. try {
  894. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  895. } catch ( ... ) {}
  896. }
  897. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  898. {
  899. try {
  900. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  901. } catch ( ... ) {}
  902. }
  903. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  904. {
  905. try {
  906. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  907. } catch ( ... ) {}
  908. }
  909. void ZT_Node_backgroundThreadMain(ZT_Node *node)
  910. {
  911. try {
  912. reinterpret_cast<ZeroTier::Node *>(node)->backgroundThreadMain();
  913. } catch ( ... ) {}
  914. }
  915. void ZT_version(int *major,int *minor,int *revision,unsigned long *featureFlags)
  916. {
  917. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  918. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  919. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  920. if (featureFlags) {
  921. *featureFlags = (
  922. ZT_FEATURE_FLAG_THREAD_SAFE
  923. );
  924. }
  925. }
  926. } // extern "C"