Node.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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. _now(now),
  47. _lastPingCheck(0),
  48. _lastHousekeepingRun(0)
  49. {
  50. if (callbacks->version != 0)
  51. throw std::runtime_error("callbacks struct version mismatch");
  52. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  53. Utils::getSecureRandom((void *)_prngState,sizeof(_prngState));
  54. _online = false;
  55. memset(_expectingRepliesToBucketPtr,0,sizeof(_expectingRepliesToBucketPtr));
  56. memset(_expectingRepliesTo,0,sizeof(_expectingRepliesTo));
  57. memset(_lastIdentityVerification,0,sizeof(_lastIdentityVerification));
  58. std::string idtmp(dataStoreGet(tptr,"identity.secret"));
  59. if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
  60. TRACE("identity.secret not found, generating...");
  61. RR->identity.generate();
  62. idtmp = RR->identity.toString(true);
  63. if (!dataStorePut(tptr,"identity.secret",idtmp,true))
  64. throw std::runtime_error("unable to write identity.secret");
  65. }
  66. RR->publicIdentityStr = RR->identity.toString(false);
  67. RR->secretIdentityStr = RR->identity.toString(true);
  68. idtmp = dataStoreGet(tptr,"identity.public");
  69. if (idtmp != RR->publicIdentityStr) {
  70. if (!dataStorePut(tptr,"identity.public",RR->publicIdentityStr,false))
  71. throw std::runtime_error("unable to write identity.public");
  72. }
  73. try {
  74. RR->sw = new Switch(RR);
  75. RR->mc = new Multicaster(RR);
  76. RR->topology = new Topology(RR,tptr);
  77. RR->sa = new SelfAwareness(RR);
  78. } catch ( ... ) {
  79. delete RR->sa;
  80. delete RR->topology;
  81. delete RR->mc;
  82. delete RR->sw;
  83. throw;
  84. }
  85. postEvent(tptr,ZT_EVENT_UP);
  86. }
  87. Node::~Node()
  88. {
  89. Mutex::Lock _l(_networks_m);
  90. _networks.clear(); // ensure that networks are destroyed before shutdow
  91. delete RR->sa;
  92. delete RR->topology;
  93. delete RR->mc;
  94. delete RR->sw;
  95. #ifdef ZT_ENABLE_CLUSTER
  96. delete RR->cluster;
  97. #endif
  98. }
  99. ZT_ResultCode Node::processWirePacket(
  100. void *tptr,
  101. uint64_t now,
  102. const struct sockaddr_storage *localAddress,
  103. const struct sockaddr_storage *remoteAddress,
  104. const void *packetData,
  105. unsigned int packetLength,
  106. volatile uint64_t *nextBackgroundTaskDeadline)
  107. {
  108. _now = now;
  109. RR->sw->onRemotePacket(tptr,*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  110. return ZT_RESULT_OK;
  111. }
  112. ZT_ResultCode Node::processVirtualNetworkFrame(
  113. void *tptr,
  114. uint64_t now,
  115. uint64_t nwid,
  116. uint64_t sourceMac,
  117. uint64_t destMac,
  118. unsigned int etherType,
  119. unsigned int vlanId,
  120. const void *frameData,
  121. unsigned int frameLength,
  122. volatile uint64_t *nextBackgroundTaskDeadline)
  123. {
  124. _now = now;
  125. SharedPtr<Network> nw(this->network(nwid));
  126. if (nw) {
  127. RR->sw->onLocalEthernet(tptr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  128. return ZT_RESULT_OK;
  129. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  130. }
  131. // Closure used to ping upstream and active/online peers
  132. class _PingPeersThatNeedPing
  133. {
  134. public:
  135. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,void *tPtr,Hashtable< Address,std::vector<InetAddress> > &upstreamsToContact,uint64_t now) :
  136. lastReceiveFromUpstream(0),
  137. RR(renv),
  138. _tPtr(tPtr),
  139. _upstreamsToContact(upstreamsToContact),
  140. _now(now),
  141. _bestCurrentUpstream(RR->topology->getUpstreamPeer())
  142. {
  143. }
  144. uint64_t lastReceiveFromUpstream; // tracks last time we got a packet from an 'upstream' peer like a root or a relay
  145. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  146. {
  147. const std::vector<InetAddress> *const upstreamStableEndpoints = _upstreamsToContact.get(p->address());
  148. if (upstreamStableEndpoints) {
  149. bool contacted = false;
  150. // Upstreams must be pinged constantly over both IPv4 and IPv6 to allow
  151. // them to perform three way handshake introductions for both stacks.
  152. if (!p->doPingAndKeepalive(_tPtr,_now,AF_INET)) {
  153. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  154. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  155. if (addr.ss_family == AF_INET) {
  156. p->sendHELLO(_tPtr,InetAddress(),addr,_now,0);
  157. contacted = true;
  158. break;
  159. }
  160. }
  161. } else contacted = true;
  162. if (!p->doPingAndKeepalive(_tPtr,_now,AF_INET6)) {
  163. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  164. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  165. if (addr.ss_family == AF_INET6) {
  166. p->sendHELLO(_tPtr,InetAddress(),addr,_now,0);
  167. contacted = true;
  168. break;
  169. }
  170. }
  171. } else contacted = true;
  172. if ((!contacted)&&(_bestCurrentUpstream)) {
  173. const SharedPtr<Path> up(_bestCurrentUpstream->getBestPath(_now,true));
  174. if (up)
  175. p->sendHELLO(_tPtr,up->localAddress(),up->address(),_now,up->nextOutgoingCounter());
  176. }
  177. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  178. _upstreamsToContact.erase(p->address()); // erase from upstreams to contact so that we can WHOIS those that remain
  179. } else if (p->isActive(_now)) {
  180. p->doPingAndKeepalive(_tPtr,_now,-1);
  181. }
  182. }
  183. private:
  184. const RuntimeEnvironment *RR;
  185. void *_tPtr;
  186. Hashtable< Address,std::vector<InetAddress> > &_upstreamsToContact;
  187. const uint64_t _now;
  188. const SharedPtr<Peer> _bestCurrentUpstream;
  189. };
  190. ZT_ResultCode Node::processBackgroundTasks(void *tptr,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  191. {
  192. _now = now;
  193. Mutex::Lock bl(_backgroundTasksLock);
  194. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  195. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  196. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  197. try {
  198. _lastPingCheck = now;
  199. // Get networks that need config without leaving mutex locked
  200. std::vector< SharedPtr<Network> > needConfig;
  201. {
  202. Mutex::Lock _l(_networks_m);
  203. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  204. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!n->second->hasConfig()))
  205. needConfig.push_back(n->second);
  206. n->second->sendUpdatesToMembers(tptr);
  207. }
  208. }
  209. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  210. (*n)->requestConfiguration(tptr);
  211. // Do pings and keepalives
  212. Hashtable< Address,std::vector<InetAddress> > upstreamsToContact;
  213. RR->topology->getUpstreamsToContact(upstreamsToContact);
  214. _PingPeersThatNeedPing pfunc(RR,tptr,upstreamsToContact,now);
  215. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  216. // Run WHOIS to create Peer for any upstreams we could not contact (including pending moon seeds)
  217. Hashtable< Address,std::vector<InetAddress> >::Iterator i(upstreamsToContact);
  218. Address *upstreamAddress = (Address *)0;
  219. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  220. while (i.next(upstreamAddress,upstreamStableEndpoints))
  221. RR->sw->requestWhois(tptr,*upstreamAddress);
  222. // Update online status, post status change as event
  223. const bool oldOnline = _online;
  224. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  225. if (oldOnline != _online)
  226. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  227. } catch ( ... ) {
  228. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  229. }
  230. } else {
  231. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  232. }
  233. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  234. try {
  235. _lastHousekeepingRun = now;
  236. RR->topology->clean(now);
  237. RR->sa->clean(now);
  238. RR->mc->clean(now);
  239. } catch ( ... ) {
  240. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  241. }
  242. }
  243. try {
  244. #ifdef ZT_ENABLE_CLUSTER
  245. // If clustering is enabled we have to call cluster->doPeriodicTasks() very often, so we override normal timer deadline behavior
  246. if (RR->cluster) {
  247. RR->sw->doTimerTasks(tptr,now);
  248. RR->cluster->doPeriodicTasks();
  249. *nextBackgroundTaskDeadline = now + ZT_CLUSTER_PERIODIC_TASK_PERIOD; // this is really short so just tick at this rate
  250. } else {
  251. #endif
  252. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  253. #ifdef ZT_ENABLE_CLUSTER
  254. }
  255. #endif
  256. } catch ( ... ) {
  257. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  258. }
  259. return ZT_RESULT_OK;
  260. }
  261. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  262. {
  263. Mutex::Lock _l(_networks_m);
  264. SharedPtr<Network> nw = _network(nwid);
  265. if(!nw) {
  266. const std::pair< uint64_t,SharedPtr<Network> > nn(nwid,SharedPtr<Network>(new Network(RR,tptr,nwid,uptr)));
  267. _networks.insert(std::upper_bound(_networks.begin(),_networks.end(),nn),nn);
  268. }
  269. return ZT_RESULT_OK;
  270. }
  271. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  272. {
  273. ZT_VirtualNetworkConfig ctmp;
  274. std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
  275. void **nUserPtr = (void **)0;
  276. Mutex::Lock _l(_networks_m);
  277. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  278. if (n->first != nwid) {
  279. newn.push_back(*n);
  280. } else {
  281. if (uptr)
  282. *uptr = *n->second->userPtr();
  283. n->second->destroy();
  284. nUserPtr = n->second->userPtr();
  285. }
  286. }
  287. _networks.swap(newn);
  288. if (nUserPtr)
  289. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  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< SharedPtr<Path> > paths(pi->second->paths(_now));
  354. SharedPtr<Path> bestp(pi->second->getBestPath(_now,false));
  355. p->pathCount = 0;
  356. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  357. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  358. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  359. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  360. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  361. p->paths[p->pathCount].linkQuality = (int)(*path)->linkQuality();
  362. p->paths[p->pathCount].expired = 0;
  363. p->paths[p->pathCount].preferred = ((*path) == 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. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  612. uint64_t x = _prngState[0];
  613. const uint64_t y = _prngState[1];
  614. _prngState[0] = y;
  615. x ^= x << 23;
  616. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  617. _prngState[1] = z;
  618. return z + y;
  619. }
  620. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  621. {
  622. std::vector< ZT_CircuitTest * > toNotify;
  623. {
  624. Mutex::Lock _l(_circuitTests_m);
  625. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  626. if ((*i)->testId == report->testId)
  627. toNotify.push_back(*i);
  628. }
  629. }
  630. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  631. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  632. }
  633. void Node::setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  634. {
  635. RR->topology->setTrustedPaths(reinterpret_cast<const InetAddress *>(networks),ids,count);
  636. }
  637. World Node::planet() const
  638. {
  639. return RR->topology->planet();
  640. }
  641. std::vector<World> Node::moons() const
  642. {
  643. return RR->topology->moons();
  644. }
  645. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  646. {
  647. if (destination == RR->identity.address()) {
  648. SharedPtr<Network> n(network(nwid));
  649. if (!n) return;
  650. n->setConfiguration((void *)0,nc,true);
  651. } else {
  652. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  653. try {
  654. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  655. uint64_t configUpdateId = prng();
  656. if (!configUpdateId) ++configUpdateId;
  657. const unsigned int totalSize = dconf->sizeBytes();
  658. unsigned int chunkIndex = 0;
  659. while (chunkIndex < totalSize) {
  660. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - (ZT_PACKET_IDX_PAYLOAD + 256)));
  661. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  662. if (requestPacketId) {
  663. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  664. outp.append(requestPacketId);
  665. }
  666. const unsigned int sigStart = outp.size();
  667. outp.append(nwid);
  668. outp.append((uint16_t)chunkLen);
  669. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  670. outp.append((uint8_t)0); // no flags
  671. outp.append((uint64_t)configUpdateId);
  672. outp.append((uint32_t)totalSize);
  673. outp.append((uint32_t)chunkIndex);
  674. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  675. outp.append((uint8_t)1);
  676. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  677. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  678. outp.compress();
  679. RR->sw->send((void *)0,outp,true);
  680. chunkIndex += chunkLen;
  681. }
  682. }
  683. delete dconf;
  684. } catch ( ... ) {
  685. delete dconf;
  686. throw;
  687. }
  688. }
  689. }
  690. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  691. {
  692. if (destination == RR->identity.address()) {
  693. SharedPtr<Network> n(network(rev.networkId()));
  694. if (!n) return;
  695. n->addCredential((void *)0,RR->identity.address(),rev);
  696. } else {
  697. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  698. outp.append((uint8_t)0x00);
  699. outp.append((uint16_t)0);
  700. outp.append((uint16_t)0);
  701. outp.append((uint16_t)1);
  702. rev.serialize(outp);
  703. outp.append((uint16_t)0);
  704. RR->sw->send((void *)0,outp,true);
  705. }
  706. }
  707. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  708. {
  709. if (destination == RR->identity.address()) {
  710. SharedPtr<Network> n(network(nwid));
  711. if (!n) return;
  712. switch(errorCode) {
  713. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  714. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  715. n->setNotFound();
  716. break;
  717. case NetworkController::NC_ERROR_ACCESS_DENIED:
  718. n->setAccessDenied();
  719. break;
  720. default: break;
  721. }
  722. } else if (requestPacketId) {
  723. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  724. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  725. outp.append(requestPacketId);
  726. switch(errorCode) {
  727. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  728. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  729. default:
  730. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  731. break;
  732. case NetworkController::NC_ERROR_ACCESS_DENIED:
  733. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  734. break;
  735. }
  736. outp.append(nwid);
  737. RR->sw->send((void *)0,outp,true);
  738. } // else we can't send an ERROR() in response to nothing, so discard
  739. }
  740. } // namespace ZeroTier
  741. /****************************************************************************/
  742. /* CAPI bindings */
  743. /****************************************************************************/
  744. extern "C" {
  745. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now)
  746. {
  747. *node = (ZT_Node *)0;
  748. try {
  749. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  750. return ZT_RESULT_OK;
  751. } catch (std::bad_alloc &exc) {
  752. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  753. } catch (std::runtime_error &exc) {
  754. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  755. } catch ( ... ) {
  756. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  757. }
  758. }
  759. void ZT_Node_delete(ZT_Node *node)
  760. {
  761. try {
  762. delete (reinterpret_cast<ZeroTier::Node *>(node));
  763. } catch ( ... ) {}
  764. }
  765. enum ZT_ResultCode ZT_Node_processWirePacket(
  766. ZT_Node *node,
  767. void *tptr,
  768. uint64_t now,
  769. const struct sockaddr_storage *localAddress,
  770. const struct sockaddr_storage *remoteAddress,
  771. const void *packetData,
  772. unsigned int packetLength,
  773. volatile uint64_t *nextBackgroundTaskDeadline)
  774. {
  775. try {
  776. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  777. } catch (std::bad_alloc &exc) {
  778. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  779. } catch ( ... ) {
  780. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  781. }
  782. }
  783. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  784. ZT_Node *node,
  785. void *tptr,
  786. uint64_t now,
  787. uint64_t nwid,
  788. uint64_t sourceMac,
  789. uint64_t destMac,
  790. unsigned int etherType,
  791. unsigned int vlanId,
  792. const void *frameData,
  793. unsigned int frameLength,
  794. volatile uint64_t *nextBackgroundTaskDeadline)
  795. {
  796. try {
  797. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  798. } catch (std::bad_alloc &exc) {
  799. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  800. } catch ( ... ) {
  801. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  802. }
  803. }
  804. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  805. {
  806. try {
  807. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  808. } catch (std::bad_alloc &exc) {
  809. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  810. } catch ( ... ) {
  811. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  812. }
  813. }
  814. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  815. {
  816. try {
  817. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  818. } catch (std::bad_alloc &exc) {
  819. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  820. } catch ( ... ) {
  821. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  822. }
  823. }
  824. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  825. {
  826. try {
  827. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  828. } catch (std::bad_alloc &exc) {
  829. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  830. } catch ( ... ) {
  831. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  832. }
  833. }
  834. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  835. {
  836. try {
  837. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  838. } catch (std::bad_alloc &exc) {
  839. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  840. } catch ( ... ) {
  841. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  842. }
  843. }
  844. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  845. {
  846. try {
  847. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  848. } catch (std::bad_alloc &exc) {
  849. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  850. } catch ( ... ) {
  851. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  852. }
  853. }
  854. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  855. {
  856. try {
  857. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  858. } catch ( ... ) {
  859. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  860. }
  861. }
  862. ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  863. {
  864. try {
  865. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  866. } catch ( ... ) {
  867. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  868. }
  869. }
  870. uint64_t ZT_Node_address(ZT_Node *node)
  871. {
  872. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  873. }
  874. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  875. {
  876. try {
  877. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  878. } catch ( ... ) {}
  879. }
  880. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  881. {
  882. try {
  883. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  884. } catch ( ... ) {
  885. return (ZT_PeerList *)0;
  886. }
  887. }
  888. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  889. {
  890. try {
  891. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  892. } catch ( ... ) {
  893. return (ZT_VirtualNetworkConfig *)0;
  894. }
  895. }
  896. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  897. {
  898. try {
  899. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  900. } catch ( ... ) {
  901. return (ZT_VirtualNetworkList *)0;
  902. }
  903. }
  904. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  905. {
  906. try {
  907. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  908. } catch ( ... ) {}
  909. }
  910. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  911. {
  912. try {
  913. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  914. } catch ( ... ) {
  915. return 0;
  916. }
  917. }
  918. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  919. {
  920. try {
  921. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  922. } catch ( ... ) {}
  923. }
  924. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  925. {
  926. try {
  927. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  928. } catch ( ... ) {
  929. return 0;
  930. }
  931. }
  932. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  933. {
  934. try {
  935. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  936. } catch ( ... ) {}
  937. }
  938. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,void *tptr,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  939. {
  940. try {
  941. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(tptr,test,reportCallback);
  942. } catch ( ... ) {
  943. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  944. }
  945. }
  946. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  947. {
  948. try {
  949. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  950. } catch ( ... ) {}
  951. }
  952. enum ZT_ResultCode ZT_Node_clusterInit(
  953. ZT_Node *node,
  954. unsigned int myId,
  955. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  956. unsigned int numZeroTierPhysicalEndpoints,
  957. int x,
  958. int y,
  959. int z,
  960. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  961. void *sendFunctionArg,
  962. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  963. void *addressToLocationFunctionArg)
  964. {
  965. try {
  966. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  967. } catch ( ... ) {
  968. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  969. }
  970. }
  971. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  972. {
  973. try {
  974. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  975. } catch ( ... ) {
  976. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  977. }
  978. }
  979. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  980. {
  981. try {
  982. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  983. } catch ( ... ) {}
  984. }
  985. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  986. {
  987. try {
  988. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  989. } catch ( ... ) {}
  990. }
  991. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  992. {
  993. try {
  994. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  995. } catch ( ... ) {}
  996. }
  997. void ZT_Node_setTrustedPaths(ZT_Node *node,const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  998. {
  999. try {
  1000. reinterpret_cast<ZeroTier::Node *>(node)->setTrustedPaths(networks,ids,count);
  1001. } catch ( ... ) {}
  1002. }
  1003. void ZT_version(int *major,int *minor,int *revision)
  1004. {
  1005. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  1006. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  1007. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  1008. }
  1009. } // extern "C"