Node.cpp 30 KB

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