Node.cpp 36 KB

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