Node.cpp 30 KB

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