Node.cpp 34 KB

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