Node.cpp 34 KB

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