Node.cpp 32 KB

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