2
0

Node.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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, 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::processHTTPResponse(
  195. void *tptr,
  196. int64_t now,
  197. void *requestId,
  198. int responseCode,
  199. const char **headerNames,
  200. const char **headerValues,
  201. const void *body,
  202. unsigned int bodySize,
  203. unsigned int flags)
  204. {
  205. return ZT_RESULT_OK;
  206. }
  207. ZT_ResultCode Node::processBackgroundTasks(
  208. void *tPtr,
  209. int64_t now,
  210. volatile int64_t *nextBackgroundTaskDeadline)
  211. {
  212. m_now = now;
  213. Mutex::Lock bl(m_backgroundTasksLock);
  214. try {
  215. // Call peer pulse() method of all peers every ZT_PEER_PULSE_INTERVAL.
  216. if ((now - m_lastPeerPulse) >= ZT_PEER_PULSE_INTERVAL) {
  217. m_lastPeerPulse = now;
  218. ZT_SPEW("running pulse() on each peer...");
  219. try {
  220. Vector< SharedPtr< Peer > > allPeers, rootPeers;
  221. RR->topology->allPeers(allPeers, rootPeers);
  222. bool online = false;
  223. for (Vector< SharedPtr< Peer > >::iterator p(allPeers.begin()); p != allPeers.end(); ++p) {
  224. const bool isRoot = std::find(rootPeers.begin(), rootPeers.end(), *p) != rootPeers.end();
  225. (*p)->pulse(tPtr, now, isRoot);
  226. online |= ((isRoot || rootPeers.empty()) && (*p)->directlyConnected(now));
  227. }
  228. if (m_online.exchange(online) != online)
  229. postEvent(tPtr, online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  230. } catch (...) {
  231. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  232. }
  233. }
  234. // Perform network housekeeping and possibly request new certs and configs every ZT_NETWORK_HOUSEKEEPING_PERIOD.
  235. if ((now - m_lastNetworkHousekeepingRun) >= ZT_NETWORK_HOUSEKEEPING_PERIOD) {
  236. m_lastHousekeepingRun = now;
  237. ZT_SPEW("running networking housekeeping...");
  238. RWMutex::RLock l(m_networks_l);
  239. for (Map< uint64_t, SharedPtr< Network > >::const_iterator i(m_networks.begin()); i != m_networks.end(); ++i) {
  240. i->second->doPeriodicTasks(tPtr, now);
  241. }
  242. }
  243. // Clean up other stuff every ZT_HOUSEKEEPING_PERIOD.
  244. if ((now - m_lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  245. m_lastHousekeepingRun = now;
  246. ZT_SPEW("running housekeeping...");
  247. // Clean up any old local controller auth memoizations. This is an
  248. // optimization for network controllers to know whether to accept
  249. // or trust nodes without doing an extra cert check.
  250. m_localControllerAuthorizations_l.lock();
  251. for (Map< p_LocalControllerAuth, int64_t >::iterator i(m_localControllerAuthorizations.begin()); i != m_localControllerAuthorizations.end();) { // NOLINT(hicpp-use-auto,modernize-use-auto)
  252. if ((i->second - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  253. m_localControllerAuthorizations.erase(i++);
  254. else ++i;
  255. }
  256. m_localControllerAuthorizations_l.unlock();
  257. RR->topology->doPeriodicTasks(tPtr, now);
  258. RR->sa->clean(now);
  259. }
  260. *nextBackgroundTaskDeadline = now + ZT_TIMER_TASK_INTERVAL;
  261. } catch (...) {
  262. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  263. }
  264. return ZT_RESULT_OK;
  265. }
  266. ZT_ResultCode Node::join(
  267. uint64_t nwid,
  268. const ZT_Fingerprint *controllerFingerprint,
  269. void *uptr,
  270. void *tptr)
  271. {
  272. Fingerprint fp;
  273. if (controllerFingerprint) {
  274. fp = *controllerFingerprint;
  275. ZT_SPEW("joining network %.16llx with fingerprint %s", nwid, fp.toString().c_str());
  276. } else {
  277. ZT_SPEW("joining network %.16llx", nwid);
  278. }
  279. RWMutex::Lock l(m_networks_l);
  280. SharedPtr< Network > &nw = m_networks[nwid];
  281. if (nw)
  282. return ZT_RESULT_OK;
  283. nw.set(new Network(RR, tptr, nwid, fp, uptr, nullptr));
  284. return ZT_RESULT_OK;
  285. }
  286. ZT_ResultCode Node::leave(
  287. uint64_t nwid,
  288. void **uptr,
  289. void *tptr)
  290. {
  291. ZT_SPEW("leaving network %.16llx", nwid);
  292. ZT_VirtualNetworkConfig ctmp;
  293. m_networks_l.lock();
  294. Map< uint64_t, SharedPtr< Network > >::iterator nwi(m_networks.find(nwid)); // NOLINT(hicpp-use-auto,modernize-use-auto)
  295. if (nwi == m_networks.end()) {
  296. m_networks_l.unlock();
  297. return ZT_RESULT_OK;
  298. }
  299. SharedPtr< Network > nw(nwi->second);
  300. m_networks.erase(nwi);
  301. m_networks_l.unlock();
  302. if (uptr)
  303. *uptr = *nw->userPtr();
  304. nw->externalConfig(&ctmp);
  305. RR->node->configureVirtualNetworkPort(tptr, nwid, uptr, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY, &ctmp);
  306. nw->destroy();
  307. nw.zero();
  308. uint64_t tmp[2];
  309. tmp[0] = nwid;
  310. tmp[1] = 0;
  311. RR->node->stateObjectDelete(tptr, ZT_STATE_OBJECT_NETWORK_CONFIG, tmp);
  312. return ZT_RESULT_OK;
  313. }
  314. ZT_ResultCode Node::multicastSubscribe(
  315. void *tPtr,
  316. uint64_t nwid,
  317. uint64_t multicastGroup,
  318. unsigned long multicastAdi)
  319. {
  320. ZT_SPEW("multicast subscribe to %s:%lu", MAC(multicastGroup).toString().c_str(), multicastAdi);
  321. const SharedPtr< Network > nw(this->network(nwid));
  322. if (nw) {
  323. nw->multicastSubscribe(tPtr, MulticastGroup(MAC(multicastGroup), (uint32_t)(multicastAdi & 0xffffffff)));
  324. return ZT_RESULT_OK;
  325. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  326. }
  327. ZT_ResultCode Node::multicastUnsubscribe(
  328. uint64_t nwid,
  329. uint64_t multicastGroup,
  330. unsigned long multicastAdi)
  331. {
  332. ZT_SPEW("multicast unsubscribe from %s:%lu", MAC(multicastGroup).toString().c_str(), multicastAdi);
  333. const SharedPtr< Network > nw(this->network(nwid));
  334. if (nw) {
  335. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup), (uint32_t)(multicastAdi & 0xffffffff)));
  336. return ZT_RESULT_OK;
  337. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  338. }
  339. uint64_t Node::address() const
  340. {
  341. return RR->identity.address().toInt();
  342. }
  343. void Node::status(ZT_NodeStatus *status) const
  344. {
  345. status->address = RR->identity.address().toInt();
  346. status->identity = reinterpret_cast<const ZT_Identity *>(&RR->identity);
  347. status->publicIdentity = RR->publicIdentityStr;
  348. status->secretIdentity = RR->secretIdentityStr;
  349. status->online = m_online ? 1 : 0;
  350. }
  351. ZT_PeerList *Node::peers() const
  352. {
  353. Vector< SharedPtr< Peer > > peers, rootPeers;
  354. RR->topology->allPeers(peers, rootPeers);
  355. std::sort(peers.begin(), peers.end(), _sortPeerPtrsByAddress());
  356. const unsigned int bufSize =
  357. sizeof(ZT_PeerList) +
  358. (sizeof(ZT_Peer) * peers.size()) +
  359. ((sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size()) +
  360. (sizeof(Identity) * peers.size()) +
  361. (ZT_LOCATOR_MARSHAL_SIZE_MAX * peers.size());
  362. char *buf = (char *)malloc(bufSize);
  363. if (!buf)
  364. return nullptr;
  365. Utils::zero(buf, bufSize);
  366. ZT_PeerList *pl = reinterpret_cast<ZT_PeerList *>(buf);
  367. buf += sizeof(ZT_PeerList);
  368. pl->peers = reinterpret_cast<ZT_Peer *>(buf);
  369. buf += sizeof(ZT_Peer) * peers.size();
  370. ZT_Path *peerPath = reinterpret_cast<ZT_Path *>(buf);
  371. buf += (sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size();
  372. Identity *identities = reinterpret_cast<Identity *>(buf);
  373. buf += sizeof(Identity) * peers.size();
  374. uint8_t *locatorBuf = reinterpret_cast<uint8_t *>(buf);
  375. const int64_t now = m_now;
  376. pl->peerCount = 0;
  377. for (Vector< SharedPtr< Peer > >::iterator pi(peers.begin()); pi != peers.end(); ++pi) {
  378. ZT_Peer *const p = pl->peers + pl->peerCount;
  379. p->address = (*pi)->address().toInt();
  380. identities[pl->peerCount] = (*pi)->identity(); // need to make a copy in case peer gets deleted
  381. p->identity = identities + pl->peerCount;
  382. p->fingerprint.address = p->address;
  383. Utils::copy< ZT_FINGERPRINT_HASH_SIZE >(p->fingerprint.hash, (*pi)->identity().fingerprint().hash);
  384. if ((*pi)->remoteVersionKnown()) {
  385. p->versionMajor = (int)(*pi)->remoteVersionMajor();
  386. p->versionMinor = (int)(*pi)->remoteVersionMinor();
  387. p->versionRev = (int)(*pi)->remoteVersionRevision();
  388. } else {
  389. p->versionMajor = -1;
  390. p->versionMinor = -1;
  391. p->versionRev = -1;
  392. }
  393. p->latency = (*pi)->latency();
  394. p->root = (std::find(rootPeers.begin(), rootPeers.end(), *pi) != rootPeers.end()) ? 1 : 0;
  395. p->networkCount = 0;
  396. // TODO: enumerate network memberships
  397. Vector< SharedPtr< Path > > paths;
  398. (*pi)->getAllPaths(paths);
  399. p->pathCount = (unsigned int)paths.size();
  400. p->paths = peerPath;
  401. for (Vector< SharedPtr< Path > >::iterator path(paths.begin()); path != paths.end(); ++path) {
  402. ZT_Path *const pp = peerPath++;
  403. pp->endpoint.type = ZT_ENDPOINT_TYPE_IP_UDP; // only type supported right now
  404. Utils::copy< sizeof(sockaddr_storage) >(&pp->endpoint.value.ss, &((*path)->address().as.ss));
  405. pp->lastSend = (*path)->lastOut();
  406. pp->lastReceive = (*path)->lastIn();
  407. pp->alive = (*path)->alive(now) ? 1 : 0;
  408. pp->preferred = (p->pathCount == 0) ? 1 : 0;
  409. }
  410. const SharedPtr< const Locator > loc((*pi)->locator());
  411. if (loc) {
  412. const int ls = loc->marshal(locatorBuf);
  413. if (ls > 0) {
  414. p->locatorSize = (unsigned int)ls;
  415. p->locator = locatorBuf;
  416. locatorBuf += ls;
  417. }
  418. }
  419. ++pl->peerCount;
  420. }
  421. return pl;
  422. }
  423. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  424. {
  425. SharedPtr< Network > nw(network(nwid));
  426. if (nw) {
  427. ZT_VirtualNetworkConfig *const nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  428. nw->externalConfig(nc);
  429. return nc;
  430. }
  431. return nullptr;
  432. }
  433. ZT_VirtualNetworkList *Node::networks() const
  434. {
  435. RWMutex::RLock l(m_networks_l);
  436. char *const buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * m_networks.size()));
  437. if (!buf)
  438. return nullptr;
  439. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf; // NOLINT(modernize-use-auto,hicpp-use-auto)
  440. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  441. nl->networkCount = 0;
  442. 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)
  443. i->second->externalConfig(&(nl->networks[nl->networkCount++]));
  444. return nl;
  445. }
  446. void Node::setNetworkUserPtr(
  447. uint64_t nwid,
  448. void *ptr)
  449. {
  450. SharedPtr< Network > nw(network(nwid));
  451. if (nw)
  452. *(nw->userPtr()) = ptr;
  453. }
  454. void Node::setInterfaceAddresses(
  455. const ZT_InterfaceAddress *addrs,
  456. unsigned int addrCount)
  457. {
  458. Mutex::Lock _l(m_localInterfaceAddresses_m);
  459. m_localInterfaceAddresses.clear();
  460. for (unsigned int i = 0; i < addrCount; ++i) {
  461. bool dupe = false;
  462. for (unsigned int j = 0; j < i; ++j) {
  463. if (*(reinterpret_cast<const InetAddress *>(&addrs[j].address)) == *(reinterpret_cast<const InetAddress *>(&addrs[i].address))) {
  464. dupe = true;
  465. break;
  466. }
  467. }
  468. if (!dupe)
  469. m_localInterfaceAddresses.push_back(addrs[i]);
  470. }
  471. }
  472. ZT_ResultCode Node::addPeer(
  473. void *tptr,
  474. const ZT_Identity *identity)
  475. {
  476. if (!identity)
  477. return ZT_RESULT_ERROR_BAD_PARAMETER;
  478. SharedPtr< Peer > peer(RR->topology->peer(tptr, reinterpret_cast<const Identity *>(identity)->address()));
  479. if (!peer) {
  480. peer.set(new Peer(RR));
  481. peer->init(*reinterpret_cast<const Identity *>(identity));
  482. peer = RR->topology->add(tptr, peer);
  483. }
  484. return (peer->identity() == *reinterpret_cast<const Identity *>(identity)) ? ZT_RESULT_OK : ZT_RESULT_ERROR_COLLIDING_OBJECT;
  485. }
  486. int Node::tryPeer(
  487. void *tptr,
  488. const ZT_Fingerprint *fp,
  489. const ZT_Endpoint *endpoint,
  490. int retries)
  491. {
  492. if ((!fp) || (!endpoint))
  493. return 0;
  494. const SharedPtr< Peer > peer(RR->topology->peer(tptr, fp->address, true));
  495. if ((peer) && (peer->identity().fingerprint().bestSpecificityEquals(*fp))) {
  496. peer->contact(tptr, m_now, Endpoint(*endpoint), std::min(retries, 1));
  497. return 1;
  498. }
  499. return 0;
  500. }
  501. int Node::sendUserMessage(
  502. void *tptr,
  503. uint64_t dest,
  504. uint64_t typeId,
  505. const void *data,
  506. unsigned int len)
  507. {
  508. try {
  509. if (RR->identity.address().toInt() != dest) {
  510. // TODO
  511. /*
  512. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  513. outp.append(typeId);
  514. outp.append(data,len);
  515. outp.compress();
  516. RR->sw->send(tptr,outp,true);
  517. */
  518. return 1;
  519. }
  520. } catch (...) {}
  521. return 0;
  522. }
  523. void Node::setController(void *networkControllerInstance)
  524. {
  525. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  526. if (networkControllerInstance)
  527. RR->localNetworkController->init(RR->identity, this);
  528. }
  529. // Methods used only within the core ----------------------------------------------------------------------------------
  530. Vector< uint8_t > Node::stateObjectGet(void *const tPtr, ZT_StateObjectType type, const uint64_t *id)
  531. {
  532. Vector< uint8_t > r;
  533. if (m_cb.stateGetFunction) {
  534. void *data = nullptr;
  535. void (*freeFunc)(void *) = nullptr;
  536. int l = m_cb.stateGetFunction(
  537. reinterpret_cast<ZT_Node *>(this),
  538. m_uPtr,
  539. tPtr,
  540. type,
  541. id,
  542. &data,
  543. &freeFunc);
  544. if ((l > 0) && (data) && (freeFunc)) {
  545. r.assign(reinterpret_cast<const uint8_t *>(data), reinterpret_cast<const uint8_t *>(data) + l);
  546. freeFunc(data);
  547. }
  548. }
  549. return r;
  550. }
  551. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr, const Identity &id, const int64_t localSocket, const InetAddress &remoteAddress)
  552. {
  553. {
  554. RWMutex::RLock l(m_networks_l);
  555. 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)
  556. for (unsigned int k = 0, j = i->second->config().staticIpCount; k < j; ++k) {
  557. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  558. return false;
  559. }
  560. }
  561. }
  562. if (m_cb.pathCheckFunction) {
  563. return (m_cb.pathCheckFunction(
  564. reinterpret_cast<ZT_Node *>(this),
  565. m_uPtr,
  566. tPtr,
  567. id.address().toInt(),
  568. (const ZT_Identity *)&id,
  569. localSocket,
  570. reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  571. }
  572. return true;
  573. }
  574. bool Node::externalPathLookup(void *tPtr, const Identity &id, int family, InetAddress &addr)
  575. {
  576. if (m_cb.pathLookupFunction) {
  577. return (m_cb.pathLookupFunction(
  578. reinterpret_cast<ZT_Node *>(this),
  579. m_uPtr,
  580. tPtr,
  581. id.address().toInt(),
  582. reinterpret_cast<const ZT_Identity *>(&id),
  583. family,
  584. reinterpret_cast<sockaddr_storage *>(&addr)) == ZT_RESULT_OK);
  585. }
  586. return false;
  587. }
  588. bool Node::localControllerHasAuthorized(const int64_t now, const uint64_t nwid, const Address &addr) const
  589. {
  590. m_localControllerAuthorizations_l.lock();
  591. Map<Node::p_LocalControllerAuth, int64_t>::const_iterator i(m_localControllerAuthorizations.find(p_LocalControllerAuth(nwid, addr)));
  592. const int64_t at = (i == m_localControllerAuthorizations.end()) ? -1LL : i->second;
  593. m_localControllerAuthorizations_l.unlock();
  594. if (at > 0)
  595. return ((now - at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  596. return false;
  597. }
  598. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  599. void Node::ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address &destination, const NetworkConfig &nc, bool sendLegacyFormatConfig)
  600. {
  601. m_localControllerAuthorizations_l.lock();
  602. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  603. m_localControllerAuthorizations_l.unlock();
  604. if (destination == RR->identity.address()) {
  605. SharedPtr< Network > n(network(nwid));
  606. if (!n)
  607. return;
  608. n->setConfiguration((void *)0, nc, true);
  609. } else {
  610. Dictionary dconf;
  611. if (nc.toDictionary(dconf)) {
  612. uint64_t configUpdateId = Utils::random();
  613. if (!configUpdateId)
  614. ++configUpdateId;
  615. Vector< uint8_t > ddata;
  616. dconf.encode(ddata);
  617. // TODO
  618. /*
  619. unsigned int chunkIndex = 0;
  620. while (chunkIndex < totalSize) {
  621. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  622. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  623. if (requestPacketId) {
  624. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  625. outp.append(requestPacketId);
  626. }
  627. const unsigned int sigStart = outp.size();
  628. outp.append(nwid);
  629. outp.append((uint16_t)chunkLen);
  630. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  631. outp.append((uint8_t)0); // no flags
  632. outp.append((uint64_t)configUpdateId);
  633. outp.append((uint32_t)totalSize);
  634. outp.append((uint32_t)chunkIndex);
  635. uint8_t sig[256];
  636. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  637. outp.append((uint8_t)1);
  638. outp.append((uint16_t)siglen);
  639. outp.append(sig,siglen);
  640. outp.compress();
  641. RR->sw->send((void *)0,outp,true);
  642. chunkIndex += chunkLen;
  643. }
  644. */
  645. }
  646. }
  647. }
  648. void Node::ncSendRevocation(const Address &destination, const RevocationCredential &rev)
  649. {
  650. if (destination == RR->identity.address()) {
  651. SharedPtr< Network > n(network(rev.networkId()));
  652. if (!n) return;
  653. n->addCredential(nullptr, RR->identity, rev);
  654. } else {
  655. // TODO
  656. /*
  657. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  658. outp.append((uint8_t)0x00);
  659. outp.append((uint16_t)0);
  660. outp.append((uint16_t)0);
  661. outp.append((uint16_t)1);
  662. rev.serialize(outp);
  663. outp.append((uint16_t)0);
  664. RR->sw->send((void *)0,outp,true);
  665. */
  666. }
  667. }
  668. void Node::ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address &destination, NetworkController::ErrorCode errorCode)
  669. {
  670. if (destination == RR->identity.address()) {
  671. SharedPtr< Network > n(network(nwid));
  672. if (!n) return;
  673. switch (errorCode) {
  674. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  675. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  676. n->setNotFound();
  677. break;
  678. case NetworkController::NC_ERROR_ACCESS_DENIED:
  679. n->setAccessDenied();
  680. break;
  681. default:
  682. break;
  683. }
  684. } else if (requestPacketId) {
  685. // TODO
  686. /*
  687. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  688. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  689. outp.append(requestPacketId);
  690. switch(errorCode) {
  691. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  692. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  693. default:
  694. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  695. break;
  696. case NetworkController::NC_ERROR_ACCESS_DENIED:
  697. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  698. break;
  699. }
  700. outp.append(nwid);
  701. RR->sw->send((void *)0,outp,true);
  702. */
  703. } // else we can't send an ERROR() in response to nothing, so discard
  704. }
  705. } // namespace ZeroTier
  706. // C API --------------------------------------------------------------------------------------------------------------
  707. extern "C" {
  708. // These macros make the idiom of passing buffers to outside code via the API work properly even
  709. // if the first address of Buf does not overlap with its data field, since the C++ standard does
  710. // not absolutely guarantee this.
  711. #define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) ))
  712. #define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
  713. void *ZT_getBuffer()
  714. {
  715. // When external code requests a Buf, grab one from the pool (or freshly allocated)
  716. // and return it with its reference count left at zero. It's the responsibility of
  717. // external code to bring it back via freeBuffer() or one of the processX() calls.
  718. // When this occurs it's either sent back to the pool with Buf's delete operator or
  719. // wrapped in a SharedPtr<> to be passed into the core.
  720. try {
  721. return _ZT_BUFTOPTR(new ZeroTier::Buf());
  722. } catch (...) {
  723. return nullptr; // can only happen on out of memory condition
  724. }
  725. }
  726. void ZT_freeBuffer(void *b)
  727. {
  728. if (b)
  729. delete _ZT_PTRTOBUF(b);
  730. }
  731. void ZT_freeQueryResult(void *qr)
  732. {
  733. if (qr)
  734. free(qr);
  735. }
  736. enum ZT_ResultCode ZT_Node_new(ZT_Node **node, void *uptr, void *tptr, const struct ZT_Node_Callbacks *callbacks, int64_t now)
  737. {
  738. *node = (ZT_Node *)0;
  739. try {
  740. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr, tptr, callbacks, now));
  741. return ZT_RESULT_OK;
  742. } catch (std::bad_alloc &exc) {
  743. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  744. } catch (std::runtime_error &exc) {
  745. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  746. } catch (...) {
  747. return ZT_RESULT_ERROR_INTERNAL;
  748. }
  749. }
  750. void ZT_Node_delete(ZT_Node *node, void *tPtr)
  751. {
  752. try {
  753. reinterpret_cast<ZeroTier::Node *>(node)->shutdown(tPtr);
  754. delete (reinterpret_cast<ZeroTier::Node *>(node));
  755. } catch (...) {}
  756. }
  757. enum ZT_ResultCode ZT_Node_processWirePacket(
  758. ZT_Node *node,
  759. void *tptr,
  760. int64_t now,
  761. int64_t localSocket,
  762. const struct sockaddr_storage *remoteAddress,
  763. const void *packetData,
  764. unsigned int packetLength,
  765. int isZtBuffer,
  766. volatile int64_t *nextBackgroundTaskDeadline)
  767. {
  768. try {
  769. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData, packetLength & ZT_BUF_MEM_MASK));
  770. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline);
  771. } catch (std::bad_alloc &exc) {
  772. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  773. } catch (...) {
  774. // "OK" since invalid packets are simply dropped, but the system is still up.
  775. // We should never make it here, but if we did that would be the interpretation.
  776. return ZT_RESULT_OK;
  777. }
  778. }
  779. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  780. ZT_Node *node,
  781. void *tptr,
  782. int64_t now,
  783. uint64_t nwid,
  784. uint64_t sourceMac,
  785. uint64_t destMac,
  786. unsigned int etherType,
  787. unsigned int vlanId,
  788. const void *frameData,
  789. unsigned int frameLength,
  790. int isZtBuffer,
  791. volatile int64_t *nextBackgroundTaskDeadline)
  792. {
  793. try {
  794. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData, frameLength & ZT_BUF_MEM_MASK));
  795. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline);
  796. } catch (std::bad_alloc &exc) {
  797. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  798. } catch (...) {
  799. return ZT_RESULT_ERROR_INTERNAL;
  800. }
  801. }
  802. enum ZT_ResultCode ZT_Node_processHTTPResponse(
  803. ZT_Node *node,
  804. void *tptr,
  805. int64_t now,
  806. void *requestId,
  807. int responseCode,
  808. const char **headerNames,
  809. const char **headerValues,
  810. const void *body,
  811. unsigned int bodySize,
  812. unsigned int flags)
  813. {
  814. try {
  815. return reinterpret_cast<ZeroTier::Node *>(node)->processHTTPResponse(tptr, now, requestId, responseCode, headerNames, headerValues, body, bodySize, flags);
  816. } catch (std::bad_alloc &exc) {
  817. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  818. } catch (...) {
  819. return ZT_RESULT_ERROR_INTERNAL;
  820. }
  821. }
  822. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node, void *tptr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline)
  823. {
  824. try {
  825. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr, now, nextBackgroundTaskDeadline);
  826. } catch (std::bad_alloc &exc) {
  827. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  828. } catch (...) {
  829. return ZT_RESULT_ERROR_INTERNAL;
  830. }
  831. }
  832. enum ZT_ResultCode ZT_Node_join(ZT_Node *node, uint64_t nwid, const ZT_Fingerprint *controllerFingerprint, void *uptr, void *tptr)
  833. {
  834. try {
  835. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid, controllerFingerprint, uptr, tptr);
  836. } catch (std::bad_alloc &exc) {
  837. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  838. } catch (...) {
  839. return ZT_RESULT_ERROR_INTERNAL;
  840. }
  841. }
  842. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node, uint64_t nwid, void **uptr, void *tptr)
  843. {
  844. try {
  845. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid, uptr, tptr);
  846. } catch (std::bad_alloc &exc) {
  847. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  848. } catch (...) {
  849. return ZT_RESULT_ERROR_INTERNAL;
  850. }
  851. }
  852. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node, void *tptr, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  853. {
  854. try {
  855. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr, nwid, multicastGroup, multicastAdi);
  856. } catch (std::bad_alloc &exc) {
  857. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  858. } catch (...) {
  859. return ZT_RESULT_ERROR_INTERNAL;
  860. }
  861. }
  862. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  863. {
  864. try {
  865. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid, multicastGroup, multicastAdi);
  866. } catch (std::bad_alloc &exc) {
  867. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  868. } catch (...) {
  869. return ZT_RESULT_ERROR_INTERNAL;
  870. }
  871. }
  872. uint64_t ZT_Node_address(ZT_Node *node)
  873. {
  874. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  875. }
  876. const ZT_Identity *ZT_Node_identity(ZT_Node *node)
  877. {
  878. return (const ZT_Identity *)(&(reinterpret_cast<ZeroTier::Node *>(node)->identity()));
  879. }
  880. void ZT_Node_status(ZT_Node *node, ZT_NodeStatus *status)
  881. {
  882. try {
  883. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  884. } catch (...) {}
  885. }
  886. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  887. {
  888. try {
  889. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  890. } catch (...) {
  891. return (ZT_PeerList *)0;
  892. }
  893. }
  894. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node, uint64_t nwid)
  895. {
  896. try {
  897. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  898. } catch (...) {
  899. return (ZT_VirtualNetworkConfig *)0;
  900. }
  901. }
  902. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  903. {
  904. try {
  905. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  906. } catch (...) {
  907. return (ZT_VirtualNetworkList *)0;
  908. }
  909. }
  910. int ZT_Node_tryPeer(
  911. ZT_Node *node,
  912. void *tptr,
  913. const ZT_Fingerprint *fp,
  914. const ZT_Endpoint *endpoint,
  915. int retries)
  916. {
  917. try {
  918. return reinterpret_cast<ZeroTier::Node *>(node)->tryPeer(tptr, fp, endpoint, retries);
  919. } catch (...) {
  920. return 0;
  921. }
  922. }
  923. void ZT_Node_setNetworkUserPtr(ZT_Node *node, uint64_t nwid, void *ptr)
  924. {
  925. try {
  926. reinterpret_cast<ZeroTier::Node *>(node)->setNetworkUserPtr(nwid, ptr);
  927. } catch (...) {}
  928. }
  929. void ZT_Node_setInterfaceAddresses(ZT_Node *node, const ZT_InterfaceAddress *addrs, unsigned int addrCount)
  930. {
  931. try {
  932. reinterpret_cast<ZeroTier::Node *>(node)->setInterfaceAddresses(addrs, addrCount);
  933. } catch (...) {}
  934. }
  935. enum ZT_ResultCode ZT_Node_addPeer(
  936. ZT_Node *node,
  937. void *tptr,
  938. const ZT_Identity *id)
  939. {
  940. try {
  941. return reinterpret_cast<ZeroTier::Node *>(node)->addPeer(tptr, id);
  942. } catch (...) {
  943. return ZT_RESULT_ERROR_INTERNAL;
  944. }
  945. }
  946. int ZT_Node_sendUserMessage(ZT_Node *node, void *tptr, uint64_t dest, uint64_t typeId, const void *data, unsigned int len)
  947. {
  948. try {
  949. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr, dest, typeId, data, len);
  950. } catch (...) {
  951. return 0;
  952. }
  953. }
  954. void ZT_Node_setController(ZT_Node *node, void *networkControllerInstance)
  955. {
  956. try {
  957. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  958. } catch (...) {}
  959. }
  960. void ZT_version(int *major, int *minor, int *revision, int *build)
  961. {
  962. if (major)
  963. *major = ZEROTIER_VERSION_MAJOR;
  964. if (minor)
  965. *minor = ZEROTIER_VERSION_MINOR;
  966. if (revision)
  967. *revision = ZEROTIER_VERSION_REVISION;
  968. if (build)
  969. *build = ZEROTIER_VERSION_BUILD;
  970. }
  971. } // extern "C"