Node.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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<ZT_VirtualNetworkStaticDevice> &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 == p->identity()) {
  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<ZT_VirtualNetworkStaticDevice>::const_iterator r(_relays.begin());r!=_relays.end();++r) {
  199. if (r->address == p->address().toInt()) {
  200. for(unsigned int i=0;i<2;++i) {
  201. if (r->physical[i].ss_family == AF_INET)
  202. stableEndpoint4 = r->physical[i];
  203. else if (r->physical[i].ss_family == AF_INET6)
  204. stableEndpoint6 = r->physical[i];
  205. }
  206. upstream = true;
  207. break;
  208. }
  209. }
  210. }
  211. if (upstream) {
  212. // "Upstream" devices are roots and relays and get special treatment -- they stay alive
  213. // forever and we try to keep (if available) both IPv4 and IPv6 channels open to them.
  214. bool needToContactIndirect = true;
  215. if (p->doPingAndKeepalive(_now,AF_INET)) {
  216. needToContactIndirect = false;
  217. } else {
  218. if (stableEndpoint4) {
  219. needToContactIndirect = false;
  220. p->sendHELLO(InetAddress(),stableEndpoint4,_now);
  221. }
  222. }
  223. if (p->doPingAndKeepalive(_now,AF_INET6)) {
  224. needToContactIndirect = false;
  225. } else {
  226. if (stableEndpoint6) {
  227. needToContactIndirect = false;
  228. p->sendHELLO(InetAddress(),stableEndpoint6,_now);
  229. }
  230. }
  231. if (needToContactIndirect) {
  232. // If this is an upstream and we have no stable endpoint for either IPv4 or IPv6,
  233. // send a NOP indirectly if possible to see if we can get to this peer in any
  234. // way whatsoever. This will e.g. find network preferred relays that lack
  235. // stable endpoints by using root servers.
  236. Packet outp(p->address(),RR->identity.address(),Packet::VERB_NOP);
  237. RR->sw->send(outp,true,0);
  238. }
  239. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  240. } else if (p->activelyTransferringFrames(_now)) {
  241. // Normal nodes get their preferred link kept alive if the node has generated frame traffic recently
  242. p->doPingAndKeepalive(_now,0);
  243. }
  244. }
  245. private:
  246. const RuntimeEnvironment *RR;
  247. uint64_t _now;
  248. const std::vector<ZT_VirtualNetworkStaticDevice> &_relays;
  249. World _world;
  250. };
  251. ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  252. {
  253. _now = now;
  254. Mutex::Lock bl(_backgroundTasksLock);
  255. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  256. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  257. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  258. try {
  259. _lastPingCheck = now;
  260. // Get relays and networks that need config without leaving the mutex locked
  261. std::vector< ZT_VirtualNetworkStaticDevice > networkRelays;
  262. std::vector< SharedPtr<Network> > needConfig;
  263. {
  264. Mutex::Lock _l(_networks_m);
  265. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  266. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!n->second->hasConfig())) {
  267. needConfig.push_back(n->second);
  268. }
  269. if (n->second->hasConfig()) {
  270. std::vector<ZT_VirtualNetworkStaticDevice> r(n->second->config().relays());
  271. networkRelays.insert(networkRelays.end(),r.begin(),r.end());
  272. }
  273. }
  274. }
  275. // Request updated configuration for networks that need it
  276. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  277. (*n)->requestConfiguration();
  278. // Do pings and keepalives
  279. _PingPeersThatNeedPing pfunc(RR,now,networkRelays);
  280. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  281. // Update online status, post status change as event
  282. const bool oldOnline = _online;
  283. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  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,void *uptr)
  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,uptr))));
  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,void **uptr)
  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 {
  337. if (uptr)
  338. *uptr = n->second->userPtr();
  339. n->second->destroy();
  340. }
  341. }
  342. _networks.swap(newn);
  343. return ZT_RESULT_OK;
  344. }
  345. ZT_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  346. {
  347. SharedPtr<Network> nw(this->network(nwid));
  348. if (nw) {
  349. nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  350. return ZT_RESULT_OK;
  351. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  352. }
  353. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  354. {
  355. SharedPtr<Network> nw(this->network(nwid));
  356. if (nw) {
  357. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  358. return ZT_RESULT_OK;
  359. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  360. }
  361. uint64_t Node::address() const
  362. {
  363. return RR->identity.address().toInt();
  364. }
  365. void Node::status(ZT_NodeStatus *status) const
  366. {
  367. status->address = RR->identity.address().toInt();
  368. status->worldId = RR->topology->worldId();
  369. status->worldTimestamp = RR->topology->worldTimestamp();
  370. status->publicIdentity = RR->publicIdentityStr.c_str();
  371. status->secretIdentity = RR->secretIdentityStr.c_str();
  372. status->online = _online ? 1 : 0;
  373. }
  374. ZT_PeerList *Node::peers() const
  375. {
  376. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  377. std::sort(peers.begin(),peers.end());
  378. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  379. if (!buf)
  380. return (ZT_PeerList *)0;
  381. ZT_PeerList *pl = (ZT_PeerList *)buf;
  382. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  383. pl->peerCount = 0;
  384. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  385. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  386. p->address = pi->second->address().toInt();
  387. p->lastUnicastFrame = pi->second->lastUnicastFrame();
  388. p->lastMulticastFrame = pi->second->lastMulticastFrame();
  389. if (pi->second->remoteVersionKnown()) {
  390. p->versionMajor = pi->second->remoteVersionMajor();
  391. p->versionMinor = pi->second->remoteVersionMinor();
  392. p->versionRev = pi->second->remoteVersionRevision();
  393. } else {
  394. p->versionMajor = -1;
  395. p->versionMinor = -1;
  396. p->versionRev = -1;
  397. }
  398. p->latency = pi->second->latency();
  399. p->role = RR->topology->isRoot(pi->second->identity()) ? ZT_PEER_ROLE_ROOT : ZT_PEER_ROLE_LEAF;
  400. std::vector<Path> paths(pi->second->paths());
  401. Path *bestPath = pi->second->getBestPath(_now);
  402. p->pathCount = 0;
  403. for(std::vector<Path>::iterator path(paths.begin());path!=paths.end();++path) {
  404. memcpy(&(p->paths[p->pathCount].address),&(path->address()),sizeof(struct sockaddr_storage));
  405. p->paths[p->pathCount].lastSend = path->lastSend();
  406. p->paths[p->pathCount].lastReceive = path->lastReceived();
  407. p->paths[p->pathCount].active = path->active(_now) ? 1 : 0;
  408. p->paths[p->pathCount].preferred = ((bestPath)&&(*path == *bestPath)) ? 1 : 0;
  409. ++p->pathCount;
  410. }
  411. }
  412. return pl;
  413. }
  414. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  415. {
  416. Mutex::Lock _l(_networks_m);
  417. SharedPtr<Network> nw = _network(nwid);
  418. if(nw) {
  419. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  420. nw->externalConfig(nc);
  421. return nc;
  422. }
  423. return (ZT_VirtualNetworkConfig *)0;
  424. }
  425. ZT_VirtualNetworkList *Node::networks() const
  426. {
  427. Mutex::Lock _l(_networks_m);
  428. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  429. if (!buf)
  430. return (ZT_VirtualNetworkList *)0;
  431. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  432. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  433. nl->networkCount = 0;
  434. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  435. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  436. return nl;
  437. }
  438. void Node::freeQueryResult(void *qr)
  439. {
  440. if (qr)
  441. ::free(qr);
  442. }
  443. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  444. {
  445. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  446. Mutex::Lock _l(_directPaths_m);
  447. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  448. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  449. return 1;
  450. }
  451. }
  452. return 0;
  453. }
  454. void Node::clearLocalInterfaceAddresses()
  455. {
  456. Mutex::Lock _l(_directPaths_m);
  457. _directPaths.clear();
  458. }
  459. void Node::setNetconfMaster(void *networkControllerInstance)
  460. {
  461. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  462. }
  463. ZT_ResultCode Node::circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  464. {
  465. if (test->hopCount > 0) {
  466. try {
  467. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  468. RR->identity.address().appendTo(outp);
  469. outp.append((uint16_t)((test->reportAtEveryHop != 0) ? 0x03 : 0x02));
  470. outp.append((uint64_t)test->timestamp);
  471. outp.append((uint64_t)test->testId);
  472. outp.append((uint16_t)0); // originator credential length, updated later
  473. if (test->credentialNetworkId) {
  474. outp.append((uint8_t)0x01);
  475. outp.append((uint64_t)test->credentialNetworkId);
  476. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23,(uint16_t)9);
  477. }
  478. outp.append((uint16_t)0);
  479. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const char *>(outp.data()) + ZT_PACKET_IDX_PAYLOAD,outp.size() - ZT_PACKET_IDX_PAYLOAD));
  480. outp.append((uint16_t)sig.size());
  481. outp.append(sig.data,(unsigned int)sig.size());
  482. outp.append((uint16_t)0); // originator doesn't need an extra credential, since it's the originator
  483. for(unsigned int h=1;h<test->hopCount;++h) {
  484. outp.append((uint8_t)0);
  485. outp.append((uint8_t)(test->hops[h].breadth & 0xff));
  486. for(unsigned int a=0;a<test->hops[h].breadth;++a)
  487. Address(test->hops[h].addresses[a]).appendTo(outp);
  488. }
  489. for(unsigned int a=0;a<test->hops[0].breadth;++a) {
  490. outp.newInitializationVector();
  491. outp.setDestination(Address(test->hops[0].addresses[a]));
  492. RR->sw->send(outp,true,0);
  493. }
  494. } catch ( ... ) {
  495. return ZT_RESULT_FATAL_ERROR_INTERNAL; // probably indicates FIFO too big for packet
  496. }
  497. }
  498. {
  499. test->_internalPtr = reinterpret_cast<void *>(reportCallback);
  500. Mutex::Lock _l(_circuitTests_m);
  501. if (std::find(_circuitTests.begin(),_circuitTests.end(),test) == _circuitTests.end())
  502. _circuitTests.push_back(test);
  503. }
  504. return ZT_RESULT_OK;
  505. }
  506. void Node::circuitTestEnd(ZT_CircuitTest *test)
  507. {
  508. Mutex::Lock _l(_circuitTests_m);
  509. for(;;) {
  510. std::vector< ZT_CircuitTest * >::iterator ct(std::find(_circuitTests.begin(),_circuitTests.end(),test));
  511. if (ct == _circuitTests.end())
  512. break;
  513. else _circuitTests.erase(ct);
  514. }
  515. }
  516. ZT_ResultCode Node::clusterInit(
  517. unsigned int myId,
  518. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  519. unsigned int numZeroTierPhysicalEndpoints,
  520. int x,
  521. int y,
  522. int z,
  523. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  524. void *sendFunctionArg,
  525. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  526. void *addressToLocationFunctionArg)
  527. {
  528. #ifdef ZT_ENABLE_CLUSTER
  529. if (RR->cluster)
  530. return ZT_RESULT_ERROR_BAD_PARAMETER;
  531. std::vector<InetAddress> eps;
  532. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  533. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  534. std::sort(eps.begin(),eps.end());
  535. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  536. return ZT_RESULT_OK;
  537. #else
  538. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  539. #endif
  540. }
  541. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  542. {
  543. #ifdef ZT_ENABLE_CLUSTER
  544. if (!RR->cluster)
  545. return ZT_RESULT_ERROR_BAD_PARAMETER;
  546. RR->cluster->addMember((uint16_t)memberId);
  547. return ZT_RESULT_OK;
  548. #else
  549. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  550. #endif
  551. }
  552. void Node::clusterRemoveMember(unsigned int memberId)
  553. {
  554. #ifdef ZT_ENABLE_CLUSTER
  555. if (RR->cluster)
  556. RR->cluster->removeMember((uint16_t)memberId);
  557. #endif
  558. }
  559. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  560. {
  561. #ifdef ZT_ENABLE_CLUSTER
  562. if (RR->cluster)
  563. RR->cluster->handleIncomingStateMessage(msg,len);
  564. #endif
  565. }
  566. void Node::clusterStatus(ZT_ClusterStatus *cs)
  567. {
  568. if (!cs)
  569. return;
  570. #ifdef ZT_ENABLE_CLUSTER
  571. if (RR->cluster)
  572. RR->cluster->status(*cs);
  573. else
  574. #endif
  575. memset(cs,0,sizeof(ZT_ClusterStatus));
  576. }
  577. void Node::backgroundThreadMain()
  578. {
  579. ++RR->dpEnabled;
  580. for(;;) {
  581. try {
  582. if (RR->dp->process() < 0)
  583. break;
  584. } catch ( ... ) {} // sanity check -- should not throw
  585. }
  586. --RR->dpEnabled;
  587. }
  588. /****************************************************************************/
  589. /* Node methods used only within node/ */
  590. /****************************************************************************/
  591. std::string Node::dataStoreGet(const char *name)
  592. {
  593. char buf[1024];
  594. std::string r;
  595. unsigned long olen = 0;
  596. do {
  597. long n = _dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  598. if (n <= 0)
  599. return std::string();
  600. r.append(buf,n);
  601. } while (r.length() < olen);
  602. return r;
  603. }
  604. bool Node::shouldUsePathForZeroTierTraffic(const InetAddress &localAddress,const InetAddress &remoteAddress)
  605. {
  606. if (!Path::isAddressValidForPath(remoteAddress))
  607. return false;
  608. {
  609. Mutex::Lock _l(_networks_m);
  610. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  611. if (i->second->hasConfig()) {
  612. std::vector<InetAddress> sips(i->second->config().staticIps());
  613. for(std::vector<InetAddress>::const_iterator a(sips.begin());a!=sips.end();++a) {
  614. if (a->containsAddress(remoteAddress)) {
  615. return false;
  616. }
  617. }
  618. }
  619. }
  620. }
  621. if (_pathCheckFunction)
  622. return (_pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,reinterpret_cast<const struct sockaddr_storage *>(&localAddress),reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  623. else return true;
  624. }
  625. #ifdef ZT_TRACE
  626. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  627. {
  628. static Mutex traceLock;
  629. va_list ap;
  630. char tmp1[1024],tmp2[1024],tmp3[256];
  631. Mutex::Lock _l(traceLock);
  632. time_t now = (time_t)(_now / 1000ULL);
  633. #ifdef __WINDOWS__
  634. ctime_s(tmp3,sizeof(tmp3),&now);
  635. char *nowstr = tmp3;
  636. #else
  637. char *nowstr = ctime_r(&now,tmp3);
  638. #endif
  639. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  640. if (nowstr[nowstrlen-1] == '\n')
  641. nowstr[--nowstrlen] = (char)0;
  642. if (nowstr[nowstrlen-1] == '\r')
  643. nowstr[--nowstrlen] = (char)0;
  644. va_start(ap,fmt);
  645. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  646. va_end(ap);
  647. tmp2[sizeof(tmp2)-1] = (char)0;
  648. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  649. postEvent(ZT_EVENT_TRACE,tmp1);
  650. }
  651. #endif // ZT_TRACE
  652. uint64_t Node::prng()
  653. {
  654. unsigned int p = (++_prngStreamPtr % (sizeof(_prngStream) / sizeof(uint64_t)));
  655. if (!p)
  656. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  657. return _prngStream[p];
  658. }
  659. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  660. {
  661. std::vector< ZT_CircuitTest * > toNotify;
  662. {
  663. Mutex::Lock _l(_circuitTests_m);
  664. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  665. if ((*i)->testId == report->testId)
  666. toNotify.push_back(*i);
  667. }
  668. }
  669. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  670. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  671. }
  672. } // namespace ZeroTier
  673. /****************************************************************************/
  674. /* CAPI bindings */
  675. /****************************************************************************/
  676. extern "C" {
  677. enum ZT_ResultCode ZT_Node_new(
  678. ZT_Node **node,
  679. void *uptr,
  680. uint64_t now,
  681. ZT_DataStoreGetFunction dataStoreGetFunction,
  682. ZT_DataStorePutFunction dataStorePutFunction,
  683. ZT_WirePacketSendFunction wirePacketSendFunction,
  684. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  685. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  686. ZT_PathCheckFunction pathCheckFunction,
  687. ZT_EventCallback eventCallback)
  688. {
  689. *node = (ZT_Node *)0;
  690. try {
  691. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,pathCheckFunction,eventCallback));
  692. return ZT_RESULT_OK;
  693. } catch (std::bad_alloc &exc) {
  694. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  695. } catch (std::runtime_error &exc) {
  696. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  697. } catch ( ... ) {
  698. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  699. }
  700. }
  701. void ZT_Node_delete(ZT_Node *node)
  702. {
  703. try {
  704. delete (reinterpret_cast<ZeroTier::Node *>(node));
  705. } catch ( ... ) {}
  706. }
  707. enum ZT_ResultCode ZT_Node_processWirePacket(
  708. ZT_Node *node,
  709. uint64_t now,
  710. const struct sockaddr_storage *localAddress,
  711. const struct sockaddr_storage *remoteAddress,
  712. const void *packetData,
  713. unsigned int packetLength,
  714. volatile uint64_t *nextBackgroundTaskDeadline)
  715. {
  716. try {
  717. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  718. } catch (std::bad_alloc &exc) {
  719. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  720. } catch ( ... ) {
  721. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  722. }
  723. }
  724. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  725. ZT_Node *node,
  726. uint64_t now,
  727. uint64_t nwid,
  728. uint64_t sourceMac,
  729. uint64_t destMac,
  730. unsigned int etherType,
  731. unsigned int vlanId,
  732. const void *frameData,
  733. unsigned int frameLength,
  734. volatile uint64_t *nextBackgroundTaskDeadline)
  735. {
  736. try {
  737. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  738. } catch (std::bad_alloc &exc) {
  739. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  740. } catch ( ... ) {
  741. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  742. }
  743. }
  744. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  745. {
  746. try {
  747. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  748. } catch (std::bad_alloc &exc) {
  749. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  750. } catch ( ... ) {
  751. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  752. }
  753. }
  754. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr)
  755. {
  756. try {
  757. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr);
  758. } catch (std::bad_alloc &exc) {
  759. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  760. } catch ( ... ) {
  761. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  762. }
  763. }
  764. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr)
  765. {
  766. try {
  767. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr);
  768. } catch (std::bad_alloc &exc) {
  769. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  770. } catch ( ... ) {
  771. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  772. }
  773. }
  774. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  775. {
  776. try {
  777. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  778. } catch (std::bad_alloc &exc) {
  779. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  780. } catch ( ... ) {
  781. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  782. }
  783. }
  784. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  785. {
  786. try {
  787. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  788. } catch (std::bad_alloc &exc) {
  789. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  790. } catch ( ... ) {
  791. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  792. }
  793. }
  794. uint64_t ZT_Node_address(ZT_Node *node)
  795. {
  796. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  797. }
  798. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  799. {
  800. try {
  801. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  802. } catch ( ... ) {}
  803. }
  804. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  805. {
  806. try {
  807. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  808. } catch ( ... ) {
  809. return (ZT_PeerList *)0;
  810. }
  811. }
  812. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  813. {
  814. try {
  815. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  816. } catch ( ... ) {
  817. return (ZT_VirtualNetworkConfig *)0;
  818. }
  819. }
  820. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  821. {
  822. try {
  823. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  824. } catch ( ... ) {
  825. return (ZT_VirtualNetworkList *)0;
  826. }
  827. }
  828. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  829. {
  830. try {
  831. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  832. } catch ( ... ) {}
  833. }
  834. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  835. {
  836. try {
  837. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  838. } catch ( ... ) {
  839. return 0;
  840. }
  841. }
  842. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  843. {
  844. try {
  845. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  846. } catch ( ... ) {}
  847. }
  848. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  849. {
  850. try {
  851. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  852. } catch ( ... ) {}
  853. }
  854. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  855. {
  856. try {
  857. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(test,reportCallback);
  858. } catch ( ... ) {
  859. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  860. }
  861. }
  862. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  863. {
  864. try {
  865. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  866. } catch ( ... ) {}
  867. }
  868. enum ZT_ResultCode ZT_Node_clusterInit(
  869. ZT_Node *node,
  870. unsigned int myId,
  871. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  872. unsigned int numZeroTierPhysicalEndpoints,
  873. int x,
  874. int y,
  875. int z,
  876. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  877. void *sendFunctionArg,
  878. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  879. void *addressToLocationFunctionArg)
  880. {
  881. try {
  882. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  883. } catch ( ... ) {
  884. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  885. }
  886. }
  887. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  888. {
  889. try {
  890. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  891. } catch ( ... ) {
  892. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  893. }
  894. }
  895. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  896. {
  897. try {
  898. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  899. } catch ( ... ) {}
  900. }
  901. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  902. {
  903. try {
  904. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  905. } catch ( ... ) {}
  906. }
  907. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  908. {
  909. try {
  910. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  911. } catch ( ... ) {}
  912. }
  913. void ZT_Node_backgroundThreadMain(ZT_Node *node)
  914. {
  915. try {
  916. reinterpret_cast<ZeroTier::Node *>(node)->backgroundThreadMain();
  917. } catch ( ... ) {}
  918. }
  919. void ZT_version(int *major,int *minor,int *revision,unsigned long *featureFlags)
  920. {
  921. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  922. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  923. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  924. if (featureFlags) {
  925. *featureFlags = (
  926. ZT_FEATURE_FLAG_THREAD_SAFE
  927. );
  928. }
  929. }
  930. } // extern "C"