Node.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <stdarg.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include "../version.h"
  32. #include "Constants.hpp"
  33. #include "SharedPtr.hpp"
  34. #include "Node.hpp"
  35. #include "RuntimeEnvironment.hpp"
  36. #include "NetworkController.hpp"
  37. #include "Switch.hpp"
  38. #include "Multicaster.hpp"
  39. #include "Topology.hpp"
  40. #include "Buffer.hpp"
  41. #include "Packet.hpp"
  42. #include "Address.hpp"
  43. #include "Identity.hpp"
  44. #include "SelfAwareness.hpp"
  45. #include "Network.hpp"
  46. #include "Trace.hpp"
  47. namespace ZeroTier {
  48. /****************************************************************************/
  49. /* Public Node interface (C++, exposed via CAPI bindings) */
  50. /****************************************************************************/
  51. Node::Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now) :
  52. _RR(this),
  53. RR(&_RR),
  54. _uPtr(uptr),
  55. _networks(8),
  56. _now(now),
  57. _lastPingCheck(0),
  58. _lastHousekeepingRun(0),
  59. _lastMemoizedTraceSettings(0)
  60. {
  61. if (callbacks->version != 0)
  62. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  63. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  64. // Initialize non-cryptographic PRNG from a good random source
  65. Utils::getSecureRandom((void *)_prngState,sizeof(_prngState));
  66. _online = false;
  67. memset(_expectingRepliesToBucketPtr,0,sizeof(_expectingRepliesToBucketPtr));
  68. memset(_expectingRepliesTo,0,sizeof(_expectingRepliesTo));
  69. memset(_lastIdentityVerification,0,sizeof(_lastIdentityVerification));
  70. memset((void *)(&_stats),0,sizeof(_stats));
  71. uint64_t idtmp[2];
  72. idtmp[0] = 0; idtmp[1] = 0;
  73. char tmp[2048];
  74. int n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,tmp,sizeof(tmp) - 1);
  75. if (n > 0) {
  76. tmp[n] = (char)0;
  77. if (RR->identity.fromString(tmp)) {
  78. RR->identity.toString(false,RR->publicIdentityStr);
  79. RR->identity.toString(true,RR->secretIdentityStr);
  80. } else {
  81. n = -1;
  82. }
  83. }
  84. if (n <= 0) {
  85. RR->identity.generate();
  86. RR->identity.toString(false,RR->publicIdentityStr);
  87. RR->identity.toString(true,RR->secretIdentityStr);
  88. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  89. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,RR->secretIdentityStr,(unsigned int)strlen(RR->secretIdentityStr));
  90. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  91. } else {
  92. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  93. n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,tmp,sizeof(tmp) - 1);
  94. if ((n > 0)&&(n < (int)sizeof(RR->publicIdentityStr))&&(n < (int)sizeof(tmp))) {
  95. if (memcmp(tmp,RR->publicIdentityStr,n))
  96. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  97. }
  98. }
  99. char *m = (char *)0;
  100. try {
  101. const unsigned long ts = sizeof(Trace) + (((sizeof(Trace) & 0xf) != 0) ? (16 - (sizeof(Trace) & 0xf)) : 0);
  102. const unsigned long sws = sizeof(Switch) + (((sizeof(Switch) & 0xf) != 0) ? (16 - (sizeof(Switch) & 0xf)) : 0);
  103. const unsigned long mcs = sizeof(Multicaster) + (((sizeof(Multicaster) & 0xf) != 0) ? (16 - (sizeof(Multicaster) & 0xf)) : 0);
  104. const unsigned long topologys = sizeof(Topology) + (((sizeof(Topology) & 0xf) != 0) ? (16 - (sizeof(Topology) & 0xf)) : 0);
  105. const unsigned long sas = sizeof(SelfAwareness) + (((sizeof(SelfAwareness) & 0xf) != 0) ? (16 - (sizeof(SelfAwareness) & 0xf)) : 0);
  106. m = reinterpret_cast<char *>(::malloc(16 + ts + sws + mcs + topologys + sas));
  107. if (!m)
  108. throw std::bad_alloc();
  109. RR->rtmem = m;
  110. while (((uintptr_t)m & 0xf) != 0) ++m;
  111. RR->t = new (m) Trace(RR);
  112. m += ts;
  113. RR->sw = new (m) Switch(RR);
  114. m += sws;
  115. RR->mc = new (m) Multicaster(RR);
  116. m += mcs;
  117. RR->topology = new (m) Topology(RR,tptr);
  118. m += topologys;
  119. RR->sa = new (m) SelfAwareness(RR);
  120. } catch ( ... ) {
  121. if (RR->sa) RR->sa->~SelfAwareness();
  122. if (RR->topology) RR->topology->~Topology();
  123. if (RR->mc) RR->mc->~Multicaster();
  124. if (RR->sw) RR->sw->~Switch();
  125. if (RR->t) RR->t->~Trace();
  126. ::free(m);
  127. throw;
  128. }
  129. postEvent(tptr,ZT_EVENT_UP);
  130. }
  131. Node::~Node()
  132. {
  133. {
  134. Mutex::Lock _l(_networks_m);
  135. _networks.clear(); // destroy all networks before shutdown
  136. }
  137. if (RR->sa) RR->sa->~SelfAwareness();
  138. if (RR->topology) RR->topology->~Topology();
  139. if (RR->mc) RR->mc->~Multicaster();
  140. if (RR->sw) RR->sw->~Switch();
  141. if (RR->t) RR->t->~Trace();
  142. ::free(RR->rtmem);
  143. }
  144. ZT_ResultCode Node::processWirePacket(
  145. void *tptr,
  146. int64_t now,
  147. int64_t localSocket,
  148. const struct sockaddr_storage *remoteAddress,
  149. const void *packetData,
  150. unsigned int packetLength,
  151. volatile int64_t *nextBackgroundTaskDeadline)
  152. {
  153. _now = now;
  154. RR->sw->onRemotePacket(tptr,localSocket,*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  155. return ZT_RESULT_OK;
  156. }
  157. ZT_ResultCode Node::processVirtualNetworkFrame(
  158. void *tptr,
  159. int64_t now,
  160. uint64_t nwid,
  161. uint64_t sourceMac,
  162. uint64_t destMac,
  163. unsigned int etherType,
  164. unsigned int vlanId,
  165. const void *frameData,
  166. unsigned int frameLength,
  167. volatile int64_t *nextBackgroundTaskDeadline)
  168. {
  169. _now = now;
  170. SharedPtr<Network> nw(this->network(nwid));
  171. if (nw) {
  172. RR->sw->onLocalEthernet(tptr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  173. return ZT_RESULT_OK;
  174. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  175. }
  176. // Closure used to ping upstream and active/online peers
  177. class _PingPeersThatNeedPing
  178. {
  179. public:
  180. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,void *tPtr,Hashtable< Address,std::vector<InetAddress> > &alwaysContact,int64_t now) :
  181. RR(renv),
  182. _tPtr(tPtr),
  183. _alwaysContact(alwaysContact),
  184. _now(now),
  185. _bestCurrentUpstream(RR->topology->getUpstreamPeer())
  186. {
  187. }
  188. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  189. {
  190. const std::vector<InetAddress> *const alwaysContactEndpoints = _alwaysContact.get(p->address());
  191. if (alwaysContactEndpoints) {
  192. const unsigned int sent = p->doPingAndKeepalive(_tPtr,_now);
  193. bool contacted = (sent != 0);
  194. if ((sent & 0x1) == 0) { // bit 0x1 == IPv4 sent
  195. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)alwaysContactEndpoints->size();++k) {
  196. const InetAddress &addr = (*alwaysContactEndpoints)[ptr++ % alwaysContactEndpoints->size()];
  197. if (addr.ss_family == AF_INET) {
  198. p->sendHELLO(_tPtr,-1,addr,_now);
  199. contacted = true;
  200. break;
  201. }
  202. }
  203. }
  204. if ((sent & 0x2) == 0) { // bit 0x2 == IPv6 sent
  205. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)alwaysContactEndpoints->size();++k) {
  206. const InetAddress &addr = (*alwaysContactEndpoints)[ptr++ % alwaysContactEndpoints->size()];
  207. if (addr.ss_family == AF_INET6) {
  208. p->sendHELLO(_tPtr,-1,addr,_now);
  209. contacted = true;
  210. break;
  211. }
  212. }
  213. }
  214. if ((!contacted)&&(_bestCurrentUpstream)) {
  215. const SharedPtr<Path> up(_bestCurrentUpstream->getAppropriatePath(_now,true));
  216. if (up)
  217. p->sendHELLO(_tPtr,up->localSocket(),up->address(),_now);
  218. }
  219. _alwaysContact.erase(p->address()); // after this we'll WHOIS all upstreams that remain
  220. } else if (p->isActive(_now)) {
  221. p->doPingAndKeepalive(_tPtr,_now);
  222. }
  223. }
  224. private:
  225. const RuntimeEnvironment *RR;
  226. void *_tPtr;
  227. Hashtable< Address,std::vector<InetAddress> > &_alwaysContact;
  228. const int64_t _now;
  229. const SharedPtr<Peer> _bestCurrentUpstream;
  230. };
  231. ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  232. {
  233. _now = now;
  234. Mutex::Lock bl(_backgroundTasksLock);
  235. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  236. const int64_t timeSinceLastPingCheck = now - _lastPingCheck;
  237. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  238. try {
  239. _lastPingCheck = now;
  240. // Get designated VL1 upstreams
  241. Hashtable< Address,std::vector<InetAddress> > alwaysContact;
  242. RR->topology->getUpstreamsToContact(alwaysContact);
  243. // Uncomment to dump stats
  244. /*
  245. for(unsigned int i=0;i<32;i++) {
  246. if (_stats.inVerbCounts[i] > 0)
  247. printf("%.2x\t%12lld %lld\n",i,(unsigned long long)_stats.inVerbCounts[i],(unsigned long long)_stats.inVerbBytes[i]);
  248. }
  249. printf("\n");
  250. */
  251. // Check last receive time on designated upstreams to see if we seem to be online
  252. int64_t lastReceivedFromUpstream = 0;
  253. {
  254. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  255. Address *upstreamAddress = (Address *)0;
  256. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  257. while (i.next(upstreamAddress,upstreamStableEndpoints)) {
  258. SharedPtr<Peer> p(RR->topology->getPeerNoCache(*upstreamAddress));
  259. if (p)
  260. lastReceivedFromUpstream = std::max(p->lastReceive(),lastReceivedFromUpstream);
  261. }
  262. }
  263. // Clean up any old local controller auth memorizations.
  264. {
  265. _localControllerAuthorizations_m.lock();
  266. Hashtable< _LocalControllerAuth,int64_t >::Iterator i(_localControllerAuthorizations);
  267. _LocalControllerAuth *k = (_LocalControllerAuth *)0;
  268. int64_t *v = (int64_t *)0;
  269. while (i.next(k,v)) {
  270. if ((*v - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  271. _localControllerAuthorizations.erase(*k);
  272. }
  273. _localControllerAuthorizations_m.unlock();
  274. }
  275. // Get peers we should stay connected to according to network configs
  276. // Also get networks and whether they need config so we only have to do one pass over networks
  277. std::vector< std::pair< SharedPtr<Network>,bool > > networkConfigNeeded;
  278. {
  279. Mutex::Lock l(_networks_m);
  280. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  281. uint64_t *nwid = (uint64_t *)0;
  282. SharedPtr<Network> *network = (SharedPtr<Network> *)0;
  283. while (i.next(nwid,network)) {
  284. (*network)->config().alwaysContactAddresses(alwaysContact);
  285. networkConfigNeeded.push_back( std::pair< SharedPtr<Network>,bool >(*network,(((now - (*network)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!(*network)->hasConfig()))) );
  286. }
  287. }
  288. // Ping active peers, upstreams, and others that we should always contact
  289. _PingPeersThatNeedPing pfunc(RR,tptr,alwaysContact,now);
  290. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  291. // Run WHOIS to create Peer for alwaysContact addresses that could not be contacted
  292. {
  293. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  294. Address *upstreamAddress = (Address *)0;
  295. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  296. while (i.next(upstreamAddress,upstreamStableEndpoints))
  297. RR->sw->requestWhois(tptr,now,*upstreamAddress);
  298. }
  299. // Refresh network config or broadcast network updates to members as needed
  300. for(std::vector< std::pair< SharedPtr<Network>,bool > >::const_iterator n(networkConfigNeeded.begin());n!=networkConfigNeeded.end();++n) {
  301. if (n->second)
  302. n->first->requestConfiguration(tptr);
  303. n->first->sendUpdatesToMembers(tptr);
  304. }
  305. // Update online status, post status change as event
  306. const bool oldOnline = _online;
  307. _online = (((now - lastReceivedFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amUpstream()));
  308. if (oldOnline != _online)
  309. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  310. } catch ( ... ) {
  311. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  312. }
  313. } else {
  314. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  315. }
  316. if ((now - _lastMemoizedTraceSettings) >= (ZT_HOUSEKEEPING_PERIOD / 4)) {
  317. _lastMemoizedTraceSettings = now;
  318. RR->t->updateMemoizedSettings();
  319. }
  320. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  321. _lastHousekeepingRun = now;
  322. try {
  323. RR->topology->doPeriodicTasks(tptr,now);
  324. RR->sa->clean(now);
  325. RR->mc->clean(now);
  326. } catch ( ... ) {
  327. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  328. }
  329. }
  330. try {
  331. *nextBackgroundTaskDeadline = now + (int64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  332. } catch ( ... ) {
  333. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  334. }
  335. return ZT_RESULT_OK;
  336. }
  337. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  338. {
  339. Mutex::Lock _l(_networks_m);
  340. SharedPtr<Network> &nw = _networks[nwid];
  341. if (!nw)
  342. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  343. return ZT_RESULT_OK;
  344. }
  345. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  346. {
  347. ZT_VirtualNetworkConfig ctmp;
  348. void **nUserPtr = (void **)0;
  349. {
  350. Mutex::Lock _l(_networks_m);
  351. SharedPtr<Network> *nw = _networks.get(nwid);
  352. RR->sw->removeNetworkQoSControlBlock(nwid);
  353. if (!nw)
  354. return ZT_RESULT_OK;
  355. if (uptr)
  356. *uptr = (*nw)->userPtr();
  357. (*nw)->externalConfig(&ctmp);
  358. (*nw)->destroy();
  359. nUserPtr = (*nw)->userPtr();
  360. }
  361. if (nUserPtr)
  362. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  363. {
  364. Mutex::Lock _l(_networks_m);
  365. _networks.erase(nwid);
  366. }
  367. uint64_t tmp[2];
  368. tmp[0] = nwid; tmp[1] = 0;
  369. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  370. return ZT_RESULT_OK;
  371. }
  372. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  373. {
  374. SharedPtr<Network> nw(this->network(nwid));
  375. if (nw) {
  376. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  377. return ZT_RESULT_OK;
  378. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  379. }
  380. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  381. {
  382. SharedPtr<Network> nw(this->network(nwid));
  383. if (nw) {
  384. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  385. return ZT_RESULT_OK;
  386. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  387. }
  388. ZT_ResultCode Node::orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  389. {
  390. RR->topology->addMoon(tptr,moonWorldId,Address(moonSeed));
  391. return ZT_RESULT_OK;
  392. }
  393. ZT_ResultCode Node::deorbit(void *tptr,uint64_t moonWorldId)
  394. {
  395. RR->topology->removeMoon(tptr,moonWorldId);
  396. return ZT_RESULT_OK;
  397. }
  398. uint64_t Node::address() const
  399. {
  400. return RR->identity.address().toInt();
  401. }
  402. void Node::status(ZT_NodeStatus *status) const
  403. {
  404. status->address = RR->identity.address().toInt();
  405. status->publicIdentity = RR->publicIdentityStr;
  406. status->secretIdentity = RR->secretIdentityStr;
  407. status->online = _online ? 1 : 0;
  408. }
  409. ZT_PeerList *Node::peers() const
  410. {
  411. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  412. std::sort(peers.begin(),peers.end());
  413. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  414. if (!buf)
  415. return (ZT_PeerList *)0;
  416. ZT_PeerList *pl = (ZT_PeerList *)buf;
  417. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  418. pl->peerCount = 0;
  419. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  420. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  421. p->address = pi->second->address().toInt();
  422. p->hadAggregateLink = 0;
  423. if (pi->second->remoteVersionKnown()) {
  424. p->versionMajor = pi->second->remoteVersionMajor();
  425. p->versionMinor = pi->second->remoteVersionMinor();
  426. p->versionRev = pi->second->remoteVersionRevision();
  427. } else {
  428. p->versionMajor = -1;
  429. p->versionMinor = -1;
  430. p->versionRev = -1;
  431. }
  432. p->latency = pi->second->latency(_now);
  433. if (p->latency >= 0xffff)
  434. p->latency = -1;
  435. p->role = RR->topology->role(pi->second->identity().address());
  436. std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
  437. SharedPtr<Path> bestp(pi->second->getAppropriatePath(_now,false));
  438. p->hadAggregateLink |= pi->second->hasAggregateLink();
  439. p->pathCount = 0;
  440. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  441. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  442. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  443. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  444. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  445. p->paths[p->pathCount].expired = 0;
  446. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  447. p->paths[p->pathCount].latency = (float)(*path)->latency();
  448. p->paths[p->pathCount].packetDelayVariance = (*path)->packetDelayVariance();
  449. p->paths[p->pathCount].throughputDisturbCoeff = (*path)->throughputDisturbanceCoefficient();
  450. p->paths[p->pathCount].packetErrorRatio = (*path)->packetErrorRatio();
  451. p->paths[p->pathCount].packetLossRatio = (*path)->packetLossRatio();
  452. p->paths[p->pathCount].stability = (*path)->lastComputedStability();
  453. p->paths[p->pathCount].throughput = (*path)->meanThroughput();
  454. p->paths[p->pathCount].maxThroughput = (*path)->maxLifetimeThroughput();
  455. p->paths[p->pathCount].allocation = (float)(*path)->allocation() / (float)255;
  456. p->paths[p->pathCount].ifname = (*path)->getName();
  457. ++p->pathCount;
  458. }
  459. }
  460. return pl;
  461. }
  462. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  463. {
  464. Mutex::Lock _l(_networks_m);
  465. const SharedPtr<Network> *nw = _networks.get(nwid);
  466. if (nw) {
  467. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  468. (*nw)->externalConfig(nc);
  469. return nc;
  470. }
  471. return (ZT_VirtualNetworkConfig *)0;
  472. }
  473. ZT_VirtualNetworkList *Node::networks() const
  474. {
  475. Mutex::Lock _l(_networks_m);
  476. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  477. if (!buf)
  478. return (ZT_VirtualNetworkList *)0;
  479. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  480. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  481. nl->networkCount = 0;
  482. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  483. uint64_t *k = (uint64_t *)0;
  484. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  485. while (i.next(k,v))
  486. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  487. return nl;
  488. }
  489. void Node::freeQueryResult(void *qr)
  490. {
  491. if (qr)
  492. ::free(qr);
  493. }
  494. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  495. {
  496. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  497. Mutex::Lock _l(_directPaths_m);
  498. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  499. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  500. return 1;
  501. }
  502. }
  503. return 0;
  504. }
  505. void Node::clearLocalInterfaceAddresses()
  506. {
  507. Mutex::Lock _l(_directPaths_m);
  508. _directPaths.clear();
  509. }
  510. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  511. {
  512. try {
  513. if (RR->identity.address().toInt() != dest) {
  514. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  515. outp.append(typeId);
  516. outp.append(data,len);
  517. outp.compress();
  518. RR->sw->send(tptr,outp,true);
  519. return 1;
  520. }
  521. } catch ( ... ) {}
  522. return 0;
  523. }
  524. void Node::setNetconfMaster(void *networkControllerInstance)
  525. {
  526. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  527. if (networkControllerInstance)
  528. RR->localNetworkController->init(RR->identity,this);
  529. }
  530. /****************************************************************************/
  531. /* Node methods used only within node/ */
  532. /****************************************************************************/
  533. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  534. {
  535. if (!Path::isAddressValidForPath(remoteAddress))
  536. return false;
  537. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  538. return false;
  539. {
  540. Mutex::Lock _l(_networks_m);
  541. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  542. uint64_t *k = (uint64_t *)0;
  543. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  544. while (i.next(k,v)) {
  545. if ((*v)->hasConfig()) {
  546. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  547. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  548. return false;
  549. }
  550. }
  551. }
  552. }
  553. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  554. }
  555. uint64_t Node::prng()
  556. {
  557. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  558. uint64_t x = _prngState[0];
  559. const uint64_t y = _prngState[1];
  560. _prngState[0] = y;
  561. x ^= x << 23;
  562. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  563. _prngState[1] = z;
  564. return z + y;
  565. }
  566. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  567. {
  568. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  569. return ZT_RESULT_OK;
  570. }
  571. World Node::planet() const
  572. {
  573. return RR->topology->planet();
  574. }
  575. std::vector<World> Node::moons() const
  576. {
  577. return RR->topology->moons();
  578. }
  579. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  580. {
  581. _localControllerAuthorizations_m.lock();
  582. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  583. _localControllerAuthorizations_m.unlock();
  584. if (destination == RR->identity.address()) {
  585. SharedPtr<Network> n(network(nwid));
  586. if (!n) return;
  587. n->setConfiguration((void *)0,nc,true);
  588. } else {
  589. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  590. try {
  591. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  592. uint64_t configUpdateId = prng();
  593. if (!configUpdateId) ++configUpdateId;
  594. const unsigned int totalSize = dconf->sizeBytes();
  595. unsigned int chunkIndex = 0;
  596. while (chunkIndex < totalSize) {
  597. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  598. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  599. if (requestPacketId) {
  600. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  601. outp.append(requestPacketId);
  602. }
  603. const unsigned int sigStart = outp.size();
  604. outp.append(nwid);
  605. outp.append((uint16_t)chunkLen);
  606. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  607. outp.append((uint8_t)0); // no flags
  608. outp.append((uint64_t)configUpdateId);
  609. outp.append((uint32_t)totalSize);
  610. outp.append((uint32_t)chunkIndex);
  611. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  612. outp.append((uint8_t)1);
  613. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  614. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  615. outp.compress();
  616. RR->sw->send((void *)0,outp,true);
  617. chunkIndex += chunkLen;
  618. }
  619. }
  620. delete dconf;
  621. } catch ( ... ) {
  622. delete dconf;
  623. throw;
  624. }
  625. }
  626. }
  627. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  628. {
  629. if (destination == RR->identity.address()) {
  630. SharedPtr<Network> n(network(rev.networkId()));
  631. if (!n) return;
  632. n->addCredential((void *)0,RR->identity.address(),rev);
  633. } else {
  634. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  635. outp.append((uint8_t)0x00);
  636. outp.append((uint16_t)0);
  637. outp.append((uint16_t)0);
  638. outp.append((uint16_t)1);
  639. rev.serialize(outp);
  640. outp.append((uint16_t)0);
  641. RR->sw->send((void *)0,outp,true);
  642. }
  643. }
  644. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  645. {
  646. if (destination == RR->identity.address()) {
  647. SharedPtr<Network> n(network(nwid));
  648. if (!n) return;
  649. switch(errorCode) {
  650. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  651. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  652. n->setNotFound();
  653. break;
  654. case NetworkController::NC_ERROR_ACCESS_DENIED:
  655. n->setAccessDenied();
  656. break;
  657. default: break;
  658. }
  659. } else if (requestPacketId) {
  660. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  661. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  662. outp.append(requestPacketId);
  663. switch(errorCode) {
  664. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  665. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  666. default:
  667. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  668. break;
  669. case NetworkController::NC_ERROR_ACCESS_DENIED:
  670. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  671. break;
  672. }
  673. outp.append(nwid);
  674. RR->sw->send((void *)0,outp,true);
  675. } // else we can't send an ERROR() in response to nothing, so discard
  676. }
  677. } // namespace ZeroTier
  678. /****************************************************************************/
  679. /* CAPI bindings */
  680. /****************************************************************************/
  681. extern "C" {
  682. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  683. {
  684. *node = (ZT_Node *)0;
  685. try {
  686. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  687. return ZT_RESULT_OK;
  688. } catch (std::bad_alloc &exc) {
  689. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  690. } catch (std::runtime_error &exc) {
  691. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  692. } catch ( ... ) {
  693. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  694. }
  695. }
  696. void ZT_Node_delete(ZT_Node *node)
  697. {
  698. try {
  699. delete (reinterpret_cast<ZeroTier::Node *>(node));
  700. } catch ( ... ) {}
  701. }
  702. enum ZT_ResultCode ZT_Node_processWirePacket(
  703. ZT_Node *node,
  704. void *tptr,
  705. int64_t now,
  706. int64_t localSocket,
  707. const struct sockaddr_storage *remoteAddress,
  708. const void *packetData,
  709. unsigned int packetLength,
  710. volatile int64_t *nextBackgroundTaskDeadline)
  711. {
  712. try {
  713. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  714. } catch (std::bad_alloc &exc) {
  715. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  716. } catch ( ... ) {
  717. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  718. }
  719. }
  720. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  721. ZT_Node *node,
  722. void *tptr,
  723. int64_t now,
  724. uint64_t nwid,
  725. uint64_t sourceMac,
  726. uint64_t destMac,
  727. unsigned int etherType,
  728. unsigned int vlanId,
  729. const void *frameData,
  730. unsigned int frameLength,
  731. volatile int64_t *nextBackgroundTaskDeadline)
  732. {
  733. try {
  734. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  735. } catch (std::bad_alloc &exc) {
  736. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  737. } catch ( ... ) {
  738. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  739. }
  740. }
  741. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  742. {
  743. try {
  744. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  745. } catch (std::bad_alloc &exc) {
  746. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  747. } catch ( ... ) {
  748. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  749. }
  750. }
  751. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  752. {
  753. try {
  754. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  755. } catch (std::bad_alloc &exc) {
  756. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  757. } catch ( ... ) {
  758. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  759. }
  760. }
  761. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  762. {
  763. try {
  764. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  765. } catch (std::bad_alloc &exc) {
  766. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  767. } catch ( ... ) {
  768. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  769. }
  770. }
  771. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  772. {
  773. try {
  774. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  775. } catch (std::bad_alloc &exc) {
  776. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  777. } catch ( ... ) {
  778. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  779. }
  780. }
  781. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  782. {
  783. try {
  784. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  785. } catch (std::bad_alloc &exc) {
  786. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  787. } catch ( ... ) {
  788. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  789. }
  790. }
  791. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  792. {
  793. try {
  794. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  795. } catch ( ... ) {
  796. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  797. }
  798. }
  799. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  800. {
  801. try {
  802. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  803. } catch ( ... ) {
  804. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  805. }
  806. }
  807. uint64_t ZT_Node_address(ZT_Node *node)
  808. {
  809. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  810. }
  811. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  812. {
  813. try {
  814. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  815. } catch ( ... ) {}
  816. }
  817. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  818. {
  819. try {
  820. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  821. } catch ( ... ) {
  822. return (ZT_PeerList *)0;
  823. }
  824. }
  825. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  826. {
  827. try {
  828. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  829. } catch ( ... ) {
  830. return (ZT_VirtualNetworkConfig *)0;
  831. }
  832. }
  833. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  834. {
  835. try {
  836. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  837. } catch ( ... ) {
  838. return (ZT_VirtualNetworkList *)0;
  839. }
  840. }
  841. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  842. {
  843. try {
  844. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  845. } catch ( ... ) {}
  846. }
  847. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  848. {
  849. try {
  850. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  851. } catch ( ... ) {
  852. return 0;
  853. }
  854. }
  855. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  856. {
  857. try {
  858. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  859. } catch ( ... ) {}
  860. }
  861. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  862. {
  863. try {
  864. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  865. } catch ( ... ) {
  866. return 0;
  867. }
  868. }
  869. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  870. {
  871. try {
  872. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  873. } catch ( ... ) {}
  874. }
  875. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  876. {
  877. try {
  878. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  879. } catch ( ... ) {
  880. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  881. }
  882. }
  883. void ZT_version(int *major,int *minor,int *revision)
  884. {
  885. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  886. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  887. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  888. }
  889. } // extern "C"