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. {
  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,0);
  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,0);
  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,up->nextOutgoingCounter());
  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->publicIdentity = RR->publicIdentityStr.c_str();
  322. status->secretIdentity = RR->secretIdentityStr.c_str();
  323. status->online = _online ? 1 : 0;
  324. }
  325. ZT_PeerList *Node::peers() const
  326. {
  327. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  328. std::sort(peers.begin(),peers.end());
  329. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  330. if (!buf)
  331. return (ZT_PeerList *)0;
  332. ZT_PeerList *pl = (ZT_PeerList *)buf;
  333. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  334. pl->peerCount = 0;
  335. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  336. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  337. p->address = pi->second->address().toInt();
  338. if (pi->second->remoteVersionKnown()) {
  339. p->versionMajor = pi->second->remoteVersionMajor();
  340. p->versionMinor = pi->second->remoteVersionMinor();
  341. p->versionRev = pi->second->remoteVersionRevision();
  342. } else {
  343. p->versionMajor = -1;
  344. p->versionMinor = -1;
  345. p->versionRev = -1;
  346. }
  347. p->latency = pi->second->latency();
  348. p->role = RR->topology->role(pi->second->identity().address());
  349. std::vector< std::pair< SharedPtr<Path>,bool > > paths(pi->second->paths(_now));
  350. SharedPtr<Path> bestp(pi->second->getBestPath(_now,false));
  351. p->pathCount = 0;
  352. for(std::vector< std::pair< SharedPtr<Path>,bool > >::iterator path(paths.begin());path!=paths.end();++path) {
  353. memcpy(&(p->paths[p->pathCount].address),&(path->first->address()),sizeof(struct sockaddr_storage));
  354. p->paths[p->pathCount].lastSend = path->first->lastOut();
  355. p->paths[p->pathCount].lastReceive = path->first->lastIn();
  356. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust(path->first->address());
  357. p->paths[p->pathCount].linkQuality = (int)path->first->linkQuality();
  358. p->paths[p->pathCount].expired = path->second;
  359. p->paths[p->pathCount].preferred = (path->first == bestp) ? 1 : 0;
  360. ++p->pathCount;
  361. }
  362. }
  363. return pl;
  364. }
  365. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  366. {
  367. Mutex::Lock _l(_networks_m);
  368. SharedPtr<Network> nw = _network(nwid);
  369. if(nw) {
  370. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  371. nw->externalConfig(nc);
  372. return nc;
  373. }
  374. return (ZT_VirtualNetworkConfig *)0;
  375. }
  376. ZT_VirtualNetworkList *Node::networks() const
  377. {
  378. Mutex::Lock _l(_networks_m);
  379. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  380. if (!buf)
  381. return (ZT_VirtualNetworkList *)0;
  382. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  383. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  384. nl->networkCount = 0;
  385. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  386. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  387. return nl;
  388. }
  389. void Node::freeQueryResult(void *qr)
  390. {
  391. if (qr)
  392. ::free(qr);
  393. }
  394. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  395. {
  396. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  397. Mutex::Lock _l(_directPaths_m);
  398. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  399. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  400. return 1;
  401. }
  402. }
  403. return 0;
  404. }
  405. void Node::clearLocalInterfaceAddresses()
  406. {
  407. Mutex::Lock _l(_directPaths_m);
  408. _directPaths.clear();
  409. }
  410. int Node::sendUserMessage(uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  411. {
  412. try {
  413. if (RR->identity.address().toInt() != dest) {
  414. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  415. outp.append(typeId);
  416. outp.append(data,len);
  417. outp.compress();
  418. RR->sw->send(outp,true);
  419. return 1;
  420. }
  421. } catch ( ... ) {}
  422. return 0;
  423. }
  424. void Node::setNetconfMaster(void *networkControllerInstance)
  425. {
  426. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  427. RR->localNetworkController->init(RR->identity,this);
  428. }
  429. ZT_ResultCode Node::circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  430. {
  431. if (test->hopCount > 0) {
  432. try {
  433. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  434. RR->identity.address().appendTo(outp);
  435. outp.append((uint16_t)((test->reportAtEveryHop != 0) ? 0x03 : 0x02));
  436. outp.append((uint64_t)test->timestamp);
  437. outp.append((uint64_t)test->testId);
  438. outp.append((uint16_t)0); // originator credential length, updated later
  439. if (test->credentialNetworkId) {
  440. outp.append((uint8_t)0x01);
  441. outp.append((uint64_t)test->credentialNetworkId);
  442. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23,(uint16_t)9);
  443. }
  444. outp.append((uint16_t)0);
  445. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const char *>(outp.data()) + ZT_PACKET_IDX_PAYLOAD,outp.size() - ZT_PACKET_IDX_PAYLOAD));
  446. outp.append((uint16_t)sig.size());
  447. outp.append(sig.data,(unsigned int)sig.size());
  448. outp.append((uint16_t)0); // originator doesn't need an extra credential, since it's the originator
  449. for(unsigned int h=1;h<test->hopCount;++h) {
  450. outp.append((uint8_t)0);
  451. outp.append((uint8_t)(test->hops[h].breadth & 0xff));
  452. for(unsigned int a=0;a<test->hops[h].breadth;++a)
  453. Address(test->hops[h].addresses[a]).appendTo(outp);
  454. }
  455. for(unsigned int a=0;a<test->hops[0].breadth;++a) {
  456. outp.newInitializationVector();
  457. outp.setDestination(Address(test->hops[0].addresses[a]));
  458. RR->sw->send(outp,true);
  459. }
  460. } catch ( ... ) {
  461. return ZT_RESULT_FATAL_ERROR_INTERNAL; // probably indicates FIFO too big for packet
  462. }
  463. }
  464. {
  465. test->_internalPtr = reinterpret_cast<void *>(reportCallback);
  466. Mutex::Lock _l(_circuitTests_m);
  467. if (std::find(_circuitTests.begin(),_circuitTests.end(),test) == _circuitTests.end())
  468. _circuitTests.push_back(test);
  469. }
  470. return ZT_RESULT_OK;
  471. }
  472. void Node::circuitTestEnd(ZT_CircuitTest *test)
  473. {
  474. Mutex::Lock _l(_circuitTests_m);
  475. for(;;) {
  476. std::vector< ZT_CircuitTest * >::iterator ct(std::find(_circuitTests.begin(),_circuitTests.end(),test));
  477. if (ct == _circuitTests.end())
  478. break;
  479. else _circuitTests.erase(ct);
  480. }
  481. }
  482. ZT_ResultCode Node::clusterInit(
  483. unsigned int myId,
  484. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  485. unsigned int numZeroTierPhysicalEndpoints,
  486. int x,
  487. int y,
  488. int z,
  489. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  490. void *sendFunctionArg,
  491. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  492. void *addressToLocationFunctionArg)
  493. {
  494. #ifdef ZT_ENABLE_CLUSTER
  495. if (RR->cluster)
  496. return ZT_RESULT_ERROR_BAD_PARAMETER;
  497. std::vector<InetAddress> eps;
  498. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  499. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  500. std::sort(eps.begin(),eps.end());
  501. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  502. return ZT_RESULT_OK;
  503. #else
  504. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  505. #endif
  506. }
  507. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  508. {
  509. #ifdef ZT_ENABLE_CLUSTER
  510. if (!RR->cluster)
  511. return ZT_RESULT_ERROR_BAD_PARAMETER;
  512. RR->cluster->addMember((uint16_t)memberId);
  513. return ZT_RESULT_OK;
  514. #else
  515. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  516. #endif
  517. }
  518. void Node::clusterRemoveMember(unsigned int memberId)
  519. {
  520. #ifdef ZT_ENABLE_CLUSTER
  521. if (RR->cluster)
  522. RR->cluster->removeMember((uint16_t)memberId);
  523. #endif
  524. }
  525. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  526. {
  527. #ifdef ZT_ENABLE_CLUSTER
  528. if (RR->cluster)
  529. RR->cluster->handleIncomingStateMessage(msg,len);
  530. #endif
  531. }
  532. void Node::clusterStatus(ZT_ClusterStatus *cs)
  533. {
  534. if (!cs)
  535. return;
  536. #ifdef ZT_ENABLE_CLUSTER
  537. if (RR->cluster)
  538. RR->cluster->status(*cs);
  539. else
  540. #endif
  541. memset(cs,0,sizeof(ZT_ClusterStatus));
  542. }
  543. /****************************************************************************/
  544. /* Node methods used only within node/ */
  545. /****************************************************************************/
  546. std::string Node::dataStoreGet(const char *name)
  547. {
  548. char buf[1024];
  549. std::string r;
  550. unsigned long olen = 0;
  551. do {
  552. long n = _cb.dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  553. if (n <= 0)
  554. return std::string();
  555. r.append(buf,n);
  556. } while (r.length() < olen);
  557. return r;
  558. }
  559. bool Node::shouldUsePathForZeroTierTraffic(const Address &ztaddr,const InetAddress &localAddress,const InetAddress &remoteAddress)
  560. {
  561. if (!Path::isAddressValidForPath(remoteAddress))
  562. return false;
  563. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  564. return false;
  565. {
  566. Mutex::Lock _l(_networks_m);
  567. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  568. if (i->second->hasConfig()) {
  569. for(unsigned int k=0;k<i->second->config().staticIpCount;++k) {
  570. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  571. return false;
  572. }
  573. }
  574. }
  575. }
  576. 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);
  577. }
  578. #ifdef ZT_TRACE
  579. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  580. {
  581. static Mutex traceLock;
  582. va_list ap;
  583. char tmp1[1024],tmp2[1024],tmp3[256];
  584. Mutex::Lock _l(traceLock);
  585. time_t now = (time_t)(_now / 1000ULL);
  586. #ifdef __WINDOWS__
  587. ctime_s(tmp3,sizeof(tmp3),&now);
  588. char *nowstr = tmp3;
  589. #else
  590. char *nowstr = ctime_r(&now,tmp3);
  591. #endif
  592. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  593. if (nowstr[nowstrlen-1] == '\n')
  594. nowstr[--nowstrlen] = (char)0;
  595. if (nowstr[nowstrlen-1] == '\r')
  596. nowstr[--nowstrlen] = (char)0;
  597. va_start(ap,fmt);
  598. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  599. va_end(ap);
  600. tmp2[sizeof(tmp2)-1] = (char)0;
  601. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  602. postEvent(ZT_EVENT_TRACE,tmp1);
  603. }
  604. #endif // ZT_TRACE
  605. uint64_t Node::prng()
  606. {
  607. unsigned int p = (++_prngStreamPtr % ZT_NODE_PRNG_BUF_SIZE);
  608. if (!p)
  609. _prng.crypt12(_prngStream,_prngStream,sizeof(_prngStream));
  610. return _prngStream[p];
  611. }
  612. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  613. {
  614. std::vector< ZT_CircuitTest * > toNotify;
  615. {
  616. Mutex::Lock _l(_circuitTests_m);
  617. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  618. if ((*i)->testId == report->testId)
  619. toNotify.push_back(*i);
  620. }
  621. }
  622. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  623. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  624. }
  625. void Node::setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  626. {
  627. RR->topology->setTrustedPaths(reinterpret_cast<const InetAddress *>(networks),ids,count);
  628. }
  629. World Node::planet() const
  630. {
  631. return RR->topology->planet();
  632. }
  633. std::vector<World> Node::moons() const
  634. {
  635. return RR->topology->moons();
  636. }
  637. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  638. {
  639. if (destination == RR->identity.address()) {
  640. SharedPtr<Network> n(network(nwid));
  641. if (!n) return;
  642. n->setConfiguration(nc,true);
  643. } else {
  644. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  645. try {
  646. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  647. uint64_t configUpdateId = prng();
  648. if (!configUpdateId) ++configUpdateId;
  649. const unsigned int totalSize = dconf->sizeBytes();
  650. unsigned int chunkIndex = 0;
  651. while (chunkIndex < totalSize) {
  652. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - (ZT_PACKET_IDX_PAYLOAD + 256)));
  653. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  654. if (requestPacketId) {
  655. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  656. outp.append(requestPacketId);
  657. }
  658. const unsigned int sigStart = outp.size();
  659. outp.append(nwid);
  660. outp.append((uint16_t)chunkLen);
  661. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  662. outp.append((uint8_t)0); // no flags
  663. outp.append((uint64_t)configUpdateId);
  664. outp.append((uint32_t)totalSize);
  665. outp.append((uint32_t)chunkIndex);
  666. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  667. outp.append((uint8_t)1);
  668. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  669. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  670. outp.compress();
  671. RR->sw->send(outp,true);
  672. chunkIndex += chunkLen;
  673. }
  674. }
  675. delete dconf;
  676. } catch ( ... ) {
  677. delete dconf;
  678. throw;
  679. }
  680. }
  681. }
  682. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  683. {
  684. if (destination == RR->identity.address()) {
  685. SharedPtr<Network> n(network(nwid));
  686. if (!n) return;
  687. switch(errorCode) {
  688. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  689. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  690. n->setNotFound();
  691. break;
  692. case NetworkController::NC_ERROR_ACCESS_DENIED:
  693. n->setAccessDenied();
  694. break;
  695. default: break;
  696. }
  697. } else if (requestPacketId) {
  698. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  699. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  700. outp.append(requestPacketId);
  701. switch(errorCode) {
  702. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  703. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  704. default:
  705. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  706. break;
  707. case NetworkController::NC_ERROR_ACCESS_DENIED:
  708. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  709. break;
  710. }
  711. outp.append(nwid);
  712. RR->sw->send(outp,true);
  713. } // else we can't send an ERROR() in response to nothing, so discard
  714. }
  715. } // namespace ZeroTier
  716. /****************************************************************************/
  717. /* CAPI bindings */
  718. /****************************************************************************/
  719. extern "C" {
  720. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now)
  721. {
  722. *node = (ZT_Node *)0;
  723. try {
  724. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,callbacks,now));
  725. return ZT_RESULT_OK;
  726. } catch (std::bad_alloc &exc) {
  727. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  728. } catch (std::runtime_error &exc) {
  729. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  730. } catch ( ... ) {
  731. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  732. }
  733. }
  734. void ZT_Node_delete(ZT_Node *node)
  735. {
  736. try {
  737. delete (reinterpret_cast<ZeroTier::Node *>(node));
  738. } catch ( ... ) {}
  739. }
  740. enum ZT_ResultCode ZT_Node_processWirePacket(
  741. ZT_Node *node,
  742. uint64_t now,
  743. const struct sockaddr_storage *localAddress,
  744. const struct sockaddr_storage *remoteAddress,
  745. const void *packetData,
  746. unsigned int packetLength,
  747. volatile uint64_t *nextBackgroundTaskDeadline)
  748. {
  749. try {
  750. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  751. } catch (std::bad_alloc &exc) {
  752. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  753. } catch ( ... ) {
  754. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  755. }
  756. }
  757. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  758. ZT_Node *node,
  759. uint64_t now,
  760. uint64_t nwid,
  761. uint64_t sourceMac,
  762. uint64_t destMac,
  763. unsigned int etherType,
  764. unsigned int vlanId,
  765. const void *frameData,
  766. unsigned int frameLength,
  767. volatile uint64_t *nextBackgroundTaskDeadline)
  768. {
  769. try {
  770. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  771. } catch (std::bad_alloc &exc) {
  772. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  773. } catch ( ... ) {
  774. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  775. }
  776. }
  777. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  778. {
  779. try {
  780. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  781. } catch (std::bad_alloc &exc) {
  782. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  783. } catch ( ... ) {
  784. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  785. }
  786. }
  787. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr)
  788. {
  789. try {
  790. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr);
  791. } catch (std::bad_alloc &exc) {
  792. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  793. } catch ( ... ) {
  794. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  795. }
  796. }
  797. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr)
  798. {
  799. try {
  800. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr);
  801. } catch (std::bad_alloc &exc) {
  802. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  803. } catch ( ... ) {
  804. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  805. }
  806. }
  807. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  808. {
  809. try {
  810. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  811. } catch (std::bad_alloc &exc) {
  812. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  813. } catch ( ... ) {
  814. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  815. }
  816. }
  817. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  818. {
  819. try {
  820. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  821. } catch (std::bad_alloc &exc) {
  822. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  823. } catch ( ... ) {
  824. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  825. }
  826. }
  827. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,uint64_t moonWorldId,uint64_t moonSeed)
  828. {
  829. try {
  830. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(moonWorldId,moonSeed);
  831. } catch ( ... ) {
  832. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  833. }
  834. }
  835. ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,uint64_t moonWorldId)
  836. {
  837. try {
  838. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(moonWorldId);
  839. } catch ( ... ) {
  840. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  841. }
  842. }
  843. uint64_t ZT_Node_address(ZT_Node *node)
  844. {
  845. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  846. }
  847. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  848. {
  849. try {
  850. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  851. } catch ( ... ) {}
  852. }
  853. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  854. {
  855. try {
  856. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  857. } catch ( ... ) {
  858. return (ZT_PeerList *)0;
  859. }
  860. }
  861. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  862. {
  863. try {
  864. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  865. } catch ( ... ) {
  866. return (ZT_VirtualNetworkConfig *)0;
  867. }
  868. }
  869. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  870. {
  871. try {
  872. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  873. } catch ( ... ) {
  874. return (ZT_VirtualNetworkList *)0;
  875. }
  876. }
  877. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  878. {
  879. try {
  880. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  881. } catch ( ... ) {}
  882. }
  883. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  884. {
  885. try {
  886. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  887. } catch ( ... ) {
  888. return 0;
  889. }
  890. }
  891. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  892. {
  893. try {
  894. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  895. } catch ( ... ) {}
  896. }
  897. int ZT_Node_sendUserMessage(ZT_Node *node,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  898. {
  899. try {
  900. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(dest,typeId,data,len);
  901. } catch ( ... ) {
  902. return 0;
  903. }
  904. }
  905. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  906. {
  907. try {
  908. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  909. } catch ( ... ) {}
  910. }
  911. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  912. {
  913. try {
  914. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(test,reportCallback);
  915. } catch ( ... ) {
  916. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  917. }
  918. }
  919. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  920. {
  921. try {
  922. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  923. } catch ( ... ) {}
  924. }
  925. enum ZT_ResultCode ZT_Node_clusterInit(
  926. ZT_Node *node,
  927. unsigned int myId,
  928. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  929. unsigned int numZeroTierPhysicalEndpoints,
  930. int x,
  931. int y,
  932. int z,
  933. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  934. void *sendFunctionArg,
  935. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  936. void *addressToLocationFunctionArg)
  937. {
  938. try {
  939. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  940. } catch ( ... ) {
  941. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  942. }
  943. }
  944. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  945. {
  946. try {
  947. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  948. } catch ( ... ) {
  949. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  950. }
  951. }
  952. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  953. {
  954. try {
  955. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  956. } catch ( ... ) {}
  957. }
  958. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  959. {
  960. try {
  961. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  962. } catch ( ... ) {}
  963. }
  964. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  965. {
  966. try {
  967. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  968. } catch ( ... ) {}
  969. }
  970. void ZT_Node_setTrustedPaths(ZT_Node *node,const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  971. {
  972. try {
  973. reinterpret_cast<ZeroTier::Node *>(node)->setTrustedPaths(networks,ids,count);
  974. } catch ( ... ) {}
  975. }
  976. void ZT_version(int *major,int *minor,int *revision)
  977. {
  978. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  979. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  980. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  981. }
  982. } // extern "C"