Node.cpp 34 KB

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