Node.cpp 35 KB

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