Node.cpp 34 KB

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