Node.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. bool Node::localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address &addr) const
  518. {
  519. m_localControllerAuthorizations_l.lock();
  520. const int64_t *const at = m_localControllerAuthorizations.get(p_LocalControllerAuth(nwid, addr));
  521. m_localControllerAuthorizations_l.unlock();
  522. if (at)
  523. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  524. return false;
  525. }
  526. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  527. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  528. {
  529. m_localControllerAuthorizations_l.lock();
  530. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  531. m_localControllerAuthorizations_l.unlock();
  532. if (destination == RR->identity.address()) {
  533. SharedPtr<Network> n(network(nwid));
  534. if (!n)
  535. return;
  536. n->setConfiguration((void *)0,nc,true);
  537. } else {
  538. Dictionary dconf;
  539. if (nc.toDictionary(dconf)) {
  540. uint64_t configUpdateId = Utils::random();
  541. if (!configUpdateId)
  542. ++configUpdateId;
  543. Vector<uint8_t> ddata;
  544. dconf.encode(ddata);
  545. // TODO
  546. /*
  547. unsigned int chunkIndex = 0;
  548. while (chunkIndex < totalSize) {
  549. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  550. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  551. if (requestPacketId) {
  552. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  553. outp.append(requestPacketId);
  554. }
  555. const unsigned int sigStart = outp.size();
  556. outp.append(nwid);
  557. outp.append((uint16_t)chunkLen);
  558. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  559. outp.append((uint8_t)0); // no flags
  560. outp.append((uint64_t)configUpdateId);
  561. outp.append((uint32_t)totalSize);
  562. outp.append((uint32_t)chunkIndex);
  563. uint8_t sig[256];
  564. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  565. outp.append((uint8_t)1);
  566. outp.append((uint16_t)siglen);
  567. outp.append(sig,siglen);
  568. outp.compress();
  569. RR->sw->send((void *)0,outp,true);
  570. chunkIndex += chunkLen;
  571. }
  572. */
  573. }
  574. }
  575. }
  576. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  577. {
  578. if (destination == RR->identity.address()) {
  579. SharedPtr<Network> n(network(rev.networkId()));
  580. if (!n) return;
  581. n->addCredential(nullptr,RR->identity,rev);
  582. } else {
  583. // TODO
  584. /*
  585. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  586. outp.append((uint8_t)0x00);
  587. outp.append((uint16_t)0);
  588. outp.append((uint16_t)0);
  589. outp.append((uint16_t)1);
  590. rev.serialize(outp);
  591. outp.append((uint16_t)0);
  592. RR->sw->send((void *)0,outp,true);
  593. */
  594. }
  595. }
  596. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  597. {
  598. if (destination == RR->identity.address()) {
  599. SharedPtr<Network> n(network(nwid));
  600. if (!n) return;
  601. switch(errorCode) {
  602. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  603. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  604. n->setNotFound();
  605. break;
  606. case NetworkController::NC_ERROR_ACCESS_DENIED:
  607. n->setAccessDenied();
  608. break;
  609. default: break;
  610. }
  611. } else if (requestPacketId) {
  612. // TODO
  613. /*
  614. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  615. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  616. outp.append(requestPacketId);
  617. switch(errorCode) {
  618. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  619. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  620. default:
  621. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  622. break;
  623. case NetworkController::NC_ERROR_ACCESS_DENIED:
  624. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  625. break;
  626. }
  627. outp.append(nwid);
  628. RR->sw->send((void *)0,outp,true);
  629. */
  630. } // else we can't send an ERROR() in response to nothing, so discard
  631. }
  632. } // namespace ZeroTier
  633. // C API --------------------------------------------------------------------------------------------------------------
  634. extern "C" {
  635. // These macros make the idiom of passing buffers to outside code via the API work properly even
  636. // if the first address of Buf does not overlap with its data field, since the C++ standard does
  637. // not absolutely guarantee this.
  638. #define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) ))
  639. #define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
  640. void *ZT_getBuffer()
  641. {
  642. // When external code requests a Buf, grab one from the pool (or freshly allocated)
  643. // and return it with its reference count left at zero. It's the responsibility of
  644. // external code to bring it back via freeBuffer() or one of the processX() calls.
  645. // When this occurs it's either sent back to the pool with Buf's delete operator or
  646. // wrapped in a SharedPtr<> to be passed into the core.
  647. try {
  648. return _ZT_BUFTOPTR(new ZeroTier::Buf());
  649. } catch ( ... ) {
  650. return nullptr; // can only happen on out of memory condition
  651. }
  652. }
  653. ZT_SDK_API void ZT_freeBuffer(void *b)
  654. {
  655. if (b)
  656. delete _ZT_PTRTOBUF(b);
  657. }
  658. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  659. {
  660. *node = (ZT_Node *)0;
  661. try {
  662. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  663. return ZT_RESULT_OK;
  664. } catch (std::bad_alloc &exc) {
  665. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  666. } catch (std::runtime_error &exc) {
  667. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  668. } catch ( ... ) {
  669. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  670. }
  671. }
  672. void ZT_Node_delete(ZT_Node *node,void *tPtr)
  673. {
  674. try {
  675. reinterpret_cast<ZeroTier::Node *>(node)->shutdown(tPtr);
  676. delete (reinterpret_cast<ZeroTier::Node *>(node));
  677. } catch ( ... ) {}
  678. }
  679. enum ZT_ResultCode ZT_Node_processWirePacket(
  680. ZT_Node *node,
  681. void *tptr,
  682. int64_t now,
  683. int64_t localSocket,
  684. const struct sockaddr_storage *remoteAddress,
  685. const void *packetData,
  686. unsigned int packetLength,
  687. int isZtBuffer,
  688. volatile int64_t *nextBackgroundTaskDeadline)
  689. {
  690. try {
  691. ZeroTier::SharedPtr<ZeroTier::Buf> buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData,packetLength & ZT_BUF_MEM_MASK));
  692. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,buf,packetLength,nextBackgroundTaskDeadline);
  693. } catch (std::bad_alloc &exc) {
  694. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  695. } catch ( ... ) {
  696. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  697. }
  698. }
  699. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  700. ZT_Node *node,
  701. void *tptr,
  702. int64_t now,
  703. uint64_t nwid,
  704. uint64_t sourceMac,
  705. uint64_t destMac,
  706. unsigned int etherType,
  707. unsigned int vlanId,
  708. const void *frameData,
  709. unsigned int frameLength,
  710. int isZtBuffer,
  711. volatile int64_t *nextBackgroundTaskDeadline)
  712. {
  713. try {
  714. ZeroTier::SharedPtr<ZeroTier::Buf> buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData,frameLength & ZT_BUF_MEM_MASK));
  715. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,buf,frameLength,nextBackgroundTaskDeadline);
  716. } catch (std::bad_alloc &exc) {
  717. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  718. } catch ( ... ) {
  719. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  720. }
  721. }
  722. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  723. {
  724. try {
  725. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  726. } catch (std::bad_alloc &exc) {
  727. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  728. } catch ( ... ) {
  729. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  730. }
  731. }
  732. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,const ZT_Fingerprint *controllerFingerprint,void *uptr,void *tptr)
  733. {
  734. try {
  735. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,controllerFingerprint,uptr,tptr);
  736. } catch (std::bad_alloc &exc) {
  737. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  738. } catch ( ... ) {
  739. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  740. }
  741. }
  742. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  743. {
  744. try {
  745. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  746. } catch (std::bad_alloc &exc) {
  747. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  748. } catch ( ... ) {
  749. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  750. }
  751. }
  752. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  753. {
  754. try {
  755. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  756. } catch (std::bad_alloc &exc) {
  757. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  758. } catch ( ... ) {
  759. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  760. }
  761. }
  762. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  763. {
  764. try {
  765. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  766. } catch (std::bad_alloc &exc) {
  767. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  768. } catch ( ... ) {
  769. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  770. }
  771. }
  772. enum ZT_ResultCode ZT_Node_addRoot(ZT_Node *node,void *tptr,const void *rdef,unsigned int rdeflen)
  773. {
  774. try {
  775. return reinterpret_cast<ZeroTier::Node *>(node)->addRoot(tptr,rdef,rdeflen);
  776. } catch (std::bad_alloc &exc) {
  777. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  778. } catch ( ... ) {
  779. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  780. }
  781. }
  782. enum ZT_ResultCode ZT_Node_removeRoot(ZT_Node *node,void *tptr,const ZT_Fingerprint *fp)
  783. {
  784. try {
  785. return reinterpret_cast<ZeroTier::Node *>(node)->removeRoot(tptr,fp);
  786. } catch (std::bad_alloc &exc) {
  787. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  788. } catch ( ... ) {
  789. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  790. }
  791. }
  792. uint64_t ZT_Node_address(ZT_Node *node)
  793. {
  794. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  795. }
  796. const ZT_Identity *ZT_Node_identity(ZT_Node *node)
  797. {
  798. return (const ZT_Identity *)(&(reinterpret_cast<ZeroTier::Node *>(node)->identity()));
  799. }
  800. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  801. {
  802. try {
  803. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  804. } catch ( ... ) {}
  805. }
  806. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  807. {
  808. try {
  809. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  810. } catch ( ... ) {
  811. return (ZT_PeerList *)0;
  812. }
  813. }
  814. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  815. {
  816. try {
  817. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  818. } catch ( ... ) {
  819. return (ZT_VirtualNetworkConfig *)0;
  820. }
  821. }
  822. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  823. {
  824. try {
  825. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  826. } catch ( ... ) {
  827. return (ZT_VirtualNetworkList *)0;
  828. }
  829. }
  830. void ZT_Node_setNetworkUserPtr(ZT_Node *node,uint64_t nwid,void *ptr)
  831. {
  832. try {
  833. reinterpret_cast<ZeroTier::Node *>(node)->setNetworkUserPtr(nwid,ptr);
  834. } catch ( ... ) {}
  835. }
  836. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  837. {
  838. try {
  839. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  840. } catch ( ... ) {}
  841. }
  842. void ZT_Node_setInterfaceAddresses(ZT_Node *node,const ZT_InterfaceAddress *addrs,unsigned int addrCount)
  843. {
  844. try {
  845. reinterpret_cast<ZeroTier::Node *>(node)->setInterfaceAddresses(addrs,addrCount);
  846. } catch ( ... ) {}
  847. }
  848. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  849. {
  850. try {
  851. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  852. } catch ( ... ) {
  853. return 0;
  854. }
  855. }
  856. void ZT_Node_setController(ZT_Node *node,void *networkControllerInstance)
  857. {
  858. try {
  859. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  860. } catch ( ... ) {}
  861. }
  862. void ZT_version(int *major,int *minor,int *revision,int *build)
  863. {
  864. if (major)
  865. *major = ZEROTIER_VERSION_MAJOR;
  866. if (minor)
  867. *minor = ZEROTIER_VERSION_MINOR;
  868. if (revision)
  869. *revision = ZEROTIER_VERSION_REVISION;
  870. if (build)
  871. *build = ZEROTIER_VERSION_BUILD;
  872. }
  873. } // extern "C"