Node.cpp 36 KB

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