Node.cpp 30 KB

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