Node.cpp 30 KB

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