Node.cpp 29 KB

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