Node.cpp 34 KB

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