Node.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <stdint.h>
  18. #include "../version.h"
  19. #include "Constants.hpp"
  20. #include "SharedPtr.hpp"
  21. #include "Node.hpp"
  22. #include "RuntimeEnvironment.hpp"
  23. #include "NetworkController.hpp"
  24. #include "Switch.hpp"
  25. #include "Multicaster.hpp"
  26. #include "Topology.hpp"
  27. #include "Buffer.hpp"
  28. #include "Packet.hpp"
  29. #include "Address.hpp"
  30. #include "Identity.hpp"
  31. #include "SelfAwareness.hpp"
  32. #include "Network.hpp"
  33. #include "Trace.hpp"
  34. #include "Metrics.hpp"
  35. #include "PacketMultiplexer.hpp"
  36. // FIXME: remove this suppression and actually fix warnings
  37. #ifdef __GNUC__
  38. #pragma GCC diagnostic ignored "-Wsign-compare"
  39. #endif
  40. namespace ZeroTier {
  41. /****************************************************************************/
  42. /* Public Node interface (C++, exposed via CAPI bindings) */
  43. /****************************************************************************/
  44. Node::Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now) :
  45. _RR(this),
  46. RR(&_RR),
  47. _uPtr(uptr),
  48. _networks(8),
  49. _now(now),
  50. _lastPingCheck(0),
  51. _lastGratuitousPingCheck(0),
  52. _lastHousekeepingRun(0),
  53. _lastMemoizedTraceSettings(0),
  54. _lowBandwidthMode(false)
  55. {
  56. if (callbacks->version != 0) {
  57. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  58. }
  59. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  60. // Initialize non-cryptographic PRNG from a good random source
  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. memset((void *)(&_stats),0,sizeof(_stats));
  67. uint64_t idtmp[2];
  68. idtmp[0] = 0;
  69. idtmp[1] = 0;
  70. char tmp[2048];
  71. int n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,tmp,sizeof(tmp) - 1);
  72. if (n > 0) {
  73. tmp[n] = (char)0;
  74. if (RR->identity.fromString(tmp)) {
  75. RR->identity.toString(false,RR->publicIdentityStr);
  76. RR->identity.toString(true,RR->secretIdentityStr);
  77. } else {
  78. throw ZT_EXCEPTION_INVALID_IDENTITY;
  79. }
  80. if (!RR->identity.locallyValidate()) {
  81. throw ZT_EXCEPTION_INVALID_IDENTITY;
  82. }
  83. }
  84. if (n <= 0) {
  85. RR->identity.generate();
  86. RR->identity.toString(false,RR->publicIdentityStr);
  87. RR->identity.toString(true,RR->secretIdentityStr);
  88. idtmp[0] = RR->identity.address().toInt();
  89. idtmp[1] = 0;
  90. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,RR->secretIdentityStr,(unsigned int)strlen(RR->secretIdentityStr));
  91. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  92. } else {
  93. idtmp[0] = RR->identity.address().toInt();
  94. idtmp[1] = 0;
  95. n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,tmp,sizeof(tmp) - 1);
  96. if ((n > 0)&&(n < (int)sizeof(RR->publicIdentityStr))&&(n < (int)sizeof(tmp))) {
  97. if (memcmp(tmp,RR->publicIdentityStr,n)) {
  98. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  99. }
  100. }
  101. }
  102. char *m = (char *)0;
  103. try {
  104. const unsigned long ts = sizeof(Trace) + (((sizeof(Trace) & 0xf) != 0) ? (16 - (sizeof(Trace) & 0xf)) : 0);
  105. const unsigned long sws = sizeof(Switch) + (((sizeof(Switch) & 0xf) != 0) ? (16 - (sizeof(Switch) & 0xf)) : 0);
  106. const unsigned long mcs = sizeof(Multicaster) + (((sizeof(Multicaster) & 0xf) != 0) ? (16 - (sizeof(Multicaster) & 0xf)) : 0);
  107. const unsigned long topologys = sizeof(Topology) + (((sizeof(Topology) & 0xf) != 0) ? (16 - (sizeof(Topology) & 0xf)) : 0);
  108. const unsigned long sas = sizeof(SelfAwareness) + (((sizeof(SelfAwareness) & 0xf) != 0) ? (16 - (sizeof(SelfAwareness) & 0xf)) : 0);
  109. const unsigned long bcs = sizeof(Bond) + (((sizeof(Bond) & 0xf) != 0) ? (16 - (sizeof(Bond) & 0xf)) : 0);
  110. const unsigned long pms = sizeof(PacketMultiplexer) + (((sizeof(PacketMultiplexer) & 0xf) != 0) ? (16 - (sizeof(PacketMultiplexer) & 0xf)) : 0);
  111. m = reinterpret_cast<char *>(::malloc(16 + ts + sws + mcs + topologys + sas + bcs + pms));
  112. if (!m) {
  113. throw std::bad_alloc();
  114. }
  115. RR->rtmem = m;
  116. while (((uintptr_t)m & 0xf) != 0) {
  117. ++m;
  118. }
  119. RR->t = new (m) Trace(RR);
  120. m += ts;
  121. RR->sw = new (m) Switch(RR);
  122. m += sws;
  123. RR->mc = new (m) Multicaster(RR);
  124. m += mcs;
  125. RR->topology = new (m) Topology(RR,tptr);
  126. m += topologys;
  127. RR->sa = new (m) SelfAwareness(RR);
  128. m += sas;
  129. RR->bc = new (m) Bond(RR);
  130. m += bcs;
  131. RR->pm = new (m) PacketMultiplexer(RR);
  132. } catch ( ... ) {
  133. if (RR->sa) {
  134. RR->sa->~SelfAwareness();
  135. }
  136. if (RR->topology) {
  137. RR->topology->~Topology();
  138. }
  139. if (RR->mc) {
  140. RR->mc->~Multicaster();
  141. }
  142. if (RR->sw) {
  143. RR->sw->~Switch();
  144. }
  145. if (RR->t) {
  146. RR->t->~Trace();
  147. }
  148. if (RR->bc) {
  149. RR->bc->~Bond();
  150. }
  151. if (RR->pm) {
  152. RR->pm->~PacketMultiplexer();
  153. }
  154. ::free(m);
  155. throw;
  156. }
  157. postEvent(tptr,ZT_EVENT_UP);
  158. }
  159. Node::~Node()
  160. {
  161. {
  162. Mutex::Lock _l(_networks_m);
  163. _networks.clear(); // destroy all networks before shutdown
  164. }
  165. if (RR->sa) {
  166. RR->sa->~SelfAwareness();
  167. }
  168. if (RR->topology) {
  169. RR->topology->~Topology();
  170. }
  171. if (RR->mc) {
  172. RR->mc->~Multicaster();
  173. }
  174. if (RR->sw) {
  175. RR->sw->~Switch();
  176. }
  177. if (RR->t) {
  178. RR->t->~Trace();
  179. }
  180. if (RR->bc) {
  181. RR->bc->~Bond();
  182. }
  183. if (RR->pm) {
  184. RR->pm->~PacketMultiplexer();
  185. }
  186. ::free(RR->rtmem);
  187. }
  188. ZT_ResultCode Node::processWirePacket(
  189. void *tptr,
  190. int64_t now,
  191. int64_t localSocket,
  192. const struct sockaddr_storage *remoteAddress,
  193. const void *packetData,
  194. unsigned int packetLength,
  195. volatile int64_t *nextBackgroundTaskDeadline)
  196. {
  197. _now = now;
  198. RR->sw->onRemotePacket(tptr,localSocket,*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  199. return ZT_RESULT_OK;
  200. }
  201. ZT_ResultCode Node::processVirtualNetworkFrame(
  202. void *tptr,
  203. int64_t now,
  204. uint64_t nwid,
  205. uint64_t sourceMac,
  206. uint64_t destMac,
  207. unsigned int etherType,
  208. unsigned int vlanId,
  209. const void *frameData,
  210. unsigned int frameLength,
  211. volatile int64_t *nextBackgroundTaskDeadline)
  212. {
  213. _now = now;
  214. SharedPtr<Network> nw(this->network(nwid));
  215. if (nw) {
  216. RR->sw->onLocalEthernet(tptr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  217. return ZT_RESULT_OK;
  218. } else {
  219. return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  220. }
  221. }
  222. void Node::initMultithreading(bool isEnabled, unsigned int concurrency, bool cpuPinningEnabled)
  223. {
  224. _multithreadingEnabled = isEnabled;
  225. RR->pm->setUpPostDecodeReceiveThreads(concurrency, cpuPinningEnabled);
  226. }
  227. // Closure used to ping upstream and active/online peers
  228. class _PingPeersThatNeedPing
  229. {
  230. public:
  231. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,void *tPtr,Hashtable< Address,std::vector<InetAddress> > &alwaysContact,int64_t now) :
  232. RR(renv),
  233. _tPtr(tPtr),
  234. _alwaysContact(alwaysContact),
  235. _now(now),
  236. _bestCurrentUpstream(RR->topology->getUpstreamPeer())
  237. {
  238. }
  239. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  240. {
  241. const std::vector<InetAddress> *const alwaysContactEndpoints = _alwaysContact.get(p->address());
  242. if (alwaysContactEndpoints) {
  243. ZT_PeerRole role = RR->topology->role(p->address());
  244. // Contact upstream peers as infrequently as possible
  245. int roleBasedTimerScale = (role == ZT_PEER_ROLE_LEAF) ? 2 : 16;
  246. // Unless we don't any have paths to the roots, then we shouldn't wait a long time to contact them
  247. bool hasPaths = p->paths(RR->node->now()).size() > 0;
  248. roleBasedTimerScale = (role != ZT_PEER_ROLE_LEAF && !hasPaths) ? 0 : roleBasedTimerScale;
  249. if ((RR->node->now() - p->lastSentFullHello()) <= (ZT_PATH_HEARTBEAT_PERIOD * roleBasedTimerScale)) {
  250. return;
  251. }
  252. const unsigned int sent = p->doPingAndKeepalive(_tPtr,_now);
  253. bool contacted = (sent != 0);
  254. if ((sent & 0x1) == 0) { // bit 0x1 == IPv4 sent
  255. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)alwaysContactEndpoints->size();++k) {
  256. const InetAddress &addr = (*alwaysContactEndpoints)[ptr++ % alwaysContactEndpoints->size()];
  257. if (addr.ss_family == AF_INET) {
  258. p->sendHELLO(_tPtr,-1,addr,_now);
  259. contacted = true;
  260. break;
  261. }
  262. }
  263. }
  264. if ((sent & 0x2) == 0) { // bit 0x2 == IPv6 sent
  265. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)alwaysContactEndpoints->size();++k) {
  266. const InetAddress &addr = (*alwaysContactEndpoints)[ptr++ % alwaysContactEndpoints->size()];
  267. if (addr.ss_family == AF_INET6) {
  268. p->sendHELLO(_tPtr,-1,addr,_now);
  269. contacted = true;
  270. break;
  271. }
  272. }
  273. }
  274. if ((!contacted)&&(_bestCurrentUpstream)) {
  275. const SharedPtr<Path> up(_bestCurrentUpstream->getAppropriatePath(_now,true));
  276. if (up) {
  277. p->sendHELLO(_tPtr,up->localSocket(),up->address(),_now);
  278. }
  279. }
  280. _alwaysContact.erase(p->address()); // after this we'll WHOIS all upstreams that remain
  281. } else if (p->isActive(_now)) {
  282. p->doPingAndKeepalive(_tPtr,_now);
  283. }
  284. }
  285. private:
  286. const RuntimeEnvironment *RR;
  287. void *_tPtr;
  288. Hashtable< Address,std::vector<InetAddress> > &_alwaysContact;
  289. const int64_t _now;
  290. const SharedPtr<Peer> _bestCurrentUpstream;
  291. };
  292. ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  293. {
  294. _now = now;
  295. Mutex::Lock bl(_backgroundTasksLock);
  296. // Process background bond tasks
  297. unsigned long bondCheckInterval = ZT_PING_CHECK_INTERVAL;
  298. if (RR->bc->inUse()) {
  299. bondCheckInterval = std::max(RR->bc->minReqMonitorInterval(), ZT_CORE_TIMER_TASK_GRANULARITY);
  300. if ((now - _lastGratuitousPingCheck) >= ZT_CORE_TIMER_TASK_GRANULARITY) {
  301. _lastGratuitousPingCheck = now;
  302. RR->bc->processBackgroundTasks(tptr, now);
  303. }
  304. }
  305. unsigned long timeUntilNextPingCheck = _lowBandwidthMode ? (ZT_PING_CHECK_INTERVAL * 5) : ZT_PING_CHECK_INTERVAL;
  306. const int64_t timeSinceLastPingCheck = now - _lastPingCheck;
  307. if (timeSinceLastPingCheck >= timeUntilNextPingCheck) {
  308. try {
  309. _lastPingCheck = now;
  310. // Get designated VL1 upstreams
  311. Hashtable< Address,std::vector<InetAddress> > alwaysContact;
  312. RR->topology->getUpstreamsToContact(alwaysContact);
  313. // Uncomment to dump stats
  314. /*
  315. for(unsigned int i=0;i<32;i++) {
  316. if (_stats.inVerbCounts[i] > 0)
  317. printf("%.2x\t%12lld %lld\n",i,(unsigned long long)_stats.inVerbCounts[i],(unsigned long long)_stats.inVerbBytes[i]);
  318. }
  319. printf("\n");
  320. */
  321. // Check last receive time on designated upstreams to see if we seem to be online
  322. int64_t lastReceivedFromUpstream = 0;
  323. {
  324. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  325. Address *upstreamAddress = (Address *)0;
  326. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  327. while (i.next(upstreamAddress,upstreamStableEndpoints)) {
  328. SharedPtr<Peer> p(RR->topology->getPeerNoCache(*upstreamAddress));
  329. if (p) {
  330. lastReceivedFromUpstream = std::max(p->lastReceive(),lastReceivedFromUpstream);
  331. }
  332. }
  333. }
  334. // Clean up any old local controller auth memorizations.
  335. {
  336. _localControllerAuthorizations_m.lock();
  337. Hashtable< _LocalControllerAuth,int64_t >::Iterator i(_localControllerAuthorizations);
  338. _LocalControllerAuth *k = (_LocalControllerAuth *)0;
  339. int64_t *v = (int64_t *)0;
  340. while (i.next(k,v)) {
  341. if ((*v - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3)) {
  342. _localControllerAuthorizations.erase(*k);
  343. }
  344. }
  345. _localControllerAuthorizations_m.unlock();
  346. }
  347. // Get peers we should stay connected to according to network configs
  348. // Also get networks and whether they need config so we only have to do one pass over networks
  349. int timerScale = _lowBandwidthMode ? 64 : 1;
  350. std::vector< std::pair< SharedPtr<Network>,bool > > networkConfigNeeded;
  351. {
  352. Mutex::Lock l(_networks_m);
  353. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  354. uint64_t *nwid = (uint64_t *)0;
  355. SharedPtr<Network> *network = (SharedPtr<Network> *)0;
  356. while (i.next(nwid,network)) {
  357. (*network)->config().alwaysContactAddresses(alwaysContact);
  358. networkConfigNeeded.push_back( std::pair< SharedPtr<Network>,bool >(*network,(((now - (*network)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY * timerScale)||(!(*network)->hasConfig()))) );
  359. }
  360. }
  361. // Ping active peers, upstreams, and others that we should always contact
  362. _PingPeersThatNeedPing pfunc(RR,tptr,alwaysContact,now);
  363. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  364. // Run WHOIS to create Peer for alwaysContact addresses that could not be contacted
  365. {
  366. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  367. Address *upstreamAddress = (Address *)0;
  368. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  369. while (i.next(upstreamAddress,upstreamStableEndpoints)) {
  370. RR->sw->requestWhois(tptr,now,*upstreamAddress);
  371. }
  372. }
  373. // Refresh network config or broadcast network updates to members as needed
  374. for(std::vector< std::pair< SharedPtr<Network>,bool > >::const_iterator n(networkConfigNeeded.begin());n!=networkConfigNeeded.end();++n) {
  375. if (n->second) {
  376. n->first->requestConfiguration(tptr);
  377. }
  378. if (! _lowBandwidthMode) {
  379. n->first->sendUpdatesToMembers(tptr);
  380. }
  381. }
  382. // Update online status, post status change as event
  383. const bool oldOnline = _online;
  384. _online = (((now - lastReceivedFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amUpstream()));
  385. if (oldOnline != _online) {
  386. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  387. }
  388. } catch ( ... ) {
  389. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  390. }
  391. } else {
  392. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  393. }
  394. if ((now - _lastMemoizedTraceSettings) >= (ZT_HOUSEKEEPING_PERIOD / 4)) {
  395. _lastMemoizedTraceSettings = now;
  396. RR->t->updateMemoizedSettings();
  397. }
  398. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  399. _lastHousekeepingRun = now;
  400. try {
  401. RR->topology->doPeriodicTasks(tptr,now);
  402. RR->sa->clean(now);
  403. RR->mc->clean(now);
  404. } catch ( ... ) {
  405. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  406. }
  407. }
  408. try {
  409. *nextBackgroundTaskDeadline = now + (int64_t)std::max(std::min(bondCheckInterval,std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now))),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  410. } catch ( ... ) {
  411. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  412. }
  413. return ZT_RESULT_OK;
  414. }
  415. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  416. {
  417. Mutex::Lock _l(_networks_m);
  418. SharedPtr<Network> &nw = _networks[nwid];
  419. if (!nw) {
  420. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  421. }
  422. return ZT_RESULT_OK;
  423. }
  424. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  425. {
  426. ZT_VirtualNetworkConfig ctmp;
  427. void **nUserPtr = (void **)0;
  428. {
  429. Mutex::Lock _l(_networks_m);
  430. SharedPtr<Network> *nw = _networks.get(nwid);
  431. RR->sw->removeNetworkQoSControlBlock(nwid);
  432. if (!nw) {
  433. return ZT_RESULT_OK;
  434. }
  435. if (uptr) {
  436. *uptr = (*nw)->userPtr();
  437. }
  438. (*nw)->externalConfig(&ctmp);
  439. (*nw)->destroy();
  440. nUserPtr = (*nw)->userPtr();
  441. }
  442. if (nUserPtr) {
  443. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  444. }
  445. {
  446. Mutex::Lock _l(_networks_m);
  447. _networks.erase(nwid);
  448. }
  449. uint64_t tmp[2];
  450. tmp[0] = nwid;
  451. tmp[1] = 0;
  452. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  453. return ZT_RESULT_OK;
  454. }
  455. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  456. {
  457. SharedPtr<Network> nw(this->network(nwid));
  458. if (nw) {
  459. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  460. return ZT_RESULT_OK;
  461. } else {
  462. return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  463. }
  464. }
  465. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  466. {
  467. SharedPtr<Network> nw(this->network(nwid));
  468. if (nw) {
  469. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  470. return ZT_RESULT_OK;
  471. } else {
  472. return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  473. }
  474. }
  475. ZT_ResultCode Node::orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  476. {
  477. RR->topology->addMoon(tptr,moonWorldId,Address(moonSeed));
  478. return ZT_RESULT_OK;
  479. }
  480. ZT_ResultCode Node::deorbit(void *tptr,uint64_t moonWorldId)
  481. {
  482. RR->topology->removeMoon(tptr,moonWorldId);
  483. return ZT_RESULT_OK;
  484. }
  485. uint64_t Node::address() const
  486. {
  487. return RR->identity.address().toInt();
  488. }
  489. void Node::status(ZT_NodeStatus *status) const
  490. {
  491. status->address = RR->identity.address().toInt();
  492. status->publicIdentity = RR->publicIdentityStr;
  493. status->secretIdentity = RR->secretIdentityStr;
  494. status->online = _online ? 1 : 0;
  495. }
  496. ZT_PeerList *Node::peers() const
  497. {
  498. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  499. std::sort(peers.begin(),peers.end());
  500. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  501. if (!buf) {
  502. return (ZT_PeerList *)0;
  503. }
  504. ZT_PeerList *pl = (ZT_PeerList *)buf;
  505. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  506. pl->peerCount = 0;
  507. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  508. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  509. p->address = pi->second->address().toInt();
  510. p->isBonded = 0;
  511. if (pi->second->remoteVersionKnown()) {
  512. p->versionMajor = pi->second->remoteVersionMajor();
  513. p->versionMinor = pi->second->remoteVersionMinor();
  514. p->versionRev = pi->second->remoteVersionRevision();
  515. } else {
  516. p->versionMajor = -1;
  517. p->versionMinor = -1;
  518. p->versionRev = -1;
  519. }
  520. p->latency = pi->second->latency(_now);
  521. if (p->latency >= 0xffff) {
  522. p->latency = -1;
  523. }
  524. p->role = RR->topology->role(pi->second->identity().address());
  525. std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
  526. SharedPtr<Path> bestp(pi->second->getAppropriatePath(_now,false));
  527. p->pathCount = 0;
  528. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  529. if((*path)->valid()) {
  530. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  531. p->paths[p->pathCount].localSocket = (*path)->localSocket();
  532. p->paths[p->pathCount].localPort = (*path)->localPort();
  533. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  534. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  535. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  536. p->paths[p->pathCount].expired = 0;
  537. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  538. p->paths[p->pathCount].scope = (*path)->ipScope();
  539. if (pi->second->bond()) {
  540. p->paths[p->pathCount].latencyMean = (*path)->latencyMean();
  541. p->paths[p->pathCount].latencyVariance = (*path)->latencyVariance();
  542. p->paths[p->pathCount].packetLossRatio = (*path)->packetLossRatio();
  543. p->paths[p->pathCount].packetErrorRatio = (*path)->packetErrorRatio();
  544. p->paths[p->pathCount].assignedFlowCount = (*path)->assignedFlowCount();
  545. p->paths[p->pathCount].relativeQuality = (*path)->relativeQuality();
  546. p->paths[p->pathCount].linkSpeed = (*path)->givenLinkSpeed();
  547. p->paths[p->pathCount].bonded = (*path)->bonded();
  548. p->paths[p->pathCount].eligible = (*path)->eligible();
  549. std::string ifname = std::string((*path)->ifname());
  550. memset(p->paths[p->pathCount].ifname, 0x0, std::min((int)ifname.length() + 1, ZT_MAX_PHYSIFNAME));
  551. memcpy(p->paths[p->pathCount].ifname, ifname.c_str(), std::min((int)ifname.length(), ZT_MAX_PHYSIFNAME));
  552. }
  553. ++p->pathCount;
  554. }
  555. }
  556. if (pi->second->bond()) {
  557. p->isBonded = pi->second->bond();
  558. p->bondingPolicy = pi->second->bondingPolicy();
  559. p->numAliveLinks = pi->second->getNumAliveLinks();
  560. p->numTotalLinks = pi->second->getNumTotalLinks();
  561. }
  562. }
  563. return pl;
  564. }
  565. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  566. {
  567. Mutex::Lock _l(_networks_m);
  568. const SharedPtr<Network> *nw = _networks.get(nwid);
  569. if (nw) {
  570. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  571. (*nw)->externalConfig(nc);
  572. return nc;
  573. }
  574. return (ZT_VirtualNetworkConfig *)0;
  575. }
  576. ZT_VirtualNetworkList *Node::networks() const
  577. {
  578. Mutex::Lock _l(_networks_m);
  579. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  580. if (!buf) {
  581. return (ZT_VirtualNetworkList *)0;
  582. }
  583. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  584. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  585. nl->networkCount = 0;
  586. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  587. uint64_t *k = (uint64_t *)0;
  588. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  589. while (i.next(k,v)) {
  590. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  591. }
  592. return nl;
  593. }
  594. void Node::freeQueryResult(void *qr)
  595. {
  596. if (qr) {
  597. ::free(qr);
  598. }
  599. }
  600. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  601. {
  602. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  603. Mutex::Lock _l(_directPaths_m);
  604. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  605. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  606. return 1;
  607. }
  608. }
  609. return 0;
  610. }
  611. void Node::clearLocalInterfaceAddresses()
  612. {
  613. Mutex::Lock _l(_directPaths_m);
  614. _directPaths.clear();
  615. }
  616. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  617. {
  618. try {
  619. if (RR->identity.address().toInt() != dest) {
  620. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  621. outp.append(typeId);
  622. outp.append(data,len);
  623. outp.compress();
  624. RR->sw->send(tptr,outp,true);
  625. return 1;
  626. }
  627. } catch ( ... ) {}
  628. return 0;
  629. }
  630. void Node::setNetconfMaster(void *networkControllerInstance)
  631. {
  632. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  633. if (networkControllerInstance) {
  634. RR->localNetworkController->init(RR->identity, this);
  635. }
  636. }
  637. /****************************************************************************/
  638. /* Node methods used only within node/ */
  639. /****************************************************************************/
  640. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  641. {
  642. if (!Path::isAddressValidForPath(remoteAddress)) {
  643. return false;
  644. }
  645. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress)) {
  646. return false;
  647. }
  648. {
  649. Mutex::Lock _l(_networks_m);
  650. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  651. uint64_t *k = (uint64_t *)0;
  652. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  653. while (i.next(k,v)) {
  654. if ((*v)->hasConfig()) {
  655. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  656. if ((*v)->config().staticIps[k].containsAddress(remoteAddress)) {
  657. return false;
  658. }
  659. }
  660. }
  661. }
  662. }
  663. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  664. }
  665. uint64_t Node::prng()
  666. {
  667. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  668. uint64_t x = _prngState[0];
  669. const uint64_t y = _prngState[1];
  670. _prngState[0] = y;
  671. x ^= x << 23;
  672. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  673. _prngState[1] = z;
  674. return z + y;
  675. }
  676. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  677. {
  678. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  679. return ZT_RESULT_OK;
  680. }
  681. World Node::planet() const
  682. {
  683. return RR->topology->planet();
  684. }
  685. std::vector<World> Node::moons() const
  686. {
  687. return RR->topology->moons();
  688. }
  689. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  690. {
  691. _localControllerAuthorizations_m.lock();
  692. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  693. _localControllerAuthorizations_m.unlock();
  694. if (destination == RR->identity.address()) {
  695. SharedPtr<Network> n(network(nwid));
  696. if (!n) {
  697. return;
  698. }
  699. n->setConfiguration((void *)0,nc,true);
  700. } else {
  701. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  702. try {
  703. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  704. uint64_t configUpdateId = prng();
  705. if (!configUpdateId) {
  706. ++configUpdateId;
  707. }
  708. const unsigned int totalSize = dconf->sizeBytes();
  709. unsigned int chunkIndex = 0;
  710. while (chunkIndex < totalSize) {
  711. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  712. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  713. if (requestPacketId) {
  714. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  715. outp.append(requestPacketId);
  716. }
  717. const unsigned int sigStart = outp.size();
  718. outp.append(nwid);
  719. outp.append((uint16_t)chunkLen);
  720. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  721. outp.append((uint8_t)0); // no flags
  722. outp.append((uint64_t)configUpdateId);
  723. outp.append((uint32_t)totalSize);
  724. outp.append((uint32_t)chunkIndex);
  725. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  726. outp.append((uint8_t)1);
  727. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  728. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  729. outp.compress();
  730. RR->sw->send((void *)0,outp,true);
  731. chunkIndex += chunkLen;
  732. }
  733. }
  734. delete dconf;
  735. } catch ( ... ) {
  736. delete dconf;
  737. throw;
  738. }
  739. }
  740. }
  741. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  742. {
  743. if (destination == RR->identity.address()) {
  744. SharedPtr<Network> n(network(rev.networkId()));
  745. if (!n) {
  746. return;
  747. }
  748. n->addCredential((void *)0,RR->identity.address(),rev);
  749. } else {
  750. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  751. outp.append((uint8_t)0x00);
  752. outp.append((uint16_t)0);
  753. outp.append((uint16_t)0);
  754. outp.append((uint16_t)1);
  755. rev.serialize(outp);
  756. outp.append((uint16_t)0);
  757. RR->sw->send((void *)0,outp,true);
  758. }
  759. }
  760. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode, const void *errorData, unsigned int errorDataSize)
  761. {
  762. if (destination == RR->identity.address()) {
  763. SharedPtr<Network> n(network(nwid));
  764. if (!n) {
  765. return;
  766. }
  767. switch(errorCode) {
  768. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  769. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  770. n->setNotFound(nullptr);
  771. break;
  772. case NetworkController::NC_ERROR_ACCESS_DENIED:
  773. n->setAccessDenied(nullptr);
  774. break;
  775. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED: {
  776. //fprintf(stderr, "\n\nGot auth required\n\n");
  777. break;
  778. }
  779. default:
  780. break;
  781. }
  782. } else if (requestPacketId) {
  783. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  784. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  785. outp.append(requestPacketId);
  786. switch(errorCode) {
  787. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  788. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  789. default:
  790. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  791. Metrics::pkt_error_obj_not_found_out++;
  792. break;
  793. case NetworkController::NC_ERROR_ACCESS_DENIED:
  794. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  795. Metrics::pkt_error_network_access_denied_out++;
  796. break;
  797. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED:
  798. outp.append((unsigned char)Packet::ERROR_NETWORK_AUTHENTICATION_REQUIRED);
  799. Metrics::pkt_error_authentication_required_out++;
  800. break;
  801. }
  802. outp.append(nwid);
  803. if ((errorData)&&(errorDataSize > 0)&&(errorDataSize <= 0xffff)) {
  804. outp.append((uint16_t)errorDataSize);
  805. outp.append(errorData, errorDataSize);
  806. }
  807. RR->sw->send((void *)0,outp,true);
  808. } // else we can't send an ERROR() in response to nothing, so discard
  809. }
  810. } // namespace ZeroTier
  811. /****************************************************************************/
  812. /* CAPI bindings */
  813. /****************************************************************************/
  814. extern "C" {
  815. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  816. {
  817. *node = (ZT_Node *)0;
  818. try {
  819. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  820. return ZT_RESULT_OK;
  821. } catch (std::bad_alloc &exc) {
  822. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  823. } catch (std::runtime_error &exc) {
  824. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  825. } catch ( ... ) {
  826. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  827. }
  828. }
  829. void ZT_Node_delete(ZT_Node *node)
  830. {
  831. try {
  832. delete (reinterpret_cast<ZeroTier::Node *>(node));
  833. } catch ( ... ) {}
  834. }
  835. enum ZT_ResultCode ZT_Node_processWirePacket(
  836. ZT_Node *node,
  837. void *tptr,
  838. int64_t now,
  839. int64_t localSocket,
  840. const struct sockaddr_storage *remoteAddress,
  841. const void *packetData,
  842. unsigned int packetLength,
  843. volatile int64_t *nextBackgroundTaskDeadline)
  844. {
  845. try {
  846. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  847. } catch (std::bad_alloc &exc) {
  848. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  849. } catch ( ... ) {
  850. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  851. }
  852. }
  853. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  854. ZT_Node *node,
  855. void *tptr,
  856. int64_t now,
  857. uint64_t nwid,
  858. uint64_t sourceMac,
  859. uint64_t destMac,
  860. unsigned int etherType,
  861. unsigned int vlanId,
  862. const void *frameData,
  863. unsigned int frameLength,
  864. volatile int64_t *nextBackgroundTaskDeadline)
  865. {
  866. try {
  867. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  868. } catch (std::bad_alloc &exc) {
  869. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  870. } catch ( ... ) {
  871. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  872. }
  873. }
  874. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  875. {
  876. try {
  877. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  878. } catch (std::bad_alloc &exc) {
  879. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  880. } catch ( ... ) {
  881. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  882. }
  883. }
  884. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  885. {
  886. try {
  887. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  888. } catch (std::bad_alloc &exc) {
  889. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  890. } catch ( ... ) {
  891. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  892. }
  893. }
  894. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  895. {
  896. try {
  897. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  898. } catch (std::bad_alloc &exc) {
  899. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  900. } catch ( ... ) {
  901. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  902. }
  903. }
  904. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  905. {
  906. try {
  907. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  908. } catch (std::bad_alloc &exc) {
  909. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  910. } catch ( ... ) {
  911. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  912. }
  913. }
  914. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  915. {
  916. try {
  917. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  918. } catch (std::bad_alloc &exc) {
  919. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  920. } catch ( ... ) {
  921. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  922. }
  923. }
  924. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  925. {
  926. try {
  927. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  928. } catch ( ... ) {
  929. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  930. }
  931. }
  932. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  933. {
  934. try {
  935. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  936. } catch ( ... ) {
  937. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  938. }
  939. }
  940. uint64_t ZT_Node_address(ZT_Node *node)
  941. {
  942. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  943. }
  944. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  945. {
  946. try {
  947. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  948. } catch ( ... ) {}
  949. }
  950. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  951. {
  952. try {
  953. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  954. } catch ( ... ) {
  955. return (ZT_PeerList *)0;
  956. }
  957. }
  958. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  959. {
  960. try {
  961. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  962. } catch ( ... ) {
  963. return (ZT_VirtualNetworkConfig *)0;
  964. }
  965. }
  966. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  967. {
  968. try {
  969. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  970. } catch ( ... ) {
  971. return (ZT_VirtualNetworkList *)0;
  972. }
  973. }
  974. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  975. {
  976. try {
  977. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  978. } catch ( ... ) {}
  979. }
  980. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  981. {
  982. try {
  983. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  984. } catch ( ... ) {
  985. return 0;
  986. }
  987. }
  988. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  989. {
  990. try {
  991. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  992. } catch ( ... ) {}
  993. }
  994. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  995. {
  996. try {
  997. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  998. } catch ( ... ) {
  999. return 0;
  1000. }
  1001. }
  1002. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  1003. {
  1004. try {
  1005. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  1006. } catch ( ... ) {}
  1007. }
  1008. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  1009. {
  1010. try {
  1011. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  1012. } catch ( ... ) {
  1013. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  1014. }
  1015. }
  1016. void ZT_version(int *major,int *minor,int *revision)
  1017. {
  1018. if (major) {
  1019. *major = ZEROTIER_ONE_VERSION_MAJOR;
  1020. }
  1021. if (minor) {
  1022. *minor = ZEROTIER_ONE_VERSION_MINOR;
  1023. }
  1024. if (revision) {
  1025. *revision = ZEROTIER_ONE_VERSION_REVISION;
  1026. }
  1027. }
  1028. } // extern "C"