Node.cpp 31 KB

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