Node.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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 bool 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. return true;
  191. }
  192. };
  193. ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  194. {
  195. _now = now;
  196. Mutex::Lock bl(_backgroundTasksLock);
  197. // Initialize these on first call so these things happen just a few seconds after
  198. // startup, since right at startup things are likely to not be ready to communicate
  199. // at all yet.
  200. if (_lastNetworkHousekeepingRun <= 0)
  201. _lastNetworkHousekeepingRun = now - (ZT_NETWORK_HOUSEKEEPING_PERIOD / 3);
  202. if (_lastHousekeepingRun <= 0)
  203. _lastHousekeepingRun = now;
  204. if ((now - _lastPing) >= ZT_PEER_PING_PERIOD) {
  205. _lastPing = now;
  206. try {
  207. _processBackgroundTasks_ping_eachRoot rf;
  208. rf.now = now;
  209. rf.tPtr = tptr;
  210. rf.online = false;
  211. RR->topology->eachRoot(rf);
  212. _processBackgroundTasks_ping_eachPeer pf;
  213. pf.now = now;
  214. pf.tPtr = tptr;
  215. pf.roots = &rf.roots;
  216. RR->topology->eachPeer(pf);
  217. if (rf.online != _online) {
  218. _online = rf.online;
  219. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  220. }
  221. } catch ( ... ) {
  222. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  223. }
  224. }
  225. if ((now - _lastNetworkHousekeepingRun) >= ZT_NETWORK_HOUSEKEEPING_PERIOD) {
  226. _lastHousekeepingRun = now;
  227. {
  228. Mutex::Lock l(_networks_m);
  229. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  230. uint64_t *nwid = (uint64_t *)0;
  231. SharedPtr<Network> *network = (SharedPtr<Network> *)0;
  232. while (i.next(nwid,network)) {
  233. (*network)->doPeriodicTasks(tptr,now);
  234. }
  235. }
  236. RR->t->updateMemoizedSettings();
  237. }
  238. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  239. _lastHousekeepingRun = now;
  240. try {
  241. // Clean up any old local controller auth memoizations. This is an
  242. // optimization for network controllers to know whether to accept
  243. // or trust nodes without doing an extra cert check.
  244. {
  245. _localControllerAuthorizations_m.lock();
  246. Hashtable< _LocalControllerAuth,int64_t >::Iterator i(_localControllerAuthorizations);
  247. _LocalControllerAuth *k = (_LocalControllerAuth *)0;
  248. int64_t *v = (int64_t *)0;
  249. while (i.next(k,v)) {
  250. if ((*v - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3)) {
  251. _localControllerAuthorizations.erase(*k);
  252. }
  253. }
  254. _localControllerAuthorizations_m.unlock();
  255. }
  256. RR->topology->doPeriodicTasks(now);
  257. RR->sa->clean(now);
  258. RR->mc->clean(now);
  259. } catch ( ... ) {
  260. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  261. }
  262. }
  263. try {
  264. *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);
  265. } catch ( ... ) {
  266. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  267. }
  268. return ZT_RESULT_OK;
  269. }
  270. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  271. {
  272. Mutex::Lock _l(_networks_m);
  273. SharedPtr<Network> &nw = _networks[nwid];
  274. if (!nw)
  275. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  276. return ZT_RESULT_OK;
  277. }
  278. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  279. {
  280. ZT_VirtualNetworkConfig ctmp;
  281. void **nUserPtr = (void **)0;
  282. {
  283. Mutex::Lock _l(_networks_m);
  284. SharedPtr<Network> *nw = _networks.get(nwid);
  285. RR->sw->removeNetworkQoSControlBlock(nwid);
  286. if (!nw)
  287. return ZT_RESULT_OK;
  288. if (uptr)
  289. *uptr = (*nw)->userPtr();
  290. (*nw)->externalConfig(&ctmp);
  291. (*nw)->destroy();
  292. nUserPtr = (*nw)->userPtr();
  293. }
  294. if (nUserPtr)
  295. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  296. {
  297. Mutex::Lock _l(_networks_m);
  298. _networks.erase(nwid);
  299. }
  300. uint64_t tmp[2];
  301. tmp[0] = nwid; tmp[1] = 0;
  302. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  303. return ZT_RESULT_OK;
  304. }
  305. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  306. {
  307. SharedPtr<Network> nw(this->network(nwid));
  308. if (nw) {
  309. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  310. return ZT_RESULT_OK;
  311. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  312. }
  313. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  314. {
  315. SharedPtr<Network> nw(this->network(nwid));
  316. if (nw) {
  317. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  318. return ZT_RESULT_OK;
  319. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  320. }
  321. uint64_t Node::address() const
  322. {
  323. return RR->identity.address().toInt();
  324. }
  325. void Node::status(ZT_NodeStatus *status) const
  326. {
  327. status->address = RR->identity.address().toInt();
  328. status->publicIdentity = RR->publicIdentityStr;
  329. status->secretIdentity = RR->secretIdentityStr;
  330. status->online = _online ? 1 : 0;
  331. }
  332. struct _sortPeerPtrsByAddress { inline bool operator()(const SharedPtr<Peer> &a,const SharedPtr<Peer> &b) const { return (a->address() < b->address()); } };
  333. ZT_PeerList *Node::peers() const
  334. {
  335. std::vector< SharedPtr<Peer> > peers;
  336. RR->topology->getAllPeers(peers);
  337. std::sort(peers.begin(),peers.end(),_sortPeerPtrsByAddress());
  338. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  339. if (!buf)
  340. return (ZT_PeerList *)0;
  341. ZT_PeerList *pl = (ZT_PeerList *)buf;
  342. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  343. pl->peerCount = 0;
  344. for(std::vector< SharedPtr<Peer> >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  345. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  346. p->address = (*pi)->address().toInt();
  347. p->hadAggregateLink = 0;
  348. if ((*pi)->remoteVersionKnown()) {
  349. p->versionMajor = (*pi)->remoteVersionMajor();
  350. p->versionMinor = (*pi)->remoteVersionMinor();
  351. p->versionRev = (*pi)->remoteVersionRevision();
  352. } else {
  353. p->versionMajor = -1;
  354. p->versionMinor = -1;
  355. p->versionRev = -1;
  356. }
  357. p->latency = (*pi)->latency(_now);
  358. if (p->latency >= 0xffff)
  359. p->latency = -1;
  360. p->role = RR->topology->isRoot((*pi)->identity()) ? ZT_PEER_ROLE_PLANET : ZT_PEER_ROLE_LEAF;
  361. std::vector< SharedPtr<Path> > paths((*pi)->paths(_now));
  362. SharedPtr<Path> bestp((*pi)->getAppropriatePath(_now,false));
  363. p->hadAggregateLink |= (*pi)->hasAggregateLink();
  364. p->pathCount = 0;
  365. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  366. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  367. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  368. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  369. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  370. p->paths[p->pathCount].expired = 0;
  371. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  372. p->paths[p->pathCount].latency = (float)(*path)->latency();
  373. p->paths[p->pathCount].packetDelayVariance = (*path)->packetDelayVariance();
  374. p->paths[p->pathCount].throughputDisturbCoeff = (*path)->throughputDisturbanceCoefficient();
  375. p->paths[p->pathCount].packetErrorRatio = (*path)->packetErrorRatio();
  376. p->paths[p->pathCount].packetLossRatio = (*path)->packetLossRatio();
  377. p->paths[p->pathCount].stability = (*path)->lastComputedStability();
  378. p->paths[p->pathCount].throughput = (*path)->meanThroughput();
  379. p->paths[p->pathCount].maxThroughput = (*path)->maxLifetimeThroughput();
  380. p->paths[p->pathCount].allocation = (float)(*path)->allocation() / (float)255;
  381. p->paths[p->pathCount].ifname = (*path)->getName();
  382. ++p->pathCount;
  383. }
  384. }
  385. return pl;
  386. }
  387. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  388. {
  389. Mutex::Lock _l(_networks_m);
  390. const SharedPtr<Network> *nw = _networks.get(nwid);
  391. if (nw) {
  392. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  393. (*nw)->externalConfig(nc);
  394. return nc;
  395. }
  396. return (ZT_VirtualNetworkConfig *)0;
  397. }
  398. ZT_VirtualNetworkList *Node::networks() const
  399. {
  400. Mutex::Lock _l(_networks_m);
  401. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  402. if (!buf)
  403. return (ZT_VirtualNetworkList *)0;
  404. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  405. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  406. nl->networkCount = 0;
  407. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  408. uint64_t *k = (uint64_t *)0;
  409. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  410. while (i.next(k,v))
  411. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  412. return nl;
  413. }
  414. void Node::freeQueryResult(void *qr)
  415. {
  416. if (qr)
  417. ::free(qr);
  418. }
  419. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  420. {
  421. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  422. Mutex::Lock _l(_localInterfaceAddresses_m);
  423. if (std::find(_localInterfaceAddresses.begin(),_localInterfaceAddresses.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _localInterfaceAddresses.end()) {
  424. _localInterfaceAddresses.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  425. return 1;
  426. }
  427. }
  428. return 0;
  429. }
  430. void Node::clearLocalInterfaceAddresses()
  431. {
  432. Mutex::Lock _l(_localInterfaceAddresses_m);
  433. _localInterfaceAddresses.clear();
  434. }
  435. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  436. {
  437. try {
  438. if (RR->identity.address().toInt() != dest) {
  439. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  440. outp.append(typeId);
  441. outp.append(data,len);
  442. outp.compress();
  443. RR->sw->send(tptr,outp,true);
  444. return 1;
  445. }
  446. } catch ( ... ) {}
  447. return 0;
  448. }
  449. void Node::setController(void *networkControllerInstance)
  450. {
  451. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  452. if (networkControllerInstance)
  453. RR->localNetworkController->init(RR->identity,this);
  454. }
  455. /****************************************************************************/
  456. /* Node methods used only within node/ */
  457. /****************************************************************************/
  458. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  459. {
  460. if (!Path::isAddressValidForPath(remoteAddress))
  461. return false;
  462. {
  463. Mutex::Lock _l(_networks_m);
  464. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  465. uint64_t *k = (uint64_t *)0;
  466. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  467. while (i.next(k,v)) {
  468. if ((*v)->hasConfig()) {
  469. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  470. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  471. return false;
  472. }
  473. }
  474. }
  475. }
  476. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  477. }
  478. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  479. {
  480. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  481. return ZT_RESULT_OK;
  482. }
  483. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  484. {
  485. _localControllerAuthorizations_m.lock();
  486. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  487. _localControllerAuthorizations_m.unlock();
  488. if (destination == RR->identity.address()) {
  489. SharedPtr<Network> n(network(nwid));
  490. if (!n) return;
  491. n->setConfiguration((void *)0,nc,true);
  492. } else {
  493. ScopedPtr< Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> > dconf(new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>());
  494. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  495. uint64_t configUpdateId = Utils::random();
  496. if (!configUpdateId) ++configUpdateId;
  497. const unsigned int totalSize = dconf->sizeBytes();
  498. unsigned int chunkIndex = 0;
  499. while (chunkIndex < totalSize) {
  500. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  501. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  502. if (requestPacketId) {
  503. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  504. outp.append(requestPacketId);
  505. }
  506. const unsigned int sigStart = outp.size();
  507. outp.append(nwid);
  508. outp.append((uint16_t)chunkLen);
  509. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  510. outp.append((uint8_t)0); // no flags
  511. outp.append((uint64_t)configUpdateId);
  512. outp.append((uint32_t)totalSize);
  513. outp.append((uint32_t)chunkIndex);
  514. uint8_t sig[256];
  515. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  516. outp.append((uint8_t)1);
  517. outp.append((uint16_t)siglen);
  518. outp.append(sig,siglen);
  519. outp.compress();
  520. RR->sw->send((void *)0,outp,true);
  521. chunkIndex += chunkLen;
  522. }
  523. }
  524. }
  525. }
  526. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  527. {
  528. if (destination == RR->identity.address()) {
  529. SharedPtr<Network> n(network(rev.networkId()));
  530. if (!n) return;
  531. n->addCredential((void *)0,RR->identity.address(),rev);
  532. } else {
  533. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  534. outp.append((uint8_t)0x00);
  535. outp.append((uint16_t)0);
  536. outp.append((uint16_t)0);
  537. outp.append((uint16_t)1);
  538. rev.serialize(outp);
  539. outp.append((uint16_t)0);
  540. RR->sw->send((void *)0,outp,true);
  541. }
  542. }
  543. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  544. {
  545. if (destination == RR->identity.address()) {
  546. SharedPtr<Network> n(network(nwid));
  547. if (!n) return;
  548. switch(errorCode) {
  549. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  550. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  551. n->setNotFound();
  552. break;
  553. case NetworkController::NC_ERROR_ACCESS_DENIED:
  554. n->setAccessDenied();
  555. break;
  556. default: break;
  557. }
  558. } else if (requestPacketId) {
  559. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  560. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  561. outp.append(requestPacketId);
  562. switch(errorCode) {
  563. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  564. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  565. default:
  566. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  567. break;
  568. case NetworkController::NC_ERROR_ACCESS_DENIED:
  569. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  570. break;
  571. }
  572. outp.append(nwid);
  573. RR->sw->send((void *)0,outp,true);
  574. } // else we can't send an ERROR() in response to nothing, so discard
  575. }
  576. } // namespace ZeroTier
  577. /****************************************************************************/
  578. /* CAPI bindings */
  579. /****************************************************************************/
  580. extern "C" {
  581. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  582. {
  583. *node = (ZT_Node *)0;
  584. try {
  585. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  586. return ZT_RESULT_OK;
  587. } catch (std::bad_alloc &exc) {
  588. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  589. } catch (std::runtime_error &exc) {
  590. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  591. } catch ( ... ) {
  592. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  593. }
  594. }
  595. void ZT_Node_delete(ZT_Node *node)
  596. {
  597. try {
  598. delete (reinterpret_cast<ZeroTier::Node *>(node));
  599. } catch ( ... ) {}
  600. }
  601. enum ZT_ResultCode ZT_Node_processWirePacket(
  602. ZT_Node *node,
  603. void *tptr,
  604. int64_t now,
  605. int64_t localSocket,
  606. const struct sockaddr_storage *remoteAddress,
  607. const void *packetData,
  608. unsigned int packetLength,
  609. volatile int64_t *nextBackgroundTaskDeadline)
  610. {
  611. try {
  612. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  613. } catch (std::bad_alloc &exc) {
  614. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  615. } catch ( ... ) {
  616. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  617. }
  618. }
  619. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  620. ZT_Node *node,
  621. void *tptr,
  622. int64_t now,
  623. uint64_t nwid,
  624. uint64_t sourceMac,
  625. uint64_t destMac,
  626. unsigned int etherType,
  627. unsigned int vlanId,
  628. const void *frameData,
  629. unsigned int frameLength,
  630. volatile int64_t *nextBackgroundTaskDeadline)
  631. {
  632. try {
  633. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  634. } catch (std::bad_alloc &exc) {
  635. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  636. } catch ( ... ) {
  637. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  638. }
  639. }
  640. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  641. {
  642. try {
  643. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  644. } catch (std::bad_alloc &exc) {
  645. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  646. } catch ( ... ) {
  647. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  648. }
  649. }
  650. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  651. {
  652. try {
  653. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  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_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  661. {
  662. try {
  663. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  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_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  671. {
  672. try {
  673. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  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_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  681. {
  682. try {
  683. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  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. uint64_t ZT_Node_address(ZT_Node *node)
  691. {
  692. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  693. }
  694. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  695. {
  696. try {
  697. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  698. } catch ( ... ) {}
  699. }
  700. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  701. {
  702. try {
  703. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  704. } catch ( ... ) {
  705. return (ZT_PeerList *)0;
  706. }
  707. }
  708. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  709. {
  710. try {
  711. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  712. } catch ( ... ) {
  713. return (ZT_VirtualNetworkConfig *)0;
  714. }
  715. }
  716. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  717. {
  718. try {
  719. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  720. } catch ( ... ) {
  721. return (ZT_VirtualNetworkList *)0;
  722. }
  723. }
  724. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  725. {
  726. try {
  727. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  728. } catch ( ... ) {}
  729. }
  730. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  731. {
  732. try {
  733. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  734. } catch ( ... ) {
  735. return 0;
  736. }
  737. }
  738. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  739. {
  740. try {
  741. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  742. } catch ( ... ) {}
  743. }
  744. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  745. {
  746. try {
  747. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  748. } catch ( ... ) {
  749. return 0;
  750. }
  751. }
  752. void ZT_Node_setController(ZT_Node *node,void *networkControllerInstance)
  753. {
  754. try {
  755. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  756. } catch ( ... ) {}
  757. }
  758. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  759. {
  760. try {
  761. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  762. } catch ( ... ) {
  763. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  764. }
  765. }
  766. void ZT_version(int *major,int *minor,int *revision)
  767. {
  768. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  769. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  770. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  771. }
  772. } // extern "C"