Node.cpp 27 KB

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