Node.cpp 30 KB

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