Node.cpp 35 KB

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