Node.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "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, const int64_t now) :
  34. t(RR),
  35. expect(),
  36. vl2(RR),
  37. vl1(RR),
  38. sa(RR),
  39. topology(RR, tPtr, now)
  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(
  62. void *uPtr,
  63. void *tPtr,
  64. const struct ZT_Node_Callbacks *callbacks,
  65. int64_t now) :
  66. m_RR(this),
  67. RR(&m_RR),
  68. m_objects(nullptr),
  69. m_cb(*callbacks),
  70. m_uPtr(uPtr),
  71. m_networks(),
  72. m_lastPeerPulse(0),
  73. m_lastHousekeepingRun(0),
  74. m_lastNetworkHousekeepingRun(0),
  75. m_now(now),
  76. m_online(false)
  77. {
  78. ZT_SPEW("starting up...");
  79. // Load this node's identity.
  80. uint64_t idtmp[2];
  81. idtmp[0] = 0;
  82. idtmp[1] = 0;
  83. Vector< uint8_t > data(stateObjectGet(tPtr, ZT_STATE_OBJECT_IDENTITY_SECRET, idtmp));
  84. bool haveIdentity = false;
  85. if (!data.empty()) {
  86. data.push_back(0); // zero-terminate string
  87. if (RR->identity.fromString((const char *)data.data())) {
  88. RR->identity.toString(false, RR->publicIdentityStr);
  89. RR->identity.toString(true, RR->secretIdentityStr);
  90. haveIdentity = true;
  91. ZT_SPEW("loaded identity %s", RR->identity.toString().c_str());
  92. }
  93. }
  94. // Generate a new identity if we don't have one.
  95. if (!haveIdentity) {
  96. RR->identity.generate(Identity::C25519);
  97. RR->identity.toString(false, RR->publicIdentityStr);
  98. RR->identity.toString(true, RR->secretIdentityStr);
  99. idtmp[0] = RR->identity.address();
  100. 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. ZT_SPEW("no pre-existing identity found, created %s", RR->identity.toString().c_str());
  104. } else {
  105. idtmp[0] = RR->identity.address();
  106. idtmp[1] = 0;
  107. data = stateObjectGet(tPtr, ZT_STATE_OBJECT_IDENTITY_PUBLIC, idtmp);
  108. if ((data.empty()) || (memcmp(data.data(), RR->publicIdentityStr, strlen(RR->publicIdentityStr)) != 0))
  109. stateObjectPut(tPtr, ZT_STATE_OBJECT_IDENTITY_PUBLIC, idtmp, RR->publicIdentityStr, (unsigned int)strlen(RR->publicIdentityStr));
  110. }
  111. // Create a secret key for encrypting local data at rest.
  112. uint8_t tmph[ZT_SHA384_DIGEST_SIZE];
  113. RR->identity.hashWithPrivate(tmph);
  114. SHA384(tmph, tmph, ZT_SHA384_DIGEST_SIZE);
  115. RR->localCacheSymmetric.init(tmph);
  116. Utils::burn(tmph, ZT_SHA384_DIGEST_SIZE);
  117. // Generate a random sort order for privileged ports for use in NAT-t algorithms.
  118. for (unsigned int i = 0; i < 1023; ++i)
  119. RR->randomPrivilegedPortOrder[i] = (uint16_t)(i + 1);
  120. for (unsigned int i = 0; i < 512; ++i) {
  121. uint64_t rn = Utils::random();
  122. const unsigned int a = (unsigned int)rn % 1023;
  123. const unsigned int b = (unsigned int)(rn >> 32U) % 1023;
  124. if (a != b) {
  125. const uint16_t tmp = RR->randomPrivilegedPortOrder[a];
  126. RR->randomPrivilegedPortOrder[a] = RR->randomPrivilegedPortOrder[b];
  127. RR->randomPrivilegedPortOrder[b] = tmp;
  128. }
  129. }
  130. // This constructs all the components of the ZeroTier core within a single contiguous memory container,
  131. // which reduces memory fragmentation and may improve cache locality.
  132. ZT_SPEW("initializing subsystem objects...");
  133. m_objects = new _NodeObjects(RR, tPtr, now);
  134. ZT_SPEW("node initialized!");
  135. postEvent(tPtr, ZT_EVENT_UP);
  136. }
  137. Node::~Node()
  138. {
  139. ZT_SPEW("node destructor run");
  140. m_networks_l.lock();
  141. m_networks_l.unlock();
  142. m_networks.clear();
  143. m_networks_l.lock();
  144. m_networks_l.unlock();
  145. if (m_objects)
  146. delete (_NodeObjects *)m_objects;
  147. // Let go of cached Buf objects. If other nodes happen to be running in this
  148. // same process space new Bufs will be allocated as needed, but this is almost
  149. // never the case. Calling this here saves RAM if we are running inside something
  150. // that wants to keep running after tearing down its ZeroTier core instance.
  151. Buf::freePool();
  152. }
  153. void Node::shutdown(void *tPtr)
  154. {
  155. ZT_SPEW("explicit shutdown() called");
  156. postEvent(tPtr, ZT_EVENT_DOWN);
  157. if (RR->topology)
  158. RR->topology->saveAll(tPtr);
  159. }
  160. ZT_ResultCode Node::processWirePacket(
  161. void *tPtr,
  162. int64_t now,
  163. int64_t localSocket,
  164. const struct sockaddr_storage *remoteAddress,
  165. SharedPtr< Buf > &packetData,
  166. unsigned int packetLength,
  167. volatile int64_t *nextBackgroundTaskDeadline)
  168. {
  169. m_now = now;
  170. RR->vl1->onRemotePacket(tPtr, localSocket, (remoteAddress) ? InetAddress::NIL : *asInetAddress(remoteAddress), packetData, packetLength);
  171. return ZT_RESULT_OK;
  172. }
  173. ZT_ResultCode Node::processVirtualNetworkFrame(
  174. void *tPtr,
  175. int64_t now,
  176. uint64_t nwid,
  177. uint64_t sourceMac,
  178. uint64_t destMac,
  179. unsigned int etherType,
  180. unsigned int vlanId,
  181. SharedPtr< Buf > &frameData,
  182. unsigned int frameLength,
  183. volatile int64_t *nextBackgroundTaskDeadline)
  184. {
  185. m_now = now;
  186. SharedPtr< Network > nw(this->network(nwid));
  187. if (nw) {
  188. RR->vl2->onLocalEthernet(tPtr, nw, MAC(sourceMac), MAC(destMac), etherType, vlanId, frameData, frameLength);
  189. return ZT_RESULT_OK;
  190. } else {
  191. return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  192. }
  193. }
  194. ZT_ResultCode Node::processBackgroundTasks(
  195. void *tPtr,
  196. int64_t now,
  197. volatile int64_t *nextBackgroundTaskDeadline)
  198. {
  199. m_now = now;
  200. Mutex::Lock bl(m_backgroundTasksLock);
  201. try {
  202. // Call peer pulse() method of all peers every ZT_PEER_PULSE_INTERVAL.
  203. if ((now - m_lastPeerPulse) >= ZT_PEER_PULSE_INTERVAL) {
  204. m_lastPeerPulse = now;
  205. ZT_SPEW("running pulse() on each peer...");
  206. try {
  207. Vector< SharedPtr< Peer > > allPeers, rootPeers;
  208. RR->topology->allPeers(allPeers, rootPeers);
  209. bool online = false;
  210. for (Vector< SharedPtr< Peer > >::iterator p(allPeers.begin()); p != allPeers.end(); ++p) {
  211. const bool isRoot = std::find(rootPeers.begin(), rootPeers.end(), *p) != rootPeers.end();
  212. (*p)->pulse(tPtr, now, isRoot);
  213. online |= ((isRoot || rootPeers.empty()) && (*p)->directlyConnected(now));
  214. }
  215. if (m_online.exchange(online) != online)
  216. postEvent(tPtr, online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  217. } catch (...) {
  218. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  219. }
  220. }
  221. // Perform network housekeeping and possibly request new certs and configs every ZT_NETWORK_HOUSEKEEPING_PERIOD.
  222. if ((now - m_lastNetworkHousekeepingRun) >= ZT_NETWORK_HOUSEKEEPING_PERIOD) {
  223. m_lastHousekeepingRun = now;
  224. ZT_SPEW("running networking housekeeping...");
  225. RWMutex::RLock l(m_networks_l);
  226. for (Map< uint64_t, SharedPtr< Network > >::const_iterator i(m_networks.begin()); i != m_networks.end(); ++i) {
  227. i->second->doPeriodicTasks(tPtr, now);
  228. }
  229. }
  230. // Clean up other stuff every ZT_HOUSEKEEPING_PERIOD.
  231. if ((now - m_lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  232. m_lastHousekeepingRun = now;
  233. ZT_SPEW("running housekeeping...");
  234. // Clean up any old local controller auth memoizations. This is an
  235. // optimization for network controllers to know whether to accept
  236. // or trust nodes without doing an extra cert check.
  237. m_localControllerAuthorizations_l.lock();
  238. for (Map< p_LocalControllerAuth, int64_t >::iterator i(m_localControllerAuthorizations.begin()); i != m_localControllerAuthorizations.end();) { // NOLINT(hicpp-use-auto,modernize-use-auto)
  239. if ((i->second - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  240. m_localControllerAuthorizations.erase(i++);
  241. else ++i;
  242. }
  243. m_localControllerAuthorizations_l.unlock();
  244. RR->topology->doPeriodicTasks(tPtr, now);
  245. RR->sa->clean(now);
  246. }
  247. *nextBackgroundTaskDeadline = now + ZT_TIMER_TASK_INTERVAL;
  248. } catch (...) {
  249. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  250. }
  251. return ZT_RESULT_OK;
  252. }
  253. ZT_ResultCode Node::join(
  254. uint64_t nwid,
  255. const ZT_Fingerprint *controllerFingerprint,
  256. void *uptr,
  257. void *tptr)
  258. {
  259. Fingerprint fp;
  260. if (controllerFingerprint) {
  261. fp = *controllerFingerprint;
  262. ZT_SPEW("joining network %.16llx with fingerprint %s", nwid, fp.toString().c_str());
  263. } else {
  264. ZT_SPEW("joining network %.16llx", nwid);
  265. }
  266. RWMutex::Lock l(m_networks_l);
  267. SharedPtr< Network > &nw = m_networks[nwid];
  268. if (nw)
  269. return ZT_RESULT_OK;
  270. nw.set(new Network(RR, tptr, nwid, fp, uptr, nullptr));
  271. return ZT_RESULT_OK;
  272. }
  273. ZT_ResultCode Node::leave(
  274. uint64_t nwid,
  275. void **uptr,
  276. void *tptr)
  277. {
  278. ZT_SPEW("leaving network %.16llx", nwid);
  279. ZT_VirtualNetworkConfig ctmp;
  280. m_networks_l.lock();
  281. Map< uint64_t, SharedPtr< Network > >::iterator nwi(m_networks.find(nwid)); // NOLINT(hicpp-use-auto,modernize-use-auto)
  282. if (nwi == m_networks.end()) {
  283. m_networks_l.unlock();
  284. return ZT_RESULT_OK;
  285. }
  286. SharedPtr< Network > nw(nwi->second);
  287. m_networks.erase(nwi);
  288. m_networks_l.unlock();
  289. if (uptr)
  290. *uptr = *nw->userPtr();
  291. nw->externalConfig(&ctmp);
  292. RR->node->configureVirtualNetworkPort(tptr, nwid, uptr, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY, &ctmp);
  293. nw->destroy();
  294. nw.zero();
  295. uint64_t tmp[2];
  296. tmp[0] = nwid;
  297. tmp[1] = 0;
  298. RR->node->stateObjectDelete(tptr, ZT_STATE_OBJECT_NETWORK_CONFIG, tmp);
  299. return ZT_RESULT_OK;
  300. }
  301. ZT_ResultCode Node::multicastSubscribe(
  302. void *tPtr,
  303. uint64_t nwid,
  304. uint64_t multicastGroup,
  305. unsigned long multicastAdi)
  306. {
  307. ZT_SPEW("multicast subscribe to %s:%lu", MAC(multicastGroup).toString().c_str(), multicastAdi);
  308. const SharedPtr< Network > nw(this->network(nwid));
  309. if (nw) {
  310. nw->multicastSubscribe(tPtr, MulticastGroup(MAC(multicastGroup), (uint32_t)(multicastAdi & 0xffffffff)));
  311. return ZT_RESULT_OK;
  312. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  313. }
  314. ZT_ResultCode Node::multicastUnsubscribe(
  315. uint64_t nwid,
  316. uint64_t multicastGroup,
  317. unsigned long multicastAdi)
  318. {
  319. ZT_SPEW("multicast unsubscribe from %s:%lu", MAC(multicastGroup).toString().c_str(), multicastAdi);
  320. const SharedPtr< Network > nw(this->network(nwid));
  321. if (nw) {
  322. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup), (uint32_t)(multicastAdi & 0xffffffff)));
  323. return ZT_RESULT_OK;
  324. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  325. }
  326. uint64_t Node::address() const
  327. {
  328. return RR->identity.address().toInt();
  329. }
  330. void Node::status(ZT_NodeStatus *status) const
  331. {
  332. status->address = RR->identity.address().toInt();
  333. status->identity = reinterpret_cast<const ZT_Identity *>(&RR->identity);
  334. status->publicIdentity = RR->publicIdentityStr;
  335. status->secretIdentity = RR->secretIdentityStr;
  336. status->online = m_online ? 1 : 0;
  337. }
  338. ZT_PeerList *Node::peers() const
  339. {
  340. Vector< SharedPtr< Peer > > peers, rootPeers;
  341. RR->topology->allPeers(peers, rootPeers);
  342. std::sort(peers.begin(), peers.end(), _sortPeerPtrsByAddress());
  343. const unsigned int bufSize =
  344. sizeof(ZT_PeerList) +
  345. (sizeof(ZT_Peer) * peers.size()) +
  346. ((sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size()) +
  347. (sizeof(Identity) * peers.size()) +
  348. (ZT_LOCATOR_MARSHAL_SIZE_MAX * peers.size());
  349. char *buf = (char *)malloc(bufSize);
  350. if (!buf)
  351. return nullptr;
  352. Utils::zero(buf, bufSize);
  353. ZT_PeerList *pl = reinterpret_cast<ZT_PeerList *>(buf);
  354. buf += sizeof(ZT_PeerList);
  355. pl->freeFunction = reinterpret_cast<void (*)(const void *)>(free);
  356. pl->peers = reinterpret_cast<ZT_Peer *>(buf);
  357. buf += sizeof(ZT_Peer) * peers.size();
  358. ZT_Path *peerPath = reinterpret_cast<ZT_Path *>(buf);
  359. buf += (sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size();
  360. Identity *identities = reinterpret_cast<Identity *>(buf);
  361. buf += sizeof(Identity) * peers.size();
  362. uint8_t *locatorBuf = reinterpret_cast<uint8_t *>(buf);
  363. const int64_t now = m_now;
  364. pl->peerCount = 0;
  365. for (Vector< SharedPtr< Peer > >::iterator pi(peers.begin()); pi != peers.end(); ++pi) {
  366. ZT_Peer *const p = pl->peers + pl->peerCount;
  367. p->address = (*pi)->address().toInt();
  368. identities[pl->peerCount] = (*pi)->identity(); // need to make a copy in case peer gets deleted
  369. p->identity = identities + pl->peerCount;
  370. p->fingerprint.address = p->address;
  371. Utils::copy< ZT_FINGERPRINT_HASH_SIZE >(p->fingerprint.hash, (*pi)->identity().fingerprint().hash);
  372. if ((*pi)->remoteVersionKnown()) {
  373. p->versionMajor = (int)(*pi)->remoteVersionMajor();
  374. p->versionMinor = (int)(*pi)->remoteVersionMinor();
  375. p->versionRev = (int)(*pi)->remoteVersionRevision();
  376. } else {
  377. p->versionMajor = -1;
  378. p->versionMinor = -1;
  379. p->versionRev = -1;
  380. }
  381. p->latency = (*pi)->latency();
  382. p->root = (std::find(rootPeers.begin(), rootPeers.end(), *pi) != rootPeers.end()) ? 1 : 0;
  383. p->networkCount = 0;
  384. // TODO: enumerate network memberships
  385. Vector< SharedPtr< Path > > paths;
  386. (*pi)->getAllPaths(paths);
  387. p->pathCount = (unsigned int)paths.size();
  388. p->paths = peerPath;
  389. for (Vector< SharedPtr< Path > >::iterator path(paths.begin()); path != paths.end(); ++path) {
  390. ZT_Path *const pp = peerPath++;
  391. pp->endpoint.type = ZT_ENDPOINT_TYPE_IP_UDP; // only type supported right now
  392. Utils::copy< sizeof(sockaddr_storage) >(&pp->endpoint.value.ss, &((*path)->address().as.ss));
  393. pp->lastSend = (*path)->lastOut();
  394. pp->lastReceive = (*path)->lastIn();
  395. pp->alive = (*path)->alive(now) ? 1 : 0;
  396. pp->preferred = (p->pathCount == 0) ? 1 : 0;
  397. }
  398. const SharedPtr< const Locator > loc((*pi)->locator());
  399. if (loc) {
  400. const int ls = loc->marshal(locatorBuf);
  401. if (ls > 0) {
  402. p->locatorSize = (unsigned int)ls;
  403. p->locator = locatorBuf;
  404. locatorBuf += ls;
  405. }
  406. }
  407. ++pl->peerCount;
  408. }
  409. return pl;
  410. }
  411. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  412. {
  413. SharedPtr< Network > nw(network(nwid));
  414. if (nw) {
  415. ZT_VirtualNetworkConfig *const nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  416. nw->externalConfig(nc);
  417. return nc;
  418. }
  419. return nullptr;
  420. }
  421. ZT_VirtualNetworkList *Node::networks() const
  422. {
  423. RWMutex::RLock l(m_networks_l);
  424. char *const buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * m_networks.size()));
  425. if (!buf)
  426. return nullptr;
  427. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf; // NOLINT(modernize-use-auto,hicpp-use-auto)
  428. nl->freeFunction = reinterpret_cast<void (*)(const void *)>(free);
  429. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  430. nl->networkCount = 0;
  431. 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)
  432. i->second->externalConfig(&(nl->networks[nl->networkCount++]));
  433. return nl;
  434. }
  435. void Node::setNetworkUserPtr(
  436. uint64_t nwid,
  437. void *ptr)
  438. {
  439. SharedPtr< Network > nw(network(nwid));
  440. if (nw)
  441. *(nw->userPtr()) = ptr;
  442. }
  443. void Node::setInterfaceAddresses(
  444. const ZT_InterfaceAddress *addrs,
  445. unsigned int addrCount)
  446. {
  447. Mutex::Lock _l(m_localInterfaceAddresses_m);
  448. m_localInterfaceAddresses.clear();
  449. for (unsigned int i = 0; i < addrCount; ++i) {
  450. bool dupe = false;
  451. for (unsigned int j = 0; j < i; ++j) {
  452. if (*(reinterpret_cast<const InetAddress *>(&addrs[j].address)) == *(reinterpret_cast<const InetAddress *>(&addrs[i].address))) {
  453. dupe = true;
  454. break;
  455. }
  456. }
  457. if (!dupe)
  458. m_localInterfaceAddresses.push_back(addrs[i]);
  459. }
  460. }
  461. ZT_ResultCode Node::addPeer(
  462. void *tptr,
  463. const ZT_Identity *identity)
  464. {
  465. if (!identity)
  466. return ZT_RESULT_ERROR_BAD_PARAMETER;
  467. SharedPtr< Peer > peer(RR->topology->peer(tptr, reinterpret_cast<const Identity *>(identity)->address()));
  468. if (!peer) {
  469. peer.set(new Peer(RR));
  470. peer->init(*reinterpret_cast<const Identity *>(identity));
  471. peer = RR->topology->add(tptr, peer);
  472. }
  473. return (peer->identity() == *reinterpret_cast<const Identity *>(identity)) ? ZT_RESULT_OK : ZT_RESULT_ERROR_COLLIDING_OBJECT;
  474. }
  475. int Node::tryPeer(
  476. void *tptr,
  477. const ZT_Fingerprint *fp,
  478. const ZT_Endpoint *endpoint,
  479. int retries)
  480. {
  481. if ((!fp) || (!endpoint))
  482. return 0;
  483. const SharedPtr< Peer > peer(RR->topology->peer(tptr, fp->address, true));
  484. if ((peer) && (peer->identity().fingerprint().bestSpecificityEquals(*fp))) {
  485. peer->contact(tptr, m_now, Endpoint(*endpoint), std::min(retries, 1));
  486. return 1;
  487. }
  488. return 0;
  489. }
  490. ZT_CertificateError Node::addCertificate(
  491. void *tptr,
  492. int64_t now,
  493. unsigned int localTrust,
  494. const ZT_Certificate *cert,
  495. const void *certData,
  496. unsigned int certSize)
  497. {
  498. Certificate c;
  499. if (cert) {
  500. c = *cert;
  501. } else {
  502. if ((!certData) || (!certSize))
  503. return ZT_CERTIFICATE_ERROR_INVALID_FORMAT;
  504. if (!c.decode(certData, certSize))
  505. return ZT_CERTIFICATE_ERROR_INVALID_FORMAT;
  506. }
  507. return RR->topology->addCertificate(tptr, c, now, localTrust, true, true, true);
  508. }
  509. ZT_ResultCode Node::deleteCertificate(
  510. void *tptr,
  511. const void *serialNo)
  512. {
  513. if (!serialNo)
  514. return ZT_RESULT_ERROR_BAD_PARAMETER;
  515. RR->topology->deleteCertificate(tptr, reinterpret_cast<const uint8_t *>(serialNo));
  516. return ZT_RESULT_OK;
  517. }
  518. struct p_certificateListInternal
  519. {
  520. Vector< SharedPtr< const Certificate > > c;
  521. Vector< unsigned int > t;
  522. };
  523. static void p_freeCertificateList(const void *cl)
  524. {
  525. if (cl) {
  526. reinterpret_cast<const p_certificateListInternal *>(reinterpret_cast<const uint8_t *>(cl) + sizeof(ZT_CertificateList))->~p_certificateListInternal();
  527. free(const_cast<void *>(cl));
  528. }
  529. }
  530. ZT_CertificateList *Node::listCertificates()
  531. {
  532. ZT_CertificateList *const cl = (ZT_CertificateList *)malloc(sizeof(ZT_CertificateList) + sizeof(p_certificateListInternal));
  533. if (!cl)
  534. return nullptr;
  535. p_certificateListInternal *const clint = reinterpret_cast<p_certificateListInternal *>(reinterpret_cast<uint8_t *>(cl) + sizeof(ZT_CertificateList));
  536. new (clint) p_certificateListInternal;
  537. RR->topology->allCerts(clint->c, clint->t);
  538. cl->freeFunction = p_freeCertificateList;
  539. static_assert(sizeof(SharedPtr< const Certificate >) == sizeof(void *), "SharedPtr<> is not just a wrapped pointer");
  540. cl->certs = reinterpret_cast<const ZT_Certificate **>(clint->c.data());
  541. cl->localTrust = clint->t.data();
  542. cl->certCount = (unsigned long)clint->c.size();
  543. return cl;
  544. }
  545. int Node::sendUserMessage(
  546. void *tptr,
  547. uint64_t dest,
  548. uint64_t typeId,
  549. const void *data,
  550. unsigned int len)
  551. {
  552. try {
  553. if (RR->identity.address().toInt() != dest) {
  554. // TODO
  555. /*
  556. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  557. outp.append(typeId);
  558. outp.append(data,len);
  559. outp.compress();
  560. RR->sw->send(tptr,outp,true);
  561. */
  562. return 1;
  563. }
  564. } catch (...) {}
  565. return 0;
  566. }
  567. void Node::setController(void *networkControllerInstance)
  568. {
  569. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  570. if (networkControllerInstance)
  571. RR->localNetworkController->init(RR->identity, this);
  572. }
  573. // Methods used only within the core ----------------------------------------------------------------------------------
  574. Vector< uint8_t > Node::stateObjectGet(void *const tPtr, ZT_StateObjectType type, const uint64_t *id)
  575. {
  576. Vector< uint8_t > r;
  577. if (m_cb.stateGetFunction) {
  578. void *data = nullptr;
  579. void (*freeFunc)(void *) = nullptr;
  580. int l = m_cb.stateGetFunction(
  581. reinterpret_cast<ZT_Node *>(this),
  582. m_uPtr,
  583. tPtr,
  584. type,
  585. id,
  586. &data,
  587. &freeFunc);
  588. if ((l > 0) && (data) && (freeFunc)) {
  589. r.assign(reinterpret_cast<const uint8_t *>(data), reinterpret_cast<const uint8_t *>(data) + l);
  590. freeFunc(data);
  591. }
  592. }
  593. return r;
  594. }
  595. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr, const Identity &id, const int64_t localSocket, const InetAddress &remoteAddress)
  596. {
  597. {
  598. RWMutex::RLock l(m_networks_l);
  599. 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)
  600. for (unsigned int k = 0, j = i->second->config().staticIpCount; k < j; ++k) {
  601. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  602. return false;
  603. }
  604. }
  605. }
  606. if (m_cb.pathCheckFunction) {
  607. return (m_cb.pathCheckFunction(
  608. reinterpret_cast<ZT_Node *>(this),
  609. m_uPtr,
  610. tPtr,
  611. id.address().toInt(),
  612. (const ZT_Identity *)&id,
  613. localSocket,
  614. reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  615. }
  616. return true;
  617. }
  618. bool Node::externalPathLookup(void *tPtr, const Identity &id, int family, InetAddress &addr)
  619. {
  620. if (m_cb.pathLookupFunction) {
  621. return (m_cb.pathLookupFunction(
  622. reinterpret_cast<ZT_Node *>(this),
  623. m_uPtr,
  624. tPtr,
  625. id.address().toInt(),
  626. reinterpret_cast<const ZT_Identity *>(&id),
  627. family,
  628. reinterpret_cast<sockaddr_storage *>(&addr)) == ZT_RESULT_OK);
  629. }
  630. return false;
  631. }
  632. bool Node::localControllerHasAuthorized(const int64_t now, const uint64_t nwid, const Address &addr) const
  633. {
  634. m_localControllerAuthorizations_l.lock();
  635. Map<Node::p_LocalControllerAuth, int64_t>::const_iterator i(m_localControllerAuthorizations.find(p_LocalControllerAuth(nwid, addr)));
  636. const int64_t at = (i == m_localControllerAuthorizations.end()) ? -1LL : i->second;
  637. m_localControllerAuthorizations_l.unlock();
  638. if (at > 0)
  639. return ((now - at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  640. return false;
  641. }
  642. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  643. void Node::ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address &destination, const NetworkConfig &nc, bool sendLegacyFormatConfig)
  644. {
  645. m_localControllerAuthorizations_l.lock();
  646. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  647. m_localControllerAuthorizations_l.unlock();
  648. if (destination == RR->identity.address()) {
  649. SharedPtr< Network > n(network(nwid));
  650. if (!n)
  651. return;
  652. n->setConfiguration((void *)0, nc, true);
  653. } else {
  654. Dictionary dconf;
  655. if (nc.toDictionary(dconf)) {
  656. uint64_t configUpdateId = Utils::random();
  657. if (!configUpdateId)
  658. ++configUpdateId;
  659. Vector< uint8_t > ddata;
  660. dconf.encode(ddata);
  661. // TODO
  662. /*
  663. unsigned int chunkIndex = 0;
  664. while (chunkIndex < totalSize) {
  665. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  666. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  667. if (requestPacketId) {
  668. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  669. outp.append(requestPacketId);
  670. }
  671. const unsigned int sigStart = outp.size();
  672. outp.append(nwid);
  673. outp.append((uint16_t)chunkLen);
  674. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  675. outp.append((uint8_t)0); // no flags
  676. outp.append((uint64_t)configUpdateId);
  677. outp.append((uint32_t)totalSize);
  678. outp.append((uint32_t)chunkIndex);
  679. uint8_t sig[256];
  680. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  681. outp.append((uint8_t)1);
  682. outp.append((uint16_t)siglen);
  683. outp.append(sig,siglen);
  684. outp.compress();
  685. RR->sw->send((void *)0,outp,true);
  686. chunkIndex += chunkLen;
  687. }
  688. */
  689. }
  690. }
  691. }
  692. void Node::ncSendRevocation(const Address &destination, const RevocationCredential &rev)
  693. {
  694. if (destination == RR->identity.address()) {
  695. SharedPtr< Network > n(network(rev.networkId()));
  696. if (!n) return;
  697. n->addCredential(nullptr, RR->identity, rev);
  698. } else {
  699. // TODO
  700. /*
  701. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  702. outp.append((uint8_t)0x00);
  703. outp.append((uint16_t)0);
  704. outp.append((uint16_t)0);
  705. outp.append((uint16_t)1);
  706. rev.serialize(outp);
  707. outp.append((uint16_t)0);
  708. RR->sw->send((void *)0,outp,true);
  709. */
  710. }
  711. }
  712. void Node::ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address &destination, NetworkController::ErrorCode errorCode)
  713. {
  714. if (destination == RR->identity.address()) {
  715. SharedPtr< Network > n(network(nwid));
  716. if (!n) return;
  717. switch (errorCode) {
  718. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  719. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  720. n->setNotFound();
  721. break;
  722. case NetworkController::NC_ERROR_ACCESS_DENIED:
  723. n->setAccessDenied();
  724. break;
  725. default:
  726. break;
  727. }
  728. } else if (requestPacketId) {
  729. // TODO
  730. /*
  731. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  732. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  733. outp.append(requestPacketId);
  734. switch(errorCode) {
  735. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  736. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  737. default:
  738. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  739. break;
  740. case NetworkController::NC_ERROR_ACCESS_DENIED:
  741. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  742. break;
  743. }
  744. outp.append(nwid);
  745. RR->sw->send((void *)0,outp,true);
  746. */
  747. } // else we can't send an ERROR() in response to nothing, so discard
  748. }
  749. } // namespace ZeroTier