Node.cpp 34 KB

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