Node.cpp 30 KB

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