Node.cpp 31 KB

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