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