Node.cpp 28 KB

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