Node.cpp 35 KB

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