Node.cpp 30 KB

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