Node.cpp 31 KB

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