Node.cpp 31 KB

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