Node.cpp 30 KB

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