Node.cpp 34 KB

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