Node.cpp 35 KB

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