Node.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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)
  309. {
  310. return (RR->topology->addRoot(tPtr, *reinterpret_cast<const Identity *>(id))) ? ZT_RESULT_OK : ZT_RESULT_ERROR_BAD_PARAMETER;
  311. }
  312. ZT_ResultCode Node::removeRoot(void *tPtr, const uint64_t address)
  313. {
  314. RR->topology->removeRoot(tPtr, Address(address));
  315. return ZT_RESULT_OK;
  316. }
  317. uint64_t Node::address() const
  318. {
  319. return RR->identity.address().toInt();
  320. }
  321. void Node::status(ZT_NodeStatus *status) const
  322. {
  323. status->address = RR->identity.address().toInt();
  324. status->identity = reinterpret_cast<const ZT_Identity *>(&RR->identity);
  325. status->publicIdentity = RR->publicIdentityStr;
  326. status->secretIdentity = RR->secretIdentityStr;
  327. status->online = m_online ? 1 : 0;
  328. }
  329. ZT_PeerList *Node::peers() const
  330. {
  331. Vector<SharedPtr<Peer> > peers;
  332. RR->topology->getAllPeers(peers);
  333. std::sort(peers.begin(), peers.end(), _sortPeerPtrsByAddress());
  334. const unsigned int bufSize =
  335. sizeof(ZT_PeerList) +
  336. (sizeof(ZT_Peer) * peers.size()) +
  337. ((sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size()) +
  338. (sizeof(Identity) * peers.size()) +
  339. (ZT_LOCATOR_MARSHAL_SIZE_MAX * peers.size());
  340. char *buf = (char *)malloc(bufSize);
  341. if (!buf)
  342. return nullptr;
  343. Utils::zero(buf, bufSize);
  344. ZT_PeerList *pl = reinterpret_cast<ZT_PeerList *>(buf);
  345. buf += sizeof(ZT_PeerList);
  346. pl->peers = reinterpret_cast<ZT_Peer *>(buf);
  347. buf += sizeof(ZT_Peer) * peers.size();
  348. ZT_Path *peerPath = reinterpret_cast<ZT_Path *>(buf);
  349. buf += (sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size();
  350. Identity *identities = reinterpret_cast<Identity *>(buf);
  351. buf += sizeof(Identity) * peers.size();
  352. uint8_t *locatorBuf = reinterpret_cast<uint8_t *>(buf);
  353. const int64_t now = m_now;
  354. pl->peerCount = 0;
  355. for (Vector<SharedPtr<Peer> >::iterator pi(peers.begin());pi != peers.end();++pi) {
  356. ZT_Peer *const p = pl->peers + pl->peerCount;
  357. p->address = (*pi)->address().toInt();
  358. identities[pl->peerCount] = (*pi)->identity(); // need to make a copy in case peer gets deleted
  359. p->identity = identities + pl->peerCount;
  360. p->fingerprint.address = p->address;
  361. Utils::copy<ZT_FINGERPRINT_HASH_SIZE>(p->fingerprint.hash, (*pi)->identity().fingerprint().hash);
  362. if ((*pi)->remoteVersionKnown()) {
  363. p->versionMajor = (int)(*pi)->remoteVersionMajor();
  364. p->versionMinor = (int)(*pi)->remoteVersionMinor();
  365. p->versionRev = (int)(*pi)->remoteVersionRevision();
  366. } else {
  367. p->versionMajor = -1;
  368. p->versionMinor = -1;
  369. p->versionRev = -1;
  370. }
  371. p->latency = (*pi)->latency();
  372. p->root = RR->topology->isRoot((*pi)->identity()) ? 1 : 0;
  373. p->networkCount = 0;
  374. // TODO: enumerate network memberships
  375. Vector< SharedPtr<Path> > paths;
  376. (*pi)->getAllPaths(paths);
  377. p->pathCount = (unsigned int)paths.size();
  378. p->paths = peerPath;
  379. for (Vector<SharedPtr<Path> >::iterator path(paths.begin());path != paths.end();++path) {
  380. ZT_Path *const pp = peerPath++;
  381. pp->endpoint.type = ZT_ENDPOINT_TYPE_IP_UDP; // only type supported right now
  382. Utils::copy<sizeof(sockaddr_storage)>(&pp->endpoint.value.ss, &((*path)->address().as.ss));
  383. pp->lastSend = (*path)->lastOut();
  384. pp->lastReceive = (*path)->lastIn();
  385. pp->alive = (*path)->alive(now) ? 1 : 0;
  386. pp->preferred = (p->pathCount == 0) ? 1 : 0;
  387. }
  388. const SharedPtr<const Locator> loc((*pi)->locator());
  389. if (loc) {
  390. const int ls = loc->marshal(locatorBuf);
  391. if (ls > 0) {
  392. p->locatorSize = (unsigned int)ls;
  393. p->locator = locatorBuf;
  394. locatorBuf += ls;
  395. }
  396. }
  397. ++pl->peerCount;
  398. }
  399. return pl;
  400. }
  401. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  402. {
  403. SharedPtr<Network> nw(network(nwid));
  404. if (nw) {
  405. ZT_VirtualNetworkConfig *const nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  406. nw->externalConfig(nc);
  407. return nc;
  408. }
  409. return nullptr;
  410. }
  411. ZT_VirtualNetworkList *Node::networks() const
  412. {
  413. RWMutex::RLock l(m_networks_l);
  414. char *const buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * m_networks.size()));
  415. if (!buf)
  416. return nullptr;
  417. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf; // NOLINT(modernize-use-auto,hicpp-use-auto)
  418. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  419. nl->networkCount = 0;
  420. 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)
  421. i->second->externalConfig(&(nl->networks[nl->networkCount++]));
  422. return nl;
  423. }
  424. void Node::setNetworkUserPtr(uint64_t nwid, void *ptr)
  425. {
  426. SharedPtr<Network> nw(network(nwid));
  427. if (nw)
  428. *(nw->userPtr()) = ptr;
  429. }
  430. void Node::setInterfaceAddresses(const ZT_InterfaceAddress *addrs, unsigned int addrCount)
  431. {
  432. Mutex::Lock _l(m_localInterfaceAddresses_m);
  433. m_localInterfaceAddresses.clear();
  434. for (unsigned int i = 0;i < addrCount;++i) {
  435. bool dupe = false;
  436. for (unsigned int j = 0;j < i;++j) {
  437. if (*(reinterpret_cast<const InetAddress *>(&addrs[j].address)) == *(reinterpret_cast<const InetAddress *>(&addrs[i].address))) {
  438. dupe = true;
  439. break;
  440. }
  441. }
  442. if (!dupe)
  443. m_localInterfaceAddresses.push_back(addrs[i]);
  444. }
  445. }
  446. int Node::sendUserMessage(void *tptr, uint64_t dest, uint64_t typeId, const void *data, unsigned int len)
  447. {
  448. try {
  449. if (RR->identity.address().toInt() != dest) {
  450. // TODO
  451. /*
  452. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  453. outp.append(typeId);
  454. outp.append(data,len);
  455. outp.compress();
  456. RR->sw->send(tptr,outp,true);
  457. */
  458. return 1;
  459. }
  460. } catch (...) {}
  461. return 0;
  462. }
  463. void Node::setController(void *networkControllerInstance)
  464. {
  465. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  466. if (networkControllerInstance)
  467. RR->localNetworkController->init(RR->identity, this);
  468. }
  469. // Methods used only within the core ----------------------------------------------------------------------------------
  470. Vector<uint8_t> Node::stateObjectGet(void *const tPtr, ZT_StateObjectType type, const uint64_t id[2])
  471. {
  472. Vector<uint8_t> r;
  473. if (m_cb.stateGetFunction) {
  474. void *data = nullptr;
  475. void (*freeFunc)(void *) = nullptr;
  476. int l = m_cb.stateGetFunction(
  477. reinterpret_cast<ZT_Node *>(this),
  478. m_uPtr,
  479. tPtr,
  480. type,
  481. id,
  482. &data,
  483. &freeFunc);
  484. if ((l > 0) && (data) && (freeFunc)) {
  485. r.assign(reinterpret_cast<const uint8_t *>(data), reinterpret_cast<const uint8_t *>(data) + l);
  486. freeFunc(data);
  487. }
  488. }
  489. return r;
  490. }
  491. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr, const Identity &id, const int64_t localSocket, const InetAddress &remoteAddress)
  492. {
  493. {
  494. RWMutex::RLock l(m_networks_l);
  495. 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)
  496. for (unsigned int k = 0, j = i->second->config().staticIpCount;k < j;++k) {
  497. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  498. return false;
  499. }
  500. }
  501. }
  502. if (m_cb.pathCheckFunction) {
  503. return (m_cb.pathCheckFunction(
  504. reinterpret_cast<ZT_Node *>(this),
  505. m_uPtr,
  506. tPtr,
  507. id.address().toInt(),
  508. (const ZT_Identity *)&id,
  509. localSocket,
  510. reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  511. }
  512. return true;
  513. }
  514. bool Node::externalPathLookup(void *tPtr, const Identity &id, int family, InetAddress &addr)
  515. {
  516. if (m_cb.pathLookupFunction) {
  517. return (m_cb.pathLookupFunction(
  518. reinterpret_cast<ZT_Node *>(this),
  519. m_uPtr,
  520. tPtr,
  521. id.address().toInt(),
  522. reinterpret_cast<const ZT_Identity *>(&id),
  523. family,
  524. reinterpret_cast<sockaddr_storage *>(&addr)) == ZT_RESULT_OK);
  525. }
  526. return false;
  527. }
  528. bool Node::localControllerHasAuthorized(const int64_t now, const uint64_t nwid, const Address &addr) const
  529. {
  530. m_localControllerAuthorizations_l.lock();
  531. const int64_t *const at = m_localControllerAuthorizations.get(p_LocalControllerAuth(nwid, addr));
  532. m_localControllerAuthorizations_l.unlock();
  533. if (at)
  534. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  535. return false;
  536. }
  537. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  538. void Node::ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address &destination, const NetworkConfig &nc, bool sendLegacyFormatConfig)
  539. {
  540. m_localControllerAuthorizations_l.lock();
  541. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  542. m_localControllerAuthorizations_l.unlock();
  543. if (destination == RR->identity.address()) {
  544. SharedPtr<Network> n(network(nwid));
  545. if (!n)
  546. return;
  547. n->setConfiguration((void *)0, nc, true);
  548. } else {
  549. Dictionary dconf;
  550. if (nc.toDictionary(dconf)) {
  551. uint64_t configUpdateId = Utils::random();
  552. if (!configUpdateId)
  553. ++configUpdateId;
  554. Vector<uint8_t> ddata;
  555. dconf.encode(ddata);
  556. // TODO
  557. /*
  558. unsigned int chunkIndex = 0;
  559. while (chunkIndex < totalSize) {
  560. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  561. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  562. if (requestPacketId) {
  563. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  564. outp.append(requestPacketId);
  565. }
  566. const unsigned int sigStart = outp.size();
  567. outp.append(nwid);
  568. outp.append((uint16_t)chunkLen);
  569. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  570. outp.append((uint8_t)0); // no flags
  571. outp.append((uint64_t)configUpdateId);
  572. outp.append((uint32_t)totalSize);
  573. outp.append((uint32_t)chunkIndex);
  574. uint8_t sig[256];
  575. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  576. outp.append((uint8_t)1);
  577. outp.append((uint16_t)siglen);
  578. outp.append(sig,siglen);
  579. outp.compress();
  580. RR->sw->send((void *)0,outp,true);
  581. chunkIndex += chunkLen;
  582. }
  583. */
  584. }
  585. }
  586. }
  587. void Node::ncSendRevocation(const Address &destination, const Revocation &rev)
  588. {
  589. if (destination == RR->identity.address()) {
  590. SharedPtr<Network> n(network(rev.networkId()));
  591. if (!n) return;
  592. n->addCredential(nullptr, RR->identity, rev);
  593. } else {
  594. // TODO
  595. /*
  596. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  597. outp.append((uint8_t)0x00);
  598. outp.append((uint16_t)0);
  599. outp.append((uint16_t)0);
  600. outp.append((uint16_t)1);
  601. rev.serialize(outp);
  602. outp.append((uint16_t)0);
  603. RR->sw->send((void *)0,outp,true);
  604. */
  605. }
  606. }
  607. void Node::ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address &destination, NetworkController::ErrorCode errorCode)
  608. {
  609. if (destination == RR->identity.address()) {
  610. SharedPtr<Network> n(network(nwid));
  611. if (!n) return;
  612. switch (errorCode) {
  613. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  614. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  615. n->setNotFound();
  616. break;
  617. case NetworkController::NC_ERROR_ACCESS_DENIED:
  618. n->setAccessDenied();
  619. break;
  620. default:
  621. break;
  622. }
  623. } else if (requestPacketId) {
  624. // TODO
  625. /*
  626. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  627. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  628. outp.append(requestPacketId);
  629. switch(errorCode) {
  630. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  631. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  632. default:
  633. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  634. break;
  635. case NetworkController::NC_ERROR_ACCESS_DENIED:
  636. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  637. break;
  638. }
  639. outp.append(nwid);
  640. RR->sw->send((void *)0,outp,true);
  641. */
  642. } // else we can't send an ERROR() in response to nothing, so discard
  643. }
  644. } // namespace ZeroTier
  645. // C API --------------------------------------------------------------------------------------------------------------
  646. extern "C" {
  647. // These macros make the idiom of passing buffers to outside code via the API work properly even
  648. // if the first address of Buf does not overlap with its data field, since the C++ standard does
  649. // not absolutely guarantee this.
  650. #define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) ))
  651. #define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
  652. void *ZT_getBuffer()
  653. {
  654. // When external code requests a Buf, grab one from the pool (or freshly allocated)
  655. // and return it with its reference count left at zero. It's the responsibility of
  656. // external code to bring it back via freeBuffer() or one of the processX() calls.
  657. // When this occurs it's either sent back to the pool with Buf's delete operator or
  658. // wrapped in a SharedPtr<> to be passed into the core.
  659. try {
  660. return _ZT_BUFTOPTR(new ZeroTier::Buf());
  661. } catch (...) {
  662. return nullptr; // can only happen on out of memory condition
  663. }
  664. }
  665. void ZT_freeBuffer(void *b)
  666. {
  667. if (b)
  668. delete _ZT_PTRTOBUF(b);
  669. }
  670. void ZT_freeQueryResult(void *qr)
  671. {
  672. if (qr)
  673. free(qr);
  674. }
  675. enum ZT_ResultCode ZT_Node_new(ZT_Node **node, void *uptr, void *tptr, const struct ZT_Node_Callbacks *callbacks, int64_t now)
  676. {
  677. *node = (ZT_Node *)0;
  678. try {
  679. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr, tptr, callbacks, now));
  680. return ZT_RESULT_OK;
  681. } catch (std::bad_alloc &exc) {
  682. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  683. } catch (std::runtime_error &exc) {
  684. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  685. } catch (...) {
  686. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  687. }
  688. }
  689. void ZT_Node_delete(ZT_Node *node, void *tPtr)
  690. {
  691. try {
  692. reinterpret_cast<ZeroTier::Node *>(node)->shutdown(tPtr);
  693. delete (reinterpret_cast<ZeroTier::Node *>(node));
  694. } catch (...) {}
  695. }
  696. enum ZT_ResultCode ZT_Node_processWirePacket(
  697. ZT_Node *node,
  698. void *tptr,
  699. int64_t now,
  700. int64_t localSocket,
  701. const struct sockaddr_storage *remoteAddress,
  702. const void *packetData,
  703. unsigned int packetLength,
  704. int isZtBuffer,
  705. volatile int64_t *nextBackgroundTaskDeadline)
  706. {
  707. try {
  708. ZeroTier::SharedPtr<ZeroTier::Buf> buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData, packetLength & ZT_BUF_MEM_MASK));
  709. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline);
  710. } catch (std::bad_alloc &exc) {
  711. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  712. } catch (...) {
  713. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  714. }
  715. }
  716. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  717. ZT_Node *node,
  718. void *tptr,
  719. int64_t now,
  720. uint64_t nwid,
  721. uint64_t sourceMac,
  722. uint64_t destMac,
  723. unsigned int etherType,
  724. unsigned int vlanId,
  725. const void *frameData,
  726. unsigned int frameLength,
  727. int isZtBuffer,
  728. volatile int64_t *nextBackgroundTaskDeadline)
  729. {
  730. try {
  731. ZeroTier::SharedPtr<ZeroTier::Buf> buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData, frameLength & ZT_BUF_MEM_MASK));
  732. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline);
  733. } catch (std::bad_alloc &exc) {
  734. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  735. } catch (...) {
  736. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  737. }
  738. }
  739. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node, void *tptr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline)
  740. {
  741. try {
  742. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr, now, nextBackgroundTaskDeadline);
  743. } catch (std::bad_alloc &exc) {
  744. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  745. } catch (...) {
  746. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  747. }
  748. }
  749. enum ZT_ResultCode ZT_Node_join(ZT_Node *node, uint64_t nwid, const ZT_Fingerprint *controllerFingerprint, void *uptr, void *tptr)
  750. {
  751. try {
  752. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid, controllerFingerprint, uptr, tptr);
  753. } catch (std::bad_alloc &exc) {
  754. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  755. } catch (...) {
  756. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  757. }
  758. }
  759. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node, uint64_t nwid, void **uptr, void *tptr)
  760. {
  761. try {
  762. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid, uptr, tptr);
  763. } catch (std::bad_alloc &exc) {
  764. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  765. } catch (...) {
  766. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  767. }
  768. }
  769. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node, void *tptr, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  770. {
  771. try {
  772. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr, nwid, multicastGroup, multicastAdi);
  773. } catch (std::bad_alloc &exc) {
  774. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  775. } catch (...) {
  776. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  777. }
  778. }
  779. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  780. {
  781. try {
  782. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid, multicastGroup, multicastAdi);
  783. } catch (std::bad_alloc &exc) {
  784. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  785. } catch (...) {
  786. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  787. }
  788. }
  789. enum ZT_ResultCode ZT_Node_addRoot(ZT_Node *node, void *tptr, const ZT_Identity *id)
  790. {
  791. try {
  792. return reinterpret_cast<ZeroTier::Node *>(node)->addRoot(tptr, id);
  793. } catch (std::bad_alloc &exc) {
  794. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  795. } catch (...) {
  796. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  797. }
  798. }
  799. enum ZT_ResultCode ZT_Node_removeRoot(ZT_Node *node, void *tptr, const uint64_t address)
  800. {
  801. try {
  802. return reinterpret_cast<ZeroTier::Node *>(node)->removeRoot(tptr, address);
  803. } catch (std::bad_alloc &exc) {
  804. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  805. } catch (...) {
  806. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  807. }
  808. }
  809. uint64_t ZT_Node_address(ZT_Node *node)
  810. {
  811. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  812. }
  813. const ZT_Identity *ZT_Node_identity(ZT_Node *node)
  814. {
  815. return (const ZT_Identity *)(&(reinterpret_cast<ZeroTier::Node *>(node)->identity()));
  816. }
  817. void ZT_Node_status(ZT_Node *node, ZT_NodeStatus *status)
  818. {
  819. try {
  820. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  821. } catch (...) {}
  822. }
  823. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  824. {
  825. try {
  826. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  827. } catch (...) {
  828. return (ZT_PeerList *)0;
  829. }
  830. }
  831. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node, uint64_t nwid)
  832. {
  833. try {
  834. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  835. } catch (...) {
  836. return (ZT_VirtualNetworkConfig *)0;
  837. }
  838. }
  839. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  840. {
  841. try {
  842. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  843. } catch (...) {
  844. return (ZT_VirtualNetworkList *)0;
  845. }
  846. }
  847. void ZT_Node_setNetworkUserPtr(ZT_Node *node, uint64_t nwid, void *ptr)
  848. {
  849. try {
  850. reinterpret_cast<ZeroTier::Node *>(node)->setNetworkUserPtr(nwid, ptr);
  851. } catch (...) {}
  852. }
  853. void ZT_Node_setInterfaceAddresses(ZT_Node *node, const ZT_InterfaceAddress *addrs, unsigned int addrCount)
  854. {
  855. try {
  856. reinterpret_cast<ZeroTier::Node *>(node)->setInterfaceAddresses(addrs, addrCount);
  857. } catch (...) {}
  858. }
  859. int ZT_Node_sendUserMessage(ZT_Node *node, void *tptr, uint64_t dest, uint64_t typeId, const void *data, unsigned int len)
  860. {
  861. try {
  862. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr, dest, typeId, data, len);
  863. } catch (...) {
  864. return 0;
  865. }
  866. }
  867. void ZT_Node_setController(ZT_Node *node, void *networkControllerInstance)
  868. {
  869. try {
  870. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  871. } catch (...) {}
  872. }
  873. void ZT_version(int *major, int *minor, int *revision, int *build)
  874. {
  875. if (major)
  876. *major = ZEROTIER_VERSION_MAJOR;
  877. if (minor)
  878. *minor = ZEROTIER_VERSION_MINOR;
  879. if (revision)
  880. *revision = ZEROTIER_VERSION_REVISION;
  881. if (build)
  882. *build = ZEROTIER_VERSION_BUILD;
  883. }
  884. } // extern "C"