Node.cpp 30 KB

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