Node.cpp 35 KB

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