Node.cpp 34 KB

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