Node.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
  38. namespace ZeroTier {
  39. /****************************************************************************/
  40. /* Public Node interface (C++, exposed via CAPI bindings) */
  41. /****************************************************************************/
  42. Node::Node(void *uptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now) :
  43. _RR(this),
  44. RR(&_RR),
  45. _uPtr(uptr),
  46. _prngStreamPtr(0),
  47. _now(now),
  48. _lastPingCheck(0),
  49. _lastHousekeepingRun(0)
  50. {
  51. if (callbacks->version != 0)
  52. throw std::runtime_error("callbacks struct version mismatch");
  53. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  54. _online = false;
  55. memset(_expectingRepliesToBucketPtr,0,sizeof(_expectingRepliesToBucketPtr));
  56. memset(_expectingRepliesTo,0,sizeof(_expectingRepliesTo));
  57. memset(_lastIdentityVerification,0,sizeof(_lastIdentityVerification));
  58. // Use Salsa20 alone as a high-quality non-crypto PRNG
  59. char foo[32];
  60. Utils::getSecureRandom(foo,32);
  61. _prng.init(foo,256,foo);
  62. memset(_prngStream,0,sizeof(_prngStream));
  63. _prng.crypt12(_prngStream,_prngStream,sizeof(_prngStream));
  64. std::string idtmp(dataStoreGet("identity.secret"));
  65. if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
  66. TRACE("identity.secret not found, generating...");
  67. RR->identity.generate();
  68. idtmp = RR->identity.toString(true);
  69. if (!dataStorePut("identity.secret",idtmp,true))
  70. throw std::runtime_error("unable to write identity.secret");
  71. }
  72. RR->publicIdentityStr = RR->identity.toString(false);
  73. RR->secretIdentityStr = RR->identity.toString(true);
  74. idtmp = dataStoreGet("identity.public");
  75. if (idtmp != RR->publicIdentityStr) {
  76. if (!dataStorePut("identity.public",RR->publicIdentityStr,false))
  77. throw std::runtime_error("unable to write identity.public");
  78. }
  79. try {
  80. RR->sw = new Switch(RR);
  81. RR->mc = new Multicaster(RR);
  82. RR->topology = new Topology(RR);
  83. RR->sa = new SelfAwareness(RR);
  84. } catch ( ... ) {
  85. delete RR->sa;
  86. delete RR->topology;
  87. delete RR->mc;
  88. delete RR->sw;
  89. throw;
  90. }
  91. postEvent(ZT_EVENT_UP);
  92. }
  93. Node::~Node()
  94. {
  95. Mutex::Lock _l(_networks_m);
  96. _networks.clear(); // ensure that networks are destroyed before shutdow
  97. delete RR->sa;
  98. delete RR->topology;
  99. delete RR->mc;
  100. delete RR->sw;
  101. #ifdef ZT_ENABLE_CLUSTER
  102. delete RR->cluster;
  103. #endif
  104. }
  105. ZT_ResultCode Node::processWirePacket(
  106. uint64_t now,
  107. const struct sockaddr_storage *localAddress,
  108. const struct sockaddr_storage *remoteAddress,
  109. const void *packetData,
  110. unsigned int packetLength,
  111. volatile uint64_t *nextBackgroundTaskDeadline)
  112. {
  113. _now = now;
  114. RR->sw->onRemotePacket(*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  115. return ZT_RESULT_OK;
  116. }
  117. ZT_ResultCode Node::processVirtualNetworkFrame(
  118. uint64_t now,
  119. uint64_t nwid,
  120. uint64_t sourceMac,
  121. uint64_t destMac,
  122. unsigned int etherType,
  123. unsigned int vlanId,
  124. const void *frameData,
  125. unsigned int frameLength,
  126. volatile uint64_t *nextBackgroundTaskDeadline)
  127. {
  128. _now = now;
  129. SharedPtr<Network> nw(this->network(nwid));
  130. if (nw) {
  131. RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  132. return ZT_RESULT_OK;
  133. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  134. }
  135. // Closure used to ping upstream and active/online peers
  136. class _PingPeersThatNeedPing
  137. {
  138. public:
  139. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,Hashtable< Address,std::vector<InetAddress> > &upstreamsToContact,uint64_t now) :
  140. lastReceiveFromUpstream(0),
  141. RR(renv),
  142. _upstreamsToContact(upstreamsToContact),
  143. _now(now),
  144. _bestCurrentUpstream(RR->topology->getUpstreamPeer())
  145. {
  146. }
  147. uint64_t lastReceiveFromUpstream; // tracks last time we got a packet from an 'upstream' peer like a root or a relay
  148. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  149. {
  150. const std::vector<InetAddress> *const upstreamStableEndpoints = _upstreamsToContact.get(p->address());
  151. if (upstreamStableEndpoints) {
  152. bool contacted = false;
  153. // Upstreams must be pinged constantly over both IPv4 and IPv6 to allow
  154. // them to perform three way handshake introductions for both stacks.
  155. if (!p->doPingAndKeepalive(_now,AF_INET)) {
  156. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  157. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  158. if (addr.ss_family == AF_INET) {
  159. p->sendHELLO(InetAddress(),addr,_now);
  160. contacted = true;
  161. break;
  162. }
  163. }
  164. } else contacted = true;
  165. if (!p->doPingAndKeepalive(_now,AF_INET6)) {
  166. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  167. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  168. if (addr.ss_family == AF_INET6) {
  169. p->sendHELLO(InetAddress(),addr,_now);
  170. contacted = true;
  171. break;
  172. }
  173. }
  174. } else contacted = true;
  175. if ((!contacted)&&(_bestCurrentUpstream)) {
  176. const SharedPtr<Path> up(_bestCurrentUpstream->getBestPath(_now,true));
  177. if (up)
  178. p->sendHELLO(up->localAddress(),up->address(),_now);
  179. }
  180. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  181. _upstreamsToContact.erase(p->address()); // erase from upstreams to contact so that we can WHOIS those that remain
  182. } else if (p->isActive(_now)) {
  183. p->doPingAndKeepalive(_now,-1);
  184. }
  185. }
  186. private:
  187. const RuntimeEnvironment *RR;
  188. Hashtable< Address,std::vector<InetAddress> > &_upstreamsToContact;
  189. const uint64_t _now;
  190. const SharedPtr<Peer> _bestCurrentUpstream;
  191. };
  192. ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  193. {
  194. _now = now;
  195. Mutex::Lock bl(_backgroundTasksLock);
  196. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  197. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  198. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  199. try {
  200. _lastPingCheck = now;
  201. // Get networks that need config without leaving mutex locked
  202. std::vector< SharedPtr<Network> > needConfig;
  203. {
  204. Mutex::Lock _l(_networks_m);
  205. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  206. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!n->second->hasConfig()))
  207. needConfig.push_back(n->second);
  208. n->second->sendUpdatesToMembers();
  209. }
  210. }
  211. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  212. (*n)->requestConfiguration();
  213. // Do pings and keepalives
  214. Hashtable< Address,std::vector<InetAddress> > upstreamsToContact;
  215. RR->topology->getUpstreamsToContact(upstreamsToContact);
  216. _PingPeersThatNeedPing pfunc(RR,upstreamsToContact,now);
  217. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  218. // Run WHOIS to create Peer for any upstreams we could not contact (including pending moon seeds)
  219. Hashtable< Address,std::vector<InetAddress> >::Iterator i(upstreamsToContact);
  220. Address *upstreamAddress = (Address *)0;
  221. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  222. while (i.next(upstreamAddress,upstreamStableEndpoints))
  223. RR->sw->requestWhois(*upstreamAddress);
  224. // Update online status, post status change as event
  225. const bool oldOnline = _online;
  226. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  227. if (oldOnline != _online)
  228. postEvent(_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  229. } catch ( ... ) {
  230. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  231. }
  232. } else {
  233. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  234. }
  235. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  236. try {
  237. _lastHousekeepingRun = now;
  238. RR->topology->clean(now);
  239. RR->sa->clean(now);
  240. RR->mc->clean(now);
  241. } catch ( ... ) {
  242. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  243. }
  244. }
  245. try {
  246. #ifdef ZT_ENABLE_CLUSTER
  247. // If clustering is enabled we have to call cluster->doPeriodicTasks() very often, so we override normal timer deadline behavior
  248. if (RR->cluster) {
  249. RR->sw->doTimerTasks(now);
  250. RR->cluster->doPeriodicTasks();
  251. *nextBackgroundTaskDeadline = now + ZT_CLUSTER_PERIODIC_TASK_PERIOD; // this is really short so just tick at this rate
  252. } else {
  253. #endif
  254. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  255. #ifdef ZT_ENABLE_CLUSTER
  256. }
  257. #endif
  258. } catch ( ... ) {
  259. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  260. }
  261. return ZT_RESULT_OK;
  262. }
  263. ZT_ResultCode Node::join(uint64_t nwid,void *uptr)
  264. {
  265. Mutex::Lock _l(_networks_m);
  266. SharedPtr<Network> nw = _network(nwid);
  267. if(!nw)
  268. _networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid,uptr))));
  269. std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
  270. return ZT_RESULT_OK;
  271. }
  272. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr)
  273. {
  274. std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
  275. Mutex::Lock _l(_networks_m);
  276. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  277. if (n->first != nwid)
  278. newn.push_back(*n);
  279. else {
  280. if (uptr)
  281. *uptr = n->second->userPtr();
  282. n->second->destroy();
  283. }
  284. }
  285. _networks.swap(newn);
  286. return ZT_RESULT_OK;
  287. }
  288. ZT_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  289. {
  290. SharedPtr<Network> nw(this->network(nwid));
  291. if (nw) {
  292. nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  293. return ZT_RESULT_OK;
  294. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  295. }
  296. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  297. {
  298. SharedPtr<Network> nw(this->network(nwid));
  299. if (nw) {
  300. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  301. return ZT_RESULT_OK;
  302. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  303. }
  304. ZT_ResultCode Node::orbit(uint64_t moonWorldId,uint64_t moonSeed)
  305. {
  306. RR->topology->addMoon(moonWorldId,Address(moonSeed));
  307. return ZT_RESULT_OK;
  308. }
  309. ZT_ResultCode Node::deorbit(uint64_t moonWorldId)
  310. {
  311. RR->topology->removeMoon(moonWorldId);
  312. return ZT_RESULT_OK;
  313. }
  314. uint64_t Node::address() const
  315. {
  316. return RR->identity.address().toInt();
  317. }
  318. void Node::status(ZT_NodeStatus *status) const
  319. {
  320. status->address = RR->identity.address().toInt();
  321. status->publicIdentity = RR->publicIdentityStr.c_str();
  322. status->secretIdentity = RR->secretIdentityStr.c_str();
  323. status->online = _online ? 1 : 0;
  324. }
  325. ZT_PeerList *Node::peers() const
  326. {
  327. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  328. std::sort(peers.begin(),peers.end());
  329. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  330. if (!buf)
  331. return (ZT_PeerList *)0;
  332. ZT_PeerList *pl = (ZT_PeerList *)buf;
  333. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  334. pl->peerCount = 0;
  335. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  336. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  337. p->address = pi->second->address().toInt();
  338. if (pi->second->remoteVersionKnown()) {
  339. p->versionMajor = pi->second->remoteVersionMajor();
  340. p->versionMinor = pi->second->remoteVersionMinor();
  341. p->versionRev = pi->second->remoteVersionRevision();
  342. } else {
  343. p->versionMajor = -1;
  344. p->versionMinor = -1;
  345. p->versionRev = -1;
  346. }
  347. p->latency = pi->second->latency();
  348. p->role = RR->topology->role(pi->second->identity().address());
  349. std::vector< std::pair< SharedPtr<Path>,bool > > paths(pi->second->paths(_now));
  350. SharedPtr<Path> bestp(pi->second->getBestPath(_now,false));
  351. p->pathCount = 0;
  352. for(std::vector< std::pair< SharedPtr<Path>,bool > >::iterator path(paths.begin());path!=paths.end();++path) {
  353. memcpy(&(p->paths[p->pathCount].address),&(path->first->address()),sizeof(struct sockaddr_storage));
  354. p->paths[p->pathCount].lastSend = path->first->lastOut();
  355. p->paths[p->pathCount].lastReceive = path->first->lastIn();
  356. p->paths[p->pathCount].expired = path->second;
  357. p->paths[p->pathCount].preferred = (path->first == bestp) ? 1 : 0;
  358. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust(path->first->address());
  359. ++p->pathCount;
  360. }
  361. }
  362. return pl;
  363. }
  364. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  365. {
  366. Mutex::Lock _l(_networks_m);
  367. SharedPtr<Network> nw = _network(nwid);
  368. if(nw) {
  369. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  370. nw->externalConfig(nc);
  371. return nc;
  372. }
  373. return (ZT_VirtualNetworkConfig *)0;
  374. }
  375. ZT_VirtualNetworkList *Node::networks() const
  376. {
  377. Mutex::Lock _l(_networks_m);
  378. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  379. if (!buf)
  380. return (ZT_VirtualNetworkList *)0;
  381. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  382. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  383. nl->networkCount = 0;
  384. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  385. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  386. return nl;
  387. }
  388. void Node::freeQueryResult(void *qr)
  389. {
  390. if (qr)
  391. ::free(qr);
  392. }
  393. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  394. {
  395. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  396. Mutex::Lock _l(_directPaths_m);
  397. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  398. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  399. return 1;
  400. }
  401. }
  402. return 0;
  403. }
  404. void Node::clearLocalInterfaceAddresses()
  405. {
  406. Mutex::Lock _l(_directPaths_m);
  407. _directPaths.clear();
  408. }
  409. int Node::sendUserMessage(uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  410. {
  411. try {
  412. if (RR->identity.address().toInt() != dest) {
  413. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  414. outp.append(typeId);
  415. outp.append(data,len);
  416. outp.compress();
  417. RR->sw->send(outp,true);
  418. return 1;
  419. }
  420. } catch ( ... ) {}
  421. return 0;
  422. }
  423. void Node::setNetconfMaster(void *networkControllerInstance)
  424. {
  425. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  426. RR->localNetworkController->init(RR->identity,this);
  427. }
  428. ZT_ResultCode Node::circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  429. {
  430. if (test->hopCount > 0) {
  431. try {
  432. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  433. RR->identity.address().appendTo(outp);
  434. outp.append((uint16_t)((test->reportAtEveryHop != 0) ? 0x03 : 0x02));
  435. outp.append((uint64_t)test->timestamp);
  436. outp.append((uint64_t)test->testId);
  437. outp.append((uint16_t)0); // originator credential length, updated later
  438. if (test->credentialNetworkId) {
  439. outp.append((uint8_t)0x01);
  440. outp.append((uint64_t)test->credentialNetworkId);
  441. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23,(uint16_t)9);
  442. }
  443. outp.append((uint16_t)0);
  444. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const char *>(outp.data()) + ZT_PACKET_IDX_PAYLOAD,outp.size() - ZT_PACKET_IDX_PAYLOAD));
  445. outp.append((uint16_t)sig.size());
  446. outp.append(sig.data,(unsigned int)sig.size());
  447. outp.append((uint16_t)0); // originator doesn't need an extra credential, since it's the originator
  448. for(unsigned int h=1;h<test->hopCount;++h) {
  449. outp.append((uint8_t)0);
  450. outp.append((uint8_t)(test->hops[h].breadth & 0xff));
  451. for(unsigned int a=0;a<test->hops[h].breadth;++a)
  452. Address(test->hops[h].addresses[a]).appendTo(outp);
  453. }
  454. for(unsigned int a=0;a<test->hops[0].breadth;++a) {
  455. outp.newInitializationVector();
  456. outp.setDestination(Address(test->hops[0].addresses[a]));
  457. RR->sw->send(outp,true);
  458. }
  459. } catch ( ... ) {
  460. return ZT_RESULT_FATAL_ERROR_INTERNAL; // probably indicates FIFO too big for packet
  461. }
  462. }
  463. {
  464. test->_internalPtr = reinterpret_cast<void *>(reportCallback);
  465. Mutex::Lock _l(_circuitTests_m);
  466. if (std::find(_circuitTests.begin(),_circuitTests.end(),test) == _circuitTests.end())
  467. _circuitTests.push_back(test);
  468. }
  469. return ZT_RESULT_OK;
  470. }
  471. void Node::circuitTestEnd(ZT_CircuitTest *test)
  472. {
  473. Mutex::Lock _l(_circuitTests_m);
  474. for(;;) {
  475. std::vector< ZT_CircuitTest * >::iterator ct(std::find(_circuitTests.begin(),_circuitTests.end(),test));
  476. if (ct == _circuitTests.end())
  477. break;
  478. else _circuitTests.erase(ct);
  479. }
  480. }
  481. ZT_ResultCode Node::clusterInit(
  482. unsigned int myId,
  483. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  484. unsigned int numZeroTierPhysicalEndpoints,
  485. int x,
  486. int y,
  487. int z,
  488. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  489. void *sendFunctionArg,
  490. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  491. void *addressToLocationFunctionArg)
  492. {
  493. #ifdef ZT_ENABLE_CLUSTER
  494. if (RR->cluster)
  495. return ZT_RESULT_ERROR_BAD_PARAMETER;
  496. std::vector<InetAddress> eps;
  497. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  498. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  499. std::sort(eps.begin(),eps.end());
  500. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  501. return ZT_RESULT_OK;
  502. #else
  503. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  504. #endif
  505. }
  506. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  507. {
  508. #ifdef ZT_ENABLE_CLUSTER
  509. if (!RR->cluster)
  510. return ZT_RESULT_ERROR_BAD_PARAMETER;
  511. RR->cluster->addMember((uint16_t)memberId);
  512. return ZT_RESULT_OK;
  513. #else
  514. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  515. #endif
  516. }
  517. void Node::clusterRemoveMember(unsigned int memberId)
  518. {
  519. #ifdef ZT_ENABLE_CLUSTER
  520. if (RR->cluster)
  521. RR->cluster->removeMember((uint16_t)memberId);
  522. #endif
  523. }
  524. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  525. {
  526. #ifdef ZT_ENABLE_CLUSTER
  527. if (RR->cluster)
  528. RR->cluster->handleIncomingStateMessage(msg,len);
  529. #endif
  530. }
  531. void Node::clusterStatus(ZT_ClusterStatus *cs)
  532. {
  533. if (!cs)
  534. return;
  535. #ifdef ZT_ENABLE_CLUSTER
  536. if (RR->cluster)
  537. RR->cluster->status(*cs);
  538. else
  539. #endif
  540. memset(cs,0,sizeof(ZT_ClusterStatus));
  541. }
  542. /****************************************************************************/
  543. /* Node methods used only within node/ */
  544. /****************************************************************************/
  545. std::string Node::dataStoreGet(const char *name)
  546. {
  547. char buf[1024];
  548. std::string r;
  549. unsigned long olen = 0;
  550. do {
  551. long n = _cb.dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  552. if (n <= 0)
  553. return std::string();
  554. r.append(buf,n);
  555. } while (r.length() < olen);
  556. return r;
  557. }
  558. bool Node::shouldUsePathForZeroTierTraffic(const Address &ztaddr,const InetAddress &localAddress,const InetAddress &remoteAddress)
  559. {
  560. if (!Path::isAddressValidForPath(remoteAddress))
  561. return false;
  562. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  563. return false;
  564. {
  565. Mutex::Lock _l(_networks_m);
  566. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  567. if (i->second->hasConfig()) {
  568. for(unsigned int k=0;k<i->second->config().staticIpCount;++k) {
  569. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  570. return false;
  571. }
  572. }
  573. }
  574. }
  575. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,ztaddr.toInt(),reinterpret_cast<const struct sockaddr_storage *>(&localAddress),reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  576. }
  577. #ifdef ZT_TRACE
  578. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  579. {
  580. static Mutex traceLock;
  581. va_list ap;
  582. char tmp1[1024],tmp2[1024],tmp3[256];
  583. Mutex::Lock _l(traceLock);
  584. time_t now = (time_t)(_now / 1000ULL);
  585. #ifdef __WINDOWS__
  586. ctime_s(tmp3,sizeof(tmp3),&now);
  587. char *nowstr = tmp3;
  588. #else
  589. char *nowstr = ctime_r(&now,tmp3);
  590. #endif
  591. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  592. if (nowstr[nowstrlen-1] == '\n')
  593. nowstr[--nowstrlen] = (char)0;
  594. if (nowstr[nowstrlen-1] == '\r')
  595. nowstr[--nowstrlen] = (char)0;
  596. va_start(ap,fmt);
  597. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  598. va_end(ap);
  599. tmp2[sizeof(tmp2)-1] = (char)0;
  600. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  601. postEvent(ZT_EVENT_TRACE,tmp1);
  602. }
  603. #endif // ZT_TRACE
  604. uint64_t Node::prng()
  605. {
  606. unsigned int p = (++_prngStreamPtr % ZT_NODE_PRNG_BUF_SIZE);
  607. if (!p)
  608. _prng.crypt12(_prngStream,_prngStream,sizeof(_prngStream));
  609. return _prngStream[p];
  610. }
  611. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  612. {
  613. std::vector< ZT_CircuitTest * > toNotify;
  614. {
  615. Mutex::Lock _l(_circuitTests_m);
  616. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  617. if ((*i)->testId == report->testId)
  618. toNotify.push_back(*i);
  619. }
  620. }
  621. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  622. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  623. }
  624. void Node::setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  625. {
  626. RR->topology->setTrustedPaths(reinterpret_cast<const InetAddress *>(networks),ids,count);
  627. }
  628. World Node::planet() const
  629. {
  630. return RR->topology->planet();
  631. }
  632. std::vector<World> Node::moons() const
  633. {
  634. return RR->topology->moons();
  635. }
  636. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  637. {
  638. if (destination == RR->identity.address()) {
  639. SharedPtr<Network> n(network(nwid));
  640. if (!n) return;
  641. n->setConfiguration(nc,true);
  642. } else {
  643. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  644. try {
  645. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  646. uint64_t configUpdateId = prng();
  647. if (!configUpdateId) ++configUpdateId;
  648. const unsigned int totalSize = dconf->sizeBytes();
  649. unsigned int chunkIndex = 0;
  650. while (chunkIndex < totalSize) {
  651. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - (ZT_PACKET_IDX_PAYLOAD + 256)));
  652. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  653. if (requestPacketId) {
  654. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  655. outp.append(requestPacketId);
  656. }
  657. const unsigned int sigStart = outp.size();
  658. outp.append(nwid);
  659. outp.append((uint16_t)chunkLen);
  660. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  661. outp.append((uint8_t)0); // no flags
  662. outp.append((uint64_t)configUpdateId);
  663. outp.append((uint32_t)totalSize);
  664. outp.append((uint32_t)chunkIndex);
  665. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  666. outp.append((uint8_t)1);
  667. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  668. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  669. outp.compress();
  670. RR->sw->send(outp,true);
  671. chunkIndex += chunkLen;
  672. }
  673. }
  674. delete dconf;
  675. } catch ( ... ) {
  676. delete dconf;
  677. throw;
  678. }
  679. }
  680. }
  681. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  682. {
  683. if (destination == RR->identity.address()) {
  684. SharedPtr<Network> n(network(nwid));
  685. if (!n) return;
  686. switch(errorCode) {
  687. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  688. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  689. n->setNotFound();
  690. break;
  691. case NetworkController::NC_ERROR_ACCESS_DENIED:
  692. n->setAccessDenied();
  693. break;
  694. default: break;
  695. }
  696. } else if (requestPacketId) {
  697. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  698. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  699. outp.append(requestPacketId);
  700. switch(errorCode) {
  701. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  702. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  703. default:
  704. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  705. break;
  706. case NetworkController::NC_ERROR_ACCESS_DENIED:
  707. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  708. break;
  709. }
  710. outp.append(nwid);
  711. RR->sw->send(outp,true);
  712. } // else we can't send an ERROR() in response to nothing, so discard
  713. }
  714. } // namespace ZeroTier
  715. /****************************************************************************/
  716. /* CAPI bindings */
  717. /****************************************************************************/
  718. extern "C" {
  719. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now)
  720. {
  721. *node = (ZT_Node *)0;
  722. try {
  723. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,callbacks,now));
  724. return ZT_RESULT_OK;
  725. } catch (std::bad_alloc &exc) {
  726. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  727. } catch (std::runtime_error &exc) {
  728. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  729. } catch ( ... ) {
  730. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  731. }
  732. }
  733. void ZT_Node_delete(ZT_Node *node)
  734. {
  735. try {
  736. delete (reinterpret_cast<ZeroTier::Node *>(node));
  737. } catch ( ... ) {}
  738. }
  739. enum ZT_ResultCode ZT_Node_processWirePacket(
  740. ZT_Node *node,
  741. uint64_t now,
  742. const struct sockaddr_storage *localAddress,
  743. const struct sockaddr_storage *remoteAddress,
  744. const void *packetData,
  745. unsigned int packetLength,
  746. volatile uint64_t *nextBackgroundTaskDeadline)
  747. {
  748. try {
  749. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  750. } catch (std::bad_alloc &exc) {
  751. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  752. } catch ( ... ) {
  753. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  754. }
  755. }
  756. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  757. ZT_Node *node,
  758. uint64_t now,
  759. uint64_t nwid,
  760. uint64_t sourceMac,
  761. uint64_t destMac,
  762. unsigned int etherType,
  763. unsigned int vlanId,
  764. const void *frameData,
  765. unsigned int frameLength,
  766. volatile uint64_t *nextBackgroundTaskDeadline)
  767. {
  768. try {
  769. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  770. } catch (std::bad_alloc &exc) {
  771. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  772. } catch ( ... ) {
  773. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  774. }
  775. }
  776. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  777. {
  778. try {
  779. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  780. } catch (std::bad_alloc &exc) {
  781. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  782. } catch ( ... ) {
  783. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  784. }
  785. }
  786. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr)
  787. {
  788. try {
  789. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr);
  790. } catch (std::bad_alloc &exc) {
  791. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  792. } catch ( ... ) {
  793. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  794. }
  795. }
  796. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr)
  797. {
  798. try {
  799. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr);
  800. } catch (std::bad_alloc &exc) {
  801. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  802. } catch ( ... ) {
  803. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  804. }
  805. }
  806. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  807. {
  808. try {
  809. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  810. } catch (std::bad_alloc &exc) {
  811. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  812. } catch ( ... ) {
  813. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  814. }
  815. }
  816. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  817. {
  818. try {
  819. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  820. } catch (std::bad_alloc &exc) {
  821. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  822. } catch ( ... ) {
  823. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  824. }
  825. }
  826. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,uint64_t moonWorldId,uint64_t moonSeed)
  827. {
  828. try {
  829. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(moonWorldId,moonSeed);
  830. } catch ( ... ) {
  831. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  832. }
  833. }
  834. ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,uint64_t moonWorldId)
  835. {
  836. try {
  837. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(moonWorldId);
  838. } catch ( ... ) {
  839. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  840. }
  841. }
  842. uint64_t ZT_Node_address(ZT_Node *node)
  843. {
  844. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  845. }
  846. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  847. {
  848. try {
  849. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  850. } catch ( ... ) {}
  851. }
  852. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  853. {
  854. try {
  855. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  856. } catch ( ... ) {
  857. return (ZT_PeerList *)0;
  858. }
  859. }
  860. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  861. {
  862. try {
  863. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  864. } catch ( ... ) {
  865. return (ZT_VirtualNetworkConfig *)0;
  866. }
  867. }
  868. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  869. {
  870. try {
  871. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  872. } catch ( ... ) {
  873. return (ZT_VirtualNetworkList *)0;
  874. }
  875. }
  876. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  877. {
  878. try {
  879. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  880. } catch ( ... ) {}
  881. }
  882. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  883. {
  884. try {
  885. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  886. } catch ( ... ) {
  887. return 0;
  888. }
  889. }
  890. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  891. {
  892. try {
  893. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  894. } catch ( ... ) {}
  895. }
  896. int ZT_Node_sendUserMessage(ZT_Node *node,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  897. {
  898. try {
  899. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(dest,typeId,data,len);
  900. } catch ( ... ) {
  901. return 0;
  902. }
  903. }
  904. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  905. {
  906. try {
  907. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  908. } catch ( ... ) {}
  909. }
  910. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  911. {
  912. try {
  913. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(test,reportCallback);
  914. } catch ( ... ) {
  915. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  916. }
  917. }
  918. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  919. {
  920. try {
  921. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  922. } catch ( ... ) {}
  923. }
  924. enum ZT_ResultCode ZT_Node_clusterInit(
  925. ZT_Node *node,
  926. unsigned int myId,
  927. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  928. unsigned int numZeroTierPhysicalEndpoints,
  929. int x,
  930. int y,
  931. int z,
  932. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  933. void *sendFunctionArg,
  934. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  935. void *addressToLocationFunctionArg)
  936. {
  937. try {
  938. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  939. } catch ( ... ) {
  940. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  941. }
  942. }
  943. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  944. {
  945. try {
  946. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  947. } catch ( ... ) {
  948. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  949. }
  950. }
  951. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  952. {
  953. try {
  954. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  955. } catch ( ... ) {}
  956. }
  957. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  958. {
  959. try {
  960. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  961. } catch ( ... ) {}
  962. }
  963. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  964. {
  965. try {
  966. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  967. } catch ( ... ) {}
  968. }
  969. void ZT_Node_setTrustedPaths(ZT_Node *node,const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  970. {
  971. try {
  972. reinterpret_cast<ZeroTier::Node *>(node)->setTrustedPaths(networks,ids,count);
  973. } catch ( ... ) {}
  974. }
  975. void ZT_version(int *major,int *minor,int *revision)
  976. {
  977. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  978. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  979. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  980. }
  981. } // extern "C"