Node.cpp 31 KB

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