2
0

Node.cpp 25 KB

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