Node.cpp 31 KB

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