Node.cpp 30 KB

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