1
0

Node.cpp 34 KB

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