Node.cpp 31 KB

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