Node.cpp 31 KB

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