2
0

Node.cpp 35 KB

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