Node.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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 "Constants.hpp"
  14. #include "SharedPtr.hpp"
  15. #include "Node.hpp"
  16. #include "NetworkController.hpp"
  17. #include "Topology.hpp"
  18. #include "Address.hpp"
  19. #include "Identity.hpp"
  20. #include "SelfAwareness.hpp"
  21. #include "Network.hpp"
  22. #include "Trace.hpp"
  23. #include "Locator.hpp"
  24. #include "Expect.hpp"
  25. #include "VL1.hpp"
  26. #include "VL2.hpp"
  27. #include "Buf.hpp"
  28. namespace ZeroTier {
  29. namespace {
  30. /**
  31. * All core objects of a ZeroTier node.
  32. *
  33. * This is just a box that allows us to allocate all core objects
  34. * and data structures at once for a bit of memory saves and improved
  35. * cache adjacency.
  36. */
  37. struct _NodeObjects
  38. {
  39. ZT_INLINE _NodeObjects(RuntimeEnvironment *const RR,void *const tPtr) :
  40. t(RR),
  41. expect(),
  42. vl2(RR),
  43. vl1(RR),
  44. sa(RR),
  45. topology(RR,tPtr)
  46. {
  47. RR->t = &t;
  48. RR->expect = &expect;
  49. RR->vl2 = &vl2;
  50. RR->vl1 = &vl1;
  51. RR->sa = &sa;
  52. RR->topology = &topology;
  53. }
  54. Trace t;
  55. Expect expect;
  56. VL2 vl2;
  57. VL1 vl1;
  58. SelfAwareness sa;
  59. Topology topology;
  60. };
  61. struct _sortPeerPtrsByAddress
  62. {
  63. ZT_INLINE bool operator()(const SharedPtr<Peer> &a,const SharedPtr<Peer> &b) const { return (a->address() < b->address()); }
  64. };
  65. } // anonymous namespace
  66. Node::Node(void *uPtr,void *tPtr,const struct ZT_Node_Callbacks *callbacks,int64_t now) :
  67. m_RR(this),
  68. RR(&m_RR),
  69. m_objects(nullptr),
  70. m_cb(*callbacks),
  71. m_uPtr(uPtr),
  72. m_networks(),
  73. m_lastPeerPulse(0),
  74. m_lastHousekeepingRun(0),
  75. m_lastNetworkHousekeepingRun(0),
  76. m_now(now),
  77. m_natMustDie(true),
  78. m_online(false)
  79. {
  80. // Load this node's identity.
  81. uint64_t idtmp[2]; idtmp[0] = 0; idtmp[1] = 0;
  82. Vector<uint8_t> data(stateObjectGet(tPtr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp));
  83. bool haveIdentity = false;
  84. if (!data.empty()) {
  85. data.push_back(0); // zero-terminate string
  86. if (RR->identity.fromString((const char *)data.data())) {
  87. RR->identity.toString(false,RR->publicIdentityStr);
  88. RR->identity.toString(true,RR->secretIdentityStr);
  89. haveIdentity = true;
  90. }
  91. }
  92. // Generate a new identity if we don't have one.
  93. if (!haveIdentity) {
  94. RR->identity.generate(Identity::C25519);
  95. RR->identity.toString(false,RR->publicIdentityStr);
  96. RR->identity.toString(true,RR->secretIdentityStr);
  97. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  98. stateObjectPut(tPtr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,RR->secretIdentityStr,(unsigned int)strlen(RR->secretIdentityStr));
  99. stateObjectPut(tPtr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  100. } else {
  101. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  102. data = stateObjectGet(tPtr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp);
  103. if ((data.empty())||(memcmp(data.data(),RR->publicIdentityStr,strlen(RR->publicIdentityStr)) != 0))
  104. stateObjectPut(tPtr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  105. }
  106. uint8_t tmph[ZT_SHA384_DIGEST_SIZE];
  107. RR->identity.hashWithPrivate(tmph);
  108. RR->localCacheSymmetric.init(tmph);
  109. // This constructs all the components of the ZeroTier core within a single contiguous memory container,
  110. // which reduces memory fragmentation and may improve cache locality.
  111. m_objects = new _NodeObjects(RR, tPtr);
  112. postEvent(tPtr, ZT_EVENT_UP);
  113. }
  114. Node::~Node()
  115. {
  116. m_networks_l.lock();
  117. m_networks_l.unlock();
  118. m_networks.clear();
  119. m_networks_l.lock();
  120. m_networks_l.unlock();
  121. if (m_objects)
  122. delete (_NodeObjects *)m_objects;
  123. // Let go of cached Buf objects. If other nodes happen to be running in this
  124. // same process space new Bufs will be allocated as needed, but this is almost
  125. // never the case. Calling this here saves RAM if we are running inside something
  126. // that wants to keep running after tearing down its ZeroTier core instance.
  127. Buf::freePool();
  128. }
  129. void Node::shutdown(void *tPtr)
  130. {
  131. if (RR->topology)
  132. RR->topology->saveAll(tPtr);
  133. }
  134. ZT_ResultCode Node::processWirePacket(
  135. void *tPtr,
  136. int64_t now,
  137. int64_t localSocket,
  138. const struct sockaddr_storage *remoteAddress,
  139. SharedPtr<Buf> &packetData,
  140. unsigned int packetLength,
  141. volatile int64_t *nextBackgroundTaskDeadline)
  142. {
  143. m_now = now;
  144. RR->vl1->onRemotePacket(tPtr,localSocket,(remoteAddress) ? InetAddress::NIL : *asInetAddress(remoteAddress),packetData,packetLength);
  145. return ZT_RESULT_OK;
  146. }
  147. ZT_ResultCode Node::processVirtualNetworkFrame(
  148. void *tPtr,
  149. int64_t now,
  150. uint64_t nwid,
  151. uint64_t sourceMac,
  152. uint64_t destMac,
  153. unsigned int etherType,
  154. unsigned int vlanId,
  155. SharedPtr<Buf> &frameData,
  156. unsigned int frameLength,
  157. volatile int64_t *nextBackgroundTaskDeadline)
  158. {
  159. m_now = now;
  160. SharedPtr<Network> nw(this->network(nwid));
  161. if (nw) {
  162. RR->vl2->onLocalEthernet(tPtr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  163. return ZT_RESULT_OK;
  164. } else {
  165. return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  166. }
  167. }
  168. struct _processBackgroundTasks_eachPeer
  169. {
  170. ZT_INLINE _processBackgroundTasks_eachPeer(const int64_t now_,Node *const parent_,void *const tPtr_) noexcept :
  171. now(now_),
  172. parent(parent_),
  173. tPtr(tPtr_),
  174. online(false),
  175. rootsNotOnline() {}
  176. const int64_t now;
  177. Node *const parent;
  178. void *const tPtr;
  179. bool online;
  180. std::vector< SharedPtr<Peer> > rootsNotOnline;
  181. ZT_INLINE void operator()(const SharedPtr<Peer> &peer,const bool isRoot) noexcept
  182. {
  183. peer->pulse(tPtr,now,isRoot);
  184. if (isRoot) {
  185. if (peer->directlyConnected(now)) {
  186. online = true;
  187. } else {
  188. rootsNotOnline.push_back(peer);
  189. }
  190. }
  191. }
  192. };
  193. ZT_ResultCode Node::processBackgroundTasks(void *tPtr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  194. {
  195. m_now = now;
  196. Mutex::Lock bl(m_backgroundTasksLock);
  197. try {
  198. // Call peer pulse() method of all peers every ZT_PEER_PULSE_INTERVAL.
  199. if ((now - m_lastPeerPulse) >= ZT_PEER_PULSE_INTERVAL) {
  200. m_lastPeerPulse = now;
  201. try {
  202. _processBackgroundTasks_eachPeer pf(now,this,tPtr);
  203. RR->topology->eachPeerWithRoot<_processBackgroundTasks_eachPeer &>(pf);
  204. if (pf.online != m_online) {
  205. m_online = pf.online;
  206. postEvent(tPtr, m_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  207. }
  208. RR->topology->rankRoots(now);
  209. if (pf.online) {
  210. // If we have at least one online root, request whois for roots not online.
  211. // This will give us updated locators for these roots which may contain new
  212. // IP addresses. It will also auto-discover IPs for roots that were not added
  213. // with an initial bootstrap address.
  214. // TODO
  215. //for (std::vector<Address>::const_iterator r(pf.rootsNotOnline.begin()); r != pf.rootsNotOnline.end(); ++r)
  216. // RR->sw->requestWhois(tPtr,now,*r);
  217. }
  218. } catch ( ... ) {
  219. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  220. }
  221. }
  222. // Perform network housekeeping and possibly request new certs and configs every ZT_NETWORK_HOUSEKEEPING_PERIOD.
  223. if ((now - m_lastNetworkHousekeepingRun) >= ZT_NETWORK_HOUSEKEEPING_PERIOD) {
  224. m_lastHousekeepingRun = now;
  225. {
  226. RWMutex::RLock l(m_networks_l);
  227. for(Map< uint64_t,SharedPtr<Network> >::const_iterator i(m_networks.begin());i != m_networks.end();++i)
  228. i->second->doPeriodicTasks(tPtr,now);
  229. }
  230. }
  231. // Clean up other stuff every ZT_HOUSEKEEPING_PERIOD.
  232. if ((now - m_lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  233. m_lastHousekeepingRun = now;
  234. try {
  235. // Clean up any old local controller auth memoizations. This is an
  236. // optimization for network controllers to know whether to accept
  237. // or trust nodes without doing an extra cert check.
  238. m_localControllerAuthorizations_l.lock();
  239. for(Map<p_LocalControllerAuth,int64_t>::iterator i(m_localControllerAuthorizations.begin());i != m_localControllerAuthorizations.end();) { // NOLINT(hicpp-use-auto,modernize-use-auto)
  240. if ((i->second - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  241. m_localControllerAuthorizations.erase(i++);
  242. else ++i;
  243. }
  244. m_localControllerAuthorizations_l.unlock();
  245. RR->topology->doPeriodicTasks(tPtr, now);
  246. RR->sa->clean(now);
  247. } catch ( ... ) {
  248. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  249. }
  250. }
  251. *nextBackgroundTaskDeadline = now + ZT_TIMER_TASK_INTERVAL;
  252. } catch ( ... ) {
  253. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  254. }
  255. return ZT_RESULT_OK;
  256. }
  257. ZT_ResultCode Node::join(uint64_t nwid,const ZT_Fingerprint *controllerFingerprint,void *uptr,void *tptr)
  258. {
  259. Fingerprint fp;
  260. if (controllerFingerprint)
  261. Utils::copy<sizeof(ZT_Fingerprint)>(fp.apiFingerprint(),controllerFingerprint);
  262. RWMutex::Lock l(m_networks_l);
  263. SharedPtr<Network> &nw = m_networks[nwid];
  264. if (nw)
  265. return ZT_RESULT_OK;
  266. nw.set(new Network(RR,tptr,nwid,fp,uptr,nullptr));
  267. return ZT_RESULT_OK;
  268. }
  269. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  270. {
  271. ZT_VirtualNetworkConfig ctmp;
  272. m_networks_l.lock();
  273. Map< uint64_t,SharedPtr<Network> >::iterator nwi(m_networks.find(nwid)); // NOLINT(hicpp-use-auto,modernize-use-auto)
  274. if (nwi == m_networks.end()) {
  275. m_networks_l.unlock();
  276. return ZT_RESULT_OK;
  277. }
  278. SharedPtr<Network> nw(nwi->second);
  279. m_networks.erase(nwi);
  280. m_networks_l.unlock();
  281. if (uptr)
  282. *uptr = *nw->userPtr();
  283. nw->externalConfig(&ctmp);
  284. RR->node->configureVirtualNetworkPort(tptr,nwid,uptr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  285. nw->destroy();
  286. nw.zero();
  287. uint64_t tmp[2];
  288. tmp[0] = nwid; tmp[1] = 0;
  289. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  290. return ZT_RESULT_OK;
  291. }
  292. ZT_ResultCode Node::multicastSubscribe(void *tPtr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  293. {
  294. const SharedPtr<Network> nw(this->network(nwid));
  295. if (nw) {
  296. nw->multicastSubscribe(tPtr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  297. return ZT_RESULT_OK;
  298. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  299. }
  300. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  301. {
  302. const SharedPtr<Network> nw(this->network(nwid));
  303. if (nw) {
  304. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  305. return ZT_RESULT_OK;
  306. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  307. }
  308. ZT_ResultCode Node::addRoot(void *tPtr,const ZT_Identity *identity,const sockaddr_storage *bootstrap)
  309. {
  310. if (!identity)
  311. return ZT_RESULT_ERROR_BAD_PARAMETER;
  312. InetAddress a;
  313. if (bootstrap)
  314. a = bootstrap;
  315. RR->topology->addRoot(tPtr,*reinterpret_cast<const Identity *>(identity),a);
  316. return ZT_RESULT_OK;
  317. }
  318. ZT_ResultCode Node::removeRoot(void *tPtr,const ZT_Identity *identity)
  319. {
  320. if (!identity)
  321. return ZT_RESULT_ERROR_BAD_PARAMETER;
  322. RR->topology->removeRoot(*reinterpret_cast<const Identity *>(identity));
  323. return ZT_RESULT_OK;
  324. }
  325. uint64_t Node::address() const
  326. {
  327. return RR->identity.address().toInt();
  328. }
  329. void Node::status(ZT_NodeStatus *status) const
  330. {
  331. status->address = RR->identity.address().toInt();
  332. status->identity = reinterpret_cast<const ZT_Identity *>(&RR->identity);
  333. status->publicIdentity = RR->publicIdentityStr;
  334. status->secretIdentity = RR->secretIdentityStr;
  335. status->online = m_online ? 1 : 0;
  336. }
  337. ZT_PeerList *Node::peers() const
  338. {
  339. std::vector< SharedPtr<Peer> > peers;
  340. RR->topology->getAllPeers(peers);
  341. std::sort(peers.begin(),peers.end(),_sortPeerPtrsByAddress());
  342. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()) + (sizeof(Identity) * peers.size()));
  343. if (!buf)
  344. return nullptr;
  345. ZT_PeerList *pl = (ZT_PeerList *)buf; // NOLINT(modernize-use-auto,hicpp-use-auto)
  346. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  347. Identity *identities = (Identity *)(buf + sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size())); // NOLINT(modernize-use-auto,hicpp-use-auto)
  348. const int64_t now = m_now;
  349. pl->peerCount = 0;
  350. for(std::vector< SharedPtr<Peer> >::iterator pi(peers.begin());pi!=peers.end();++pi) { // NOLINT(modernize-use-auto,modernize-loop-convert,hicpp-use-auto)
  351. ZT_Peer *const p = &(pl->peers[pl->peerCount]);
  352. p->address = (*pi)->address().toInt();
  353. identities[pl->peerCount] = (*pi)->identity(); // need to make a copy in case peer gets deleted
  354. p->identity = &identities[pl->peerCount];
  355. p->fingerprint.address = p->address;
  356. Utils::copy<ZT_FINGERPRINT_HASH_SIZE>(p->fingerprint.hash,(*pi)->identity().fingerprint().hash());
  357. if ((*pi)->remoteVersionKnown()) {
  358. p->versionMajor = (int)(*pi)->remoteVersionMajor();
  359. p->versionMinor = (int)(*pi)->remoteVersionMinor();
  360. p->versionRev = (int)(*pi)->remoteVersionRevision();
  361. } else {
  362. p->versionMajor = -1;
  363. p->versionMinor = -1;
  364. p->versionRev = -1;
  365. }
  366. p->latency = (*pi)->latency();
  367. p->root = RR->topology->isRoot((*pi)->identity()) ? 1 : 0;
  368. {
  369. FCV<Endpoint,ZT_MAX_PEER_NETWORK_PATHS> bs((*pi)->bootstrap());
  370. p->bootstrapAddressCount = 0;
  371. for (FCV<Endpoint,ZT_MAX_PEER_NETWORK_PATHS>::const_iterator i(bs.begin());i!=bs.end();++i) // NOLINT(modernize-loop-convert)
  372. Utils::copy<sizeof(sockaddr_storage)>(&(p->bootstrap[p->bootstrapAddressCount++]),&(*i));
  373. }
  374. std::vector< SharedPtr<Path> > paths;
  375. (*pi)->getAllPaths(paths);
  376. p->pathCount = 0;
  377. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) { // NOLINT(modernize-use-auto,modernize-loop-convert,hicpp-use-auto)
  378. Utils::copy<sizeof(sockaddr_storage)>(&(p->paths[p->pathCount].address),&((*path)->address()));
  379. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  380. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  381. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  382. p->paths[p->pathCount].alive = (*path)->alive(now) ? 1 : 0;
  383. p->paths[p->pathCount].preferred = (p->pathCount == 0) ? 1 : 0;
  384. ++p->pathCount;
  385. }
  386. ++pl->peerCount;
  387. }
  388. return pl;
  389. }
  390. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  391. {
  392. SharedPtr<Network> nw(network(nwid));
  393. if (nw) {
  394. ZT_VirtualNetworkConfig *const nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig)); // NOLINT(modernize-use-auto,hicpp-use-auto)
  395. nw->externalConfig(nc);
  396. return nc;
  397. }
  398. return nullptr;
  399. }
  400. ZT_VirtualNetworkList *Node::networks() const
  401. {
  402. RWMutex::RLock l(m_networks_l);
  403. char *const buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * m_networks.size()));
  404. if (!buf)
  405. return nullptr;
  406. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf; // NOLINT(modernize-use-auto,hicpp-use-auto)
  407. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  408. nl->networkCount = 0;
  409. for(Map< uint64_t,SharedPtr<Network> >::const_iterator i(m_networks.begin());i != m_networks.end();++i) // NOLINT(modernize-use-auto,modernize-loop-convert,hicpp-use-auto)
  410. i->second->externalConfig(&(nl->networks[nl->networkCount++]));
  411. return nl;
  412. }
  413. void Node::setNetworkUserPtr(uint64_t nwid,void *ptr)
  414. {
  415. SharedPtr<Network> nw(network(nwid));
  416. if (nw)
  417. *(nw->userPtr()) = ptr;
  418. }
  419. void Node::freeQueryResult(void *qr)
  420. {
  421. if (qr)
  422. ::free(qr);
  423. }
  424. void Node::setInterfaceAddresses(const ZT_InterfaceAddress *addrs,unsigned int addrCount)
  425. {
  426. Mutex::Lock _l(m_localInterfaceAddresses_m);
  427. m_localInterfaceAddresses.clear();
  428. for(unsigned int i=0;i<addrCount;++i) {
  429. bool dupe = false;
  430. for(unsigned int j=0;j<i;++j) {
  431. if (*(reinterpret_cast<const InetAddress *>(&addrs[j].address)) == *(reinterpret_cast<const InetAddress *>(&addrs[i].address))) {
  432. dupe = true;
  433. break;
  434. }
  435. }
  436. if (!dupe)
  437. m_localInterfaceAddresses.push_back(addrs[i]);
  438. }
  439. }
  440. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  441. {
  442. try {
  443. if (RR->identity.address().toInt() != dest) {
  444. // TODO
  445. /*
  446. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  447. outp.append(typeId);
  448. outp.append(data,len);
  449. outp.compress();
  450. RR->sw->send(tptr,outp,true);
  451. */
  452. return 1;
  453. }
  454. } catch ( ... ) {}
  455. return 0;
  456. }
  457. void Node::setController(void *networkControllerInstance)
  458. {
  459. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  460. if (networkControllerInstance)
  461. RR->localNetworkController->init(RR->identity,this);
  462. }
  463. // Methods used only within the core ----------------------------------------------------------------------------------
  464. Vector<uint8_t> Node::stateObjectGet(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2])
  465. {
  466. Vector<uint8_t> r;
  467. if (m_cb.stateGetFunction) {
  468. void *data = nullptr;
  469. void (*freeFunc)(void *) = nullptr;
  470. int l = m_cb.stateGetFunction(
  471. reinterpret_cast<ZT_Node *>(this),
  472. m_uPtr,
  473. tPtr,
  474. type,
  475. id,
  476. &data,
  477. &freeFunc);
  478. if ((l > 0)&&(data)&&(freeFunc)) {
  479. r.assign(reinterpret_cast<const uint8_t *>(data),reinterpret_cast<const uint8_t *>(data) + l);
  480. freeFunc(data);
  481. }
  482. }
  483. return r;
  484. }
  485. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Identity &id,const int64_t localSocket,const InetAddress &remoteAddress)
  486. {
  487. {
  488. RWMutex::RLock l(m_networks_l);
  489. for(Map< uint64_t,SharedPtr<Network> >::iterator i(m_networks.begin());i != m_networks.end();++i) { // NOLINT(hicpp-use-auto,modernize-use-auto,modernize-loop-convert)
  490. for (unsigned int k = 0,j = i->second->config().staticIpCount; k < j; ++k) {
  491. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  492. return false;
  493. }
  494. }
  495. }
  496. if (m_cb.pathCheckFunction) {
  497. return (m_cb.pathCheckFunction(
  498. reinterpret_cast<ZT_Node *>(this),
  499. m_uPtr,
  500. tPtr,
  501. id.address().toInt(),
  502. (const ZT_Identity *)&id,
  503. localSocket,
  504. reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  505. }
  506. return true;
  507. }
  508. bool Node::externalPathLookup(void *tPtr,const Identity &id,int family,InetAddress &addr)
  509. {
  510. if (m_cb.pathLookupFunction) {
  511. return (m_cb.pathLookupFunction(
  512. reinterpret_cast<ZT_Node *>(this),
  513. m_uPtr,
  514. tPtr,
  515. id.address().toInt(),
  516. reinterpret_cast<const ZT_Identity *>(&id),
  517. family,
  518. reinterpret_cast<sockaddr_storage *>(&addr)) == ZT_RESULT_OK);
  519. }
  520. return false;
  521. }
  522. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  523. {
  524. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  525. return ZT_RESULT_OK;
  526. }
  527. bool Node::localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address &addr) const
  528. {
  529. m_localControllerAuthorizations_l.lock();
  530. const int64_t *const at = m_localControllerAuthorizations.get(p_LocalControllerAuth(nwid, addr));
  531. m_localControllerAuthorizations_l.unlock();
  532. if (at)
  533. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  534. return false;
  535. }
  536. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  537. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  538. {
  539. m_localControllerAuthorizations_l.lock();
  540. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  541. m_localControllerAuthorizations_l.unlock();
  542. if (destination == RR->identity.address()) {
  543. SharedPtr<Network> n(network(nwid));
  544. if (!n) return;
  545. n->setConfiguration((void *)0,nc,true);
  546. } else {
  547. Dictionary dconf;
  548. if (nc.toDictionary(dconf,sendLegacyFormatConfig)) {
  549. uint64_t configUpdateId = Utils::random();
  550. if (!configUpdateId) ++configUpdateId;
  551. std::vector<uint8_t> ddata;
  552. dconf.encode(ddata);
  553. // TODO
  554. /*
  555. unsigned int chunkIndex = 0;
  556. while (chunkIndex < totalSize) {
  557. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  558. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  559. if (requestPacketId) {
  560. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  561. outp.append(requestPacketId);
  562. }
  563. const unsigned int sigStart = outp.size();
  564. outp.append(nwid);
  565. outp.append((uint16_t)chunkLen);
  566. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  567. outp.append((uint8_t)0); // no flags
  568. outp.append((uint64_t)configUpdateId);
  569. outp.append((uint32_t)totalSize);
  570. outp.append((uint32_t)chunkIndex);
  571. uint8_t sig[256];
  572. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  573. outp.append((uint8_t)1);
  574. outp.append((uint16_t)siglen);
  575. outp.append(sig,siglen);
  576. outp.compress();
  577. RR->sw->send((void *)0,outp,true);
  578. chunkIndex += chunkLen;
  579. }
  580. */
  581. }
  582. }
  583. }
  584. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  585. {
  586. if (destination == RR->identity.address()) {
  587. SharedPtr<Network> n(network(rev.networkId()));
  588. if (!n) return;
  589. n->addCredential(nullptr,RR->identity,rev);
  590. } else {
  591. // TODO
  592. /*
  593. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  594. outp.append((uint8_t)0x00);
  595. outp.append((uint16_t)0);
  596. outp.append((uint16_t)0);
  597. outp.append((uint16_t)1);
  598. rev.serialize(outp);
  599. outp.append((uint16_t)0);
  600. RR->sw->send((void *)0,outp,true);
  601. */
  602. }
  603. }
  604. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  605. {
  606. if (destination == RR->identity.address()) {
  607. SharedPtr<Network> n(network(nwid));
  608. if (!n) return;
  609. switch(errorCode) {
  610. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  611. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  612. n->setNotFound();
  613. break;
  614. case NetworkController::NC_ERROR_ACCESS_DENIED:
  615. n->setAccessDenied();
  616. break;
  617. default: break;
  618. }
  619. } else if (requestPacketId) {
  620. // TODO
  621. /*
  622. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  623. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  624. outp.append(requestPacketId);
  625. switch(errorCode) {
  626. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  627. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  628. default:
  629. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  630. break;
  631. case NetworkController::NC_ERROR_ACCESS_DENIED:
  632. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  633. break;
  634. }
  635. outp.append(nwid);
  636. RR->sw->send((void *)0,outp,true);
  637. */
  638. } // else we can't send an ERROR() in response to nothing, so discard
  639. }
  640. } // namespace ZeroTier
  641. // C API --------------------------------------------------------------------------------------------------------------
  642. extern "C" {
  643. // These macros make the idiom of passing buffers to outside code via the API work properly even
  644. // if the first address of Buf does not overlap with its data field, since the C++ standard does
  645. // not absolutely guarantee this.
  646. #define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) ))
  647. #define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
  648. void *ZT_getBuffer()
  649. {
  650. // When external code requests a Buf, grab one from the pool (or freshly allocated)
  651. // and return it with its reference count left at zero. It's the responsibility of
  652. // external code to bring it back via freeBuffer() or one of the processX() calls.
  653. // When this occurs it's either sent back to the pool with Buf's delete operator or
  654. // wrapped in a SharedPtr<> to be passed into the core.
  655. try {
  656. return _ZT_BUFTOPTR(new ZeroTier::Buf());
  657. } catch ( ... ) {
  658. return nullptr; // can only happen on out of memory condition
  659. }
  660. }
  661. ZT_SDK_API void ZT_freeBuffer(void *b)
  662. {
  663. if (b)
  664. delete _ZT_PTRTOBUF(b);
  665. }
  666. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  667. {
  668. *node = (ZT_Node *)0;
  669. try {
  670. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  671. return ZT_RESULT_OK;
  672. } catch (std::bad_alloc &exc) {
  673. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  674. } catch (std::runtime_error &exc) {
  675. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  676. } catch ( ... ) {
  677. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  678. }
  679. }
  680. void ZT_Node_delete(ZT_Node *node,void *tPtr)
  681. {
  682. try {
  683. reinterpret_cast<ZeroTier::Node *>(node)->shutdown(tPtr);
  684. delete (reinterpret_cast<ZeroTier::Node *>(node));
  685. } catch ( ... ) {}
  686. }
  687. enum ZT_ResultCode ZT_Node_processWirePacket(
  688. ZT_Node *node,
  689. void *tptr,
  690. int64_t now,
  691. int64_t localSocket,
  692. const struct sockaddr_storage *remoteAddress,
  693. const void *packetData,
  694. unsigned int packetLength,
  695. int isZtBuffer,
  696. volatile int64_t *nextBackgroundTaskDeadline)
  697. {
  698. try {
  699. ZeroTier::SharedPtr<ZeroTier::Buf> buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData,packetLength & ZT_BUF_MEM_MASK));
  700. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,buf,packetLength,nextBackgroundTaskDeadline);
  701. } catch (std::bad_alloc &exc) {
  702. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  703. } catch ( ... ) {
  704. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  705. }
  706. }
  707. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  708. ZT_Node *node,
  709. void *tptr,
  710. int64_t now,
  711. uint64_t nwid,
  712. uint64_t sourceMac,
  713. uint64_t destMac,
  714. unsigned int etherType,
  715. unsigned int vlanId,
  716. const void *frameData,
  717. unsigned int frameLength,
  718. int isZtBuffer,
  719. volatile int64_t *nextBackgroundTaskDeadline)
  720. {
  721. try {
  722. ZeroTier::SharedPtr<ZeroTier::Buf> buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData,frameLength & ZT_BUF_MEM_MASK));
  723. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,buf,frameLength,nextBackgroundTaskDeadline);
  724. } catch (std::bad_alloc &exc) {
  725. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  726. } catch ( ... ) {
  727. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  728. }
  729. }
  730. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  731. {
  732. try {
  733. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  734. } catch (std::bad_alloc &exc) {
  735. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  736. } catch ( ... ) {
  737. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  738. }
  739. }
  740. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,const ZT_Fingerprint *controllerFingerprint,void *uptr,void *tptr)
  741. {
  742. try {
  743. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,controllerFingerprint,uptr,tptr);
  744. } catch (std::bad_alloc &exc) {
  745. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  746. } catch ( ... ) {
  747. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  748. }
  749. }
  750. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  751. {
  752. try {
  753. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  754. } catch (std::bad_alloc &exc) {
  755. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  756. } catch ( ... ) {
  757. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  758. }
  759. }
  760. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  761. {
  762. try {
  763. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  764. } catch (std::bad_alloc &exc) {
  765. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  766. } catch ( ... ) {
  767. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  768. }
  769. }
  770. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  771. {
  772. try {
  773. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  774. } catch (std::bad_alloc &exc) {
  775. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  776. } catch ( ... ) {
  777. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  778. }
  779. }
  780. enum ZT_ResultCode ZT_Node_addRoot(ZT_Node *node,void *tptr,const ZT_Identity *identity,const struct sockaddr_storage *bootstrap)
  781. {
  782. try {
  783. return reinterpret_cast<ZeroTier::Node *>(node)->addRoot(tptr,identity,bootstrap);
  784. } catch (std::bad_alloc &exc) {
  785. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  786. } catch ( ... ) {
  787. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  788. }
  789. }
  790. enum ZT_ResultCode ZT_Node_removeRoot(ZT_Node *node,void *tptr,const ZT_Identity *identity)
  791. {
  792. try {
  793. return reinterpret_cast<ZeroTier::Node *>(node)->removeRoot(tptr,identity);
  794. } catch (std::bad_alloc &exc) {
  795. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  796. } catch ( ... ) {
  797. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  798. }
  799. }
  800. uint64_t ZT_Node_address(ZT_Node *node)
  801. {
  802. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  803. }
  804. const ZT_Identity *ZT_Node_identity(ZT_Node *node)
  805. {
  806. return (const ZT_Identity *)(&(reinterpret_cast<ZeroTier::Node *>(node)->identity()));
  807. }
  808. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  809. {
  810. try {
  811. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  812. } catch ( ... ) {}
  813. }
  814. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  815. {
  816. try {
  817. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  818. } catch ( ... ) {
  819. return (ZT_PeerList *)0;
  820. }
  821. }
  822. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  823. {
  824. try {
  825. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  826. } catch ( ... ) {
  827. return (ZT_VirtualNetworkConfig *)0;
  828. }
  829. }
  830. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  831. {
  832. try {
  833. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  834. } catch ( ... ) {
  835. return (ZT_VirtualNetworkList *)0;
  836. }
  837. }
  838. void ZT_Node_setNetworkUserPtr(ZT_Node *node,uint64_t nwid,void *ptr)
  839. {
  840. try {
  841. reinterpret_cast<ZeroTier::Node *>(node)->setNetworkUserPtr(nwid,ptr);
  842. } catch ( ... ) {}
  843. }
  844. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  845. {
  846. try {
  847. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  848. } catch ( ... ) {}
  849. }
  850. void ZT_Node_setInterfaceAddresses(ZT_Node *node,const ZT_InterfaceAddress *addrs,unsigned int addrCount)
  851. {
  852. try {
  853. reinterpret_cast<ZeroTier::Node *>(node)->setInterfaceAddresses(addrs,addrCount);
  854. } catch ( ... ) {}
  855. }
  856. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  857. {
  858. try {
  859. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  860. } catch ( ... ) {
  861. return 0;
  862. }
  863. }
  864. void ZT_Node_setController(ZT_Node *node,void *networkControllerInstance)
  865. {
  866. try {
  867. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  868. } catch ( ... ) {}
  869. }
  870. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  871. {
  872. try {
  873. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  874. } catch ( ... ) {
  875. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  876. }
  877. }
  878. void ZT_version(int *major,int *minor,int *revision,int *build)
  879. {
  880. if (major)
  881. *major = ZEROTIER_VERSION_MAJOR;
  882. if (minor)
  883. *minor = ZEROTIER_VERSION_MINOR;
  884. if (revision)
  885. *revision = ZEROTIER_VERSION_REVISION;
  886. if (build)
  887. *build = ZEROTIER_VERSION_BUILD;
  888. }
  889. } // extern "C"