Node.cpp 34 KB

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