Node.cpp 30 KB

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