Node.cpp 27 KB

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