Node.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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].assignedFlowCount = (*path)->assignedFlowCount();
  529. p->paths[p->pathCount].relativeQuality = (*path)->relativeQuality();
  530. p->paths[p->pathCount].linkSpeed = (*path)->givenLinkSpeed();
  531. p->paths[p->pathCount].bonded = (*path)->bonded();
  532. p->paths[p->pathCount].eligible = (*path)->eligible();
  533. std::string ifname = std::string((*path)->ifname());
  534. memset(p->paths[p->pathCount].ifname, 0x0, std::min((int)ifname.length() + 1, ZT_MAX_PHYSIFNAME));
  535. memcpy(p->paths[p->pathCount].ifname, ifname.c_str(), std::min((int)ifname.length(), ZT_MAX_PHYSIFNAME));
  536. }
  537. ++p->pathCount;
  538. }
  539. }
  540. if (pi->second->bond()) {
  541. p->isBonded = pi->second->bond();
  542. p->bondingPolicy = pi->second->bondingPolicy();
  543. p->numAliveLinks = pi->second->getNumAliveLinks();
  544. p->numTotalLinks = pi->second->getNumTotalLinks();
  545. }
  546. }
  547. return pl;
  548. }
  549. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  550. {
  551. Mutex::Lock _l(_networks_m);
  552. const SharedPtr<Network> *nw = _networks.get(nwid);
  553. if (nw) {
  554. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  555. (*nw)->externalConfig(nc);
  556. return nc;
  557. }
  558. return (ZT_VirtualNetworkConfig *)0;
  559. }
  560. ZT_VirtualNetworkList *Node::networks() const
  561. {
  562. Mutex::Lock _l(_networks_m);
  563. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  564. if (!buf) {
  565. return (ZT_VirtualNetworkList *)0;
  566. }
  567. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  568. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  569. nl->networkCount = 0;
  570. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  571. uint64_t *k = (uint64_t *)0;
  572. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  573. while (i.next(k,v)) {
  574. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  575. }
  576. return nl;
  577. }
  578. void Node::freeQueryResult(void *qr)
  579. {
  580. if (qr) {
  581. ::free(qr);
  582. }
  583. }
  584. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  585. {
  586. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  587. Mutex::Lock _l(_directPaths_m);
  588. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  589. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  590. return 1;
  591. }
  592. }
  593. return 0;
  594. }
  595. void Node::clearLocalInterfaceAddresses()
  596. {
  597. Mutex::Lock _l(_directPaths_m);
  598. _directPaths.clear();
  599. }
  600. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  601. {
  602. try {
  603. if (RR->identity.address().toInt() != dest) {
  604. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  605. outp.append(typeId);
  606. outp.append(data,len);
  607. outp.compress();
  608. RR->sw->send(tptr,outp,true);
  609. return 1;
  610. }
  611. } catch ( ... ) {}
  612. return 0;
  613. }
  614. void Node::setNetconfMaster(void *networkControllerInstance)
  615. {
  616. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  617. if (networkControllerInstance) {
  618. RR->localNetworkController->init(RR->identity, this);
  619. }
  620. }
  621. /****************************************************************************/
  622. /* Node methods used only within node/ */
  623. /****************************************************************************/
  624. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  625. {
  626. if (!Path::isAddressValidForPath(remoteAddress)) {
  627. return false;
  628. }
  629. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress)) {
  630. return false;
  631. }
  632. {
  633. Mutex::Lock _l(_networks_m);
  634. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  635. uint64_t *k = (uint64_t *)0;
  636. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  637. while (i.next(k,v)) {
  638. if ((*v)->hasConfig()) {
  639. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  640. if ((*v)->config().staticIps[k].containsAddress(remoteAddress)) {
  641. return false;
  642. }
  643. }
  644. }
  645. }
  646. }
  647. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  648. }
  649. uint64_t Node::prng()
  650. {
  651. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  652. uint64_t x = _prngState[0];
  653. const uint64_t y = _prngState[1];
  654. _prngState[0] = y;
  655. x ^= x << 23;
  656. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  657. _prngState[1] = z;
  658. return z + y;
  659. }
  660. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  661. {
  662. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  663. return ZT_RESULT_OK;
  664. }
  665. World Node::planet() const
  666. {
  667. return RR->topology->planet();
  668. }
  669. std::vector<World> Node::moons() const
  670. {
  671. return RR->topology->moons();
  672. }
  673. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  674. {
  675. _localControllerAuthorizations_m.lock();
  676. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  677. _localControllerAuthorizations_m.unlock();
  678. if (destination == RR->identity.address()) {
  679. SharedPtr<Network> n(network(nwid));
  680. if (!n) {
  681. return;
  682. }
  683. n->setConfiguration((void *)0,nc,true);
  684. } else {
  685. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  686. try {
  687. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  688. uint64_t configUpdateId = prng();
  689. if (!configUpdateId) {
  690. ++configUpdateId;
  691. }
  692. const unsigned int totalSize = dconf->sizeBytes();
  693. unsigned int chunkIndex = 0;
  694. while (chunkIndex < totalSize) {
  695. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  696. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  697. if (requestPacketId) {
  698. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  699. outp.append(requestPacketId);
  700. }
  701. const unsigned int sigStart = outp.size();
  702. outp.append(nwid);
  703. outp.append((uint16_t)chunkLen);
  704. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  705. outp.append((uint8_t)0); // no flags
  706. outp.append((uint64_t)configUpdateId);
  707. outp.append((uint32_t)totalSize);
  708. outp.append((uint32_t)chunkIndex);
  709. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  710. outp.append((uint8_t)1);
  711. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  712. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  713. outp.compress();
  714. RR->sw->send((void *)0,outp,true);
  715. chunkIndex += chunkLen;
  716. }
  717. }
  718. delete dconf;
  719. } catch ( ... ) {
  720. delete dconf;
  721. throw;
  722. }
  723. }
  724. }
  725. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  726. {
  727. if (destination == RR->identity.address()) {
  728. SharedPtr<Network> n(network(rev.networkId()));
  729. if (!n) {
  730. return;
  731. }
  732. n->addCredential((void *)0,RR->identity.address(),rev);
  733. } else {
  734. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  735. outp.append((uint8_t)0x00);
  736. outp.append((uint16_t)0);
  737. outp.append((uint16_t)0);
  738. outp.append((uint16_t)1);
  739. rev.serialize(outp);
  740. outp.append((uint16_t)0);
  741. RR->sw->send((void *)0,outp,true);
  742. }
  743. }
  744. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode, const void *errorData, unsigned int errorDataSize)
  745. {
  746. if (destination == RR->identity.address()) {
  747. SharedPtr<Network> n(network(nwid));
  748. if (!n) {
  749. return;
  750. }
  751. switch(errorCode) {
  752. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  753. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  754. n->setNotFound(nullptr);
  755. break;
  756. case NetworkController::NC_ERROR_ACCESS_DENIED:
  757. n->setAccessDenied(nullptr);
  758. break;
  759. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED: {
  760. //fprintf(stderr, "\n\nGot auth required\n\n");
  761. break;
  762. }
  763. default:
  764. break;
  765. }
  766. } else if (requestPacketId) {
  767. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  768. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  769. outp.append(requestPacketId);
  770. switch(errorCode) {
  771. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  772. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  773. default:
  774. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  775. Metrics::pkt_error_obj_not_found_out++;
  776. break;
  777. case NetworkController::NC_ERROR_ACCESS_DENIED:
  778. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  779. Metrics::pkt_error_network_access_denied_out++;
  780. break;
  781. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED:
  782. outp.append((unsigned char)Packet::ERROR_NETWORK_AUTHENTICATION_REQUIRED);
  783. Metrics::pkt_error_authentication_required_out++;
  784. break;
  785. }
  786. outp.append(nwid);
  787. if ((errorData)&&(errorDataSize > 0)&&(errorDataSize <= 0xffff)) {
  788. outp.append((uint16_t)errorDataSize);
  789. outp.append(errorData, errorDataSize);
  790. }
  791. RR->sw->send((void *)0,outp,true);
  792. } // else we can't send an ERROR() in response to nothing, so discard
  793. }
  794. } // namespace ZeroTier
  795. /****************************************************************************/
  796. /* CAPI bindings */
  797. /****************************************************************************/
  798. extern "C" {
  799. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  800. {
  801. *node = (ZT_Node *)0;
  802. try {
  803. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  804. return ZT_RESULT_OK;
  805. } catch (std::bad_alloc &exc) {
  806. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  807. } catch (std::runtime_error &exc) {
  808. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  809. } catch ( ... ) {
  810. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  811. }
  812. }
  813. void ZT_Node_delete(ZT_Node *node)
  814. {
  815. try {
  816. delete (reinterpret_cast<ZeroTier::Node *>(node));
  817. } catch ( ... ) {}
  818. }
  819. enum ZT_ResultCode ZT_Node_processWirePacket(
  820. ZT_Node *node,
  821. void *tptr,
  822. int64_t now,
  823. int64_t localSocket,
  824. const struct sockaddr_storage *remoteAddress,
  825. const void *packetData,
  826. unsigned int packetLength,
  827. volatile int64_t *nextBackgroundTaskDeadline)
  828. {
  829. try {
  830. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  831. } catch (std::bad_alloc &exc) {
  832. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  833. } catch ( ... ) {
  834. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  835. }
  836. }
  837. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  838. ZT_Node *node,
  839. void *tptr,
  840. int64_t now,
  841. uint64_t nwid,
  842. uint64_t sourceMac,
  843. uint64_t destMac,
  844. unsigned int etherType,
  845. unsigned int vlanId,
  846. const void *frameData,
  847. unsigned int frameLength,
  848. volatile int64_t *nextBackgroundTaskDeadline)
  849. {
  850. try {
  851. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  852. } catch (std::bad_alloc &exc) {
  853. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  854. } catch ( ... ) {
  855. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  856. }
  857. }
  858. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  859. {
  860. try {
  861. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  862. } catch (std::bad_alloc &exc) {
  863. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  864. } catch ( ... ) {
  865. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  866. }
  867. }
  868. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  869. {
  870. try {
  871. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  872. } catch (std::bad_alloc &exc) {
  873. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  874. } catch ( ... ) {
  875. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  876. }
  877. }
  878. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  879. {
  880. try {
  881. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  882. } catch (std::bad_alloc &exc) {
  883. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  884. } catch ( ... ) {
  885. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  886. }
  887. }
  888. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  889. {
  890. try {
  891. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  892. } catch (std::bad_alloc &exc) {
  893. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  894. } catch ( ... ) {
  895. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  896. }
  897. }
  898. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  899. {
  900. try {
  901. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  902. } catch (std::bad_alloc &exc) {
  903. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  904. } catch ( ... ) {
  905. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  906. }
  907. }
  908. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  909. {
  910. try {
  911. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  912. } catch ( ... ) {
  913. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  914. }
  915. }
  916. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  917. {
  918. try {
  919. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  920. } catch ( ... ) {
  921. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  922. }
  923. }
  924. uint64_t ZT_Node_address(ZT_Node *node)
  925. {
  926. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  927. }
  928. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  929. {
  930. try {
  931. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  932. } catch ( ... ) {}
  933. }
  934. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  935. {
  936. try {
  937. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  938. } catch ( ... ) {
  939. return (ZT_PeerList *)0;
  940. }
  941. }
  942. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  943. {
  944. try {
  945. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  946. } catch ( ... ) {
  947. return (ZT_VirtualNetworkConfig *)0;
  948. }
  949. }
  950. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  951. {
  952. try {
  953. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  954. } catch ( ... ) {
  955. return (ZT_VirtualNetworkList *)0;
  956. }
  957. }
  958. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  959. {
  960. try {
  961. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  962. } catch ( ... ) {}
  963. }
  964. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  965. {
  966. try {
  967. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  968. } catch ( ... ) {
  969. return 0;
  970. }
  971. }
  972. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  973. {
  974. try {
  975. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  976. } catch ( ... ) {}
  977. }
  978. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  979. {
  980. try {
  981. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  982. } catch ( ... ) {
  983. return 0;
  984. }
  985. }
  986. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  987. {
  988. try {
  989. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  990. } catch ( ... ) {}
  991. }
  992. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  993. {
  994. try {
  995. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  996. } catch ( ... ) {
  997. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  998. }
  999. }
  1000. void ZT_version(int *major,int *minor,int *revision)
  1001. {
  1002. if (major) {
  1003. *major = ZEROTIER_ONE_VERSION_MAJOR;
  1004. }
  1005. if (minor) {
  1006. *minor = ZEROTIER_ONE_VERSION_MINOR;
  1007. }
  1008. if (revision) {
  1009. *revision = ZEROTIER_ONE_VERSION_REVISION;
  1010. }
  1011. }
  1012. } // extern "C"