Node.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. ZT_FAST_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. for(unsigned int i=0;i<32;i++) {
  245. if (_stats.inVerbCounts[i] > 0)
  246. printf("%.2x\t%12lld %lld\n",i,(unsigned long long)_stats.inVerbCounts[i],(unsigned long long)_stats.inVerbBytes[i]);
  247. }
  248. printf("\n");
  249. // Check last receive time on designated upstreams to see if we seem to be online
  250. int64_t lastReceivedFromUpstream = 0;
  251. {
  252. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  253. Address *upstreamAddress = (Address *)0;
  254. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  255. while (i.next(upstreamAddress,upstreamStableEndpoints)) {
  256. SharedPtr<Peer> p(RR->topology->getPeerNoCache(*upstreamAddress));
  257. if (p)
  258. lastReceivedFromUpstream = std::max(p->lastReceive(),lastReceivedFromUpstream);
  259. }
  260. }
  261. // Clean up any old local controller auth memorizations.
  262. {
  263. _localControllerAuthorizations_m.lock();
  264. Hashtable< _LocalControllerAuth,int64_t >::Iterator i(_localControllerAuthorizations);
  265. _LocalControllerAuth *k = (_LocalControllerAuth *)0;
  266. int64_t *v = (int64_t *)0;
  267. while (i.next(k,v)) {
  268. if ((*v - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  269. _localControllerAuthorizations.erase(*k);
  270. }
  271. _localControllerAuthorizations_m.unlock();
  272. }
  273. // Get peers we should stay connected to according to network configs
  274. // Also get networks and whether they need config so we only have to do one pass over networks
  275. std::vector< std::pair< SharedPtr<Network>,bool > > networkConfigNeeded;
  276. {
  277. Mutex::Lock l(_networks_m);
  278. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  279. uint64_t *nwid = (uint64_t *)0;
  280. SharedPtr<Network> *network = (SharedPtr<Network> *)0;
  281. while (i.next(nwid,network)) {
  282. (*network)->config().alwaysContactAddresses(alwaysContact);
  283. networkConfigNeeded.push_back( std::pair< SharedPtr<Network>,bool >(*network,(((now - (*network)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!(*network)->hasConfig()))) );
  284. }
  285. }
  286. // Ping active peers, upstreams, and others that we should always contact
  287. _PingPeersThatNeedPing pfunc(RR,tptr,alwaysContact,now);
  288. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  289. // Run WHOIS to create Peer for alwaysContact addresses that could not be contacted
  290. {
  291. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  292. Address *upstreamAddress = (Address *)0;
  293. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  294. while (i.next(upstreamAddress,upstreamStableEndpoints))
  295. RR->sw->requestWhois(tptr,now,*upstreamAddress);
  296. }
  297. // Refresh network config or broadcast network updates to members as needed
  298. for(std::vector< std::pair< SharedPtr<Network>,bool > >::const_iterator n(networkConfigNeeded.begin());n!=networkConfigNeeded.end();++n) {
  299. if (n->second)
  300. n->first->requestConfiguration(tptr);
  301. n->first->sendUpdatesToMembers(tptr);
  302. }
  303. // Update online status, post status change as event
  304. const bool oldOnline = _online;
  305. _online = (((now - lastReceivedFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amUpstream()));
  306. if (oldOnline != _online)
  307. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  308. } catch ( ... ) {
  309. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  310. }
  311. } else {
  312. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  313. }
  314. if ((now - _lastMemoizedTraceSettings) >= (ZT_HOUSEKEEPING_PERIOD / 4)) {
  315. _lastMemoizedTraceSettings = now;
  316. RR->t->updateMemoizedSettings();
  317. }
  318. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  319. _lastHousekeepingRun = now;
  320. try {
  321. RR->topology->doPeriodicTasks(tptr,now);
  322. RR->sa->clean(now);
  323. RR->mc->clean(now);
  324. } catch ( ... ) {
  325. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  326. }
  327. }
  328. try {
  329. *nextBackgroundTaskDeadline = now + (int64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  330. } catch ( ... ) {
  331. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  332. }
  333. return ZT_RESULT_OK;
  334. }
  335. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  336. {
  337. Mutex::Lock _l(_networks_m);
  338. SharedPtr<Network> &nw = _networks[nwid];
  339. if (!nw)
  340. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  341. return ZT_RESULT_OK;
  342. }
  343. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  344. {
  345. ZT_VirtualNetworkConfig ctmp;
  346. void **nUserPtr = (void **)0;
  347. {
  348. Mutex::Lock _l(_networks_m);
  349. SharedPtr<Network> *nw = _networks.get(nwid);
  350. RR->sw->removeNetworkQoSControlBlock(nwid);
  351. if (!nw)
  352. return ZT_RESULT_OK;
  353. if (uptr)
  354. *uptr = (*nw)->userPtr();
  355. (*nw)->externalConfig(&ctmp);
  356. (*nw)->destroy();
  357. nUserPtr = (*nw)->userPtr();
  358. }
  359. if (nUserPtr)
  360. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  361. {
  362. Mutex::Lock _l(_networks_m);
  363. _networks.erase(nwid);
  364. }
  365. uint64_t tmp[2];
  366. tmp[0] = nwid; tmp[1] = 0;
  367. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  368. return ZT_RESULT_OK;
  369. }
  370. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  371. {
  372. SharedPtr<Network> nw(this->network(nwid));
  373. if (nw) {
  374. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  375. return ZT_RESULT_OK;
  376. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  377. }
  378. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  379. {
  380. SharedPtr<Network> nw(this->network(nwid));
  381. if (nw) {
  382. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  383. return ZT_RESULT_OK;
  384. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  385. }
  386. ZT_ResultCode Node::orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  387. {
  388. RR->topology->addMoon(tptr,moonWorldId,Address(moonSeed));
  389. return ZT_RESULT_OK;
  390. }
  391. ZT_ResultCode Node::deorbit(void *tptr,uint64_t moonWorldId)
  392. {
  393. RR->topology->removeMoon(tptr,moonWorldId);
  394. return ZT_RESULT_OK;
  395. }
  396. uint64_t Node::address() const
  397. {
  398. return RR->identity.address().toInt();
  399. }
  400. void Node::status(ZT_NodeStatus *status) const
  401. {
  402. status->address = RR->identity.address().toInt();
  403. status->publicIdentity = RR->publicIdentityStr;
  404. status->secretIdentity = RR->secretIdentityStr;
  405. status->online = _online ? 1 : 0;
  406. }
  407. ZT_PeerList *Node::peers() const
  408. {
  409. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  410. std::sort(peers.begin(),peers.end());
  411. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  412. if (!buf)
  413. return (ZT_PeerList *)0;
  414. ZT_PeerList *pl = (ZT_PeerList *)buf;
  415. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  416. pl->peerCount = 0;
  417. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  418. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  419. p->address = pi->second->address().toInt();
  420. p->hadAggregateLink = 0;
  421. if (pi->second->remoteVersionKnown()) {
  422. p->versionMajor = pi->second->remoteVersionMajor();
  423. p->versionMinor = pi->second->remoteVersionMinor();
  424. p->versionRev = pi->second->remoteVersionRevision();
  425. } else {
  426. p->versionMajor = -1;
  427. p->versionMinor = -1;
  428. p->versionRev = -1;
  429. }
  430. p->latency = pi->second->latency(_now);
  431. if (p->latency >= 0xffff)
  432. p->latency = -1;
  433. p->role = RR->topology->role(pi->second->identity().address());
  434. std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
  435. SharedPtr<Path> bestp(pi->second->getAppropriatePath(_now,false));
  436. p->hadAggregateLink |= pi->second->hasAggregateLink();
  437. p->pathCount = 0;
  438. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  439. ZT_FAST_MEMCPY(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  440. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  441. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  442. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  443. p->paths[p->pathCount].expired = 0;
  444. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  445. p->paths[p->pathCount].latency = (*path)->latency();
  446. p->paths[p->pathCount].packetDelayVariance = (*path)->packetDelayVariance();
  447. p->paths[p->pathCount].throughputDisturbCoeff = (*path)->throughputDisturbanceCoefficient();
  448. p->paths[p->pathCount].packetErrorRatio = (*path)->packetErrorRatio();
  449. p->paths[p->pathCount].packetLossRatio = (*path)->packetLossRatio();
  450. p->paths[p->pathCount].stability = (*path)->lastComputedStability();
  451. p->paths[p->pathCount].throughput = (*path)->meanThroughput();
  452. p->paths[p->pathCount].maxThroughput = (*path)->maxLifetimeThroughput();
  453. p->paths[p->pathCount].allocation = (float)(*path)->allocation() / (float)255;
  454. p->paths[p->pathCount].ifname = (*path)->getName();
  455. ++p->pathCount;
  456. }
  457. }
  458. return pl;
  459. }
  460. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  461. {
  462. Mutex::Lock _l(_networks_m);
  463. const SharedPtr<Network> *nw = _networks.get(nwid);
  464. if (nw) {
  465. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  466. (*nw)->externalConfig(nc);
  467. return nc;
  468. }
  469. return (ZT_VirtualNetworkConfig *)0;
  470. }
  471. ZT_VirtualNetworkList *Node::networks() const
  472. {
  473. Mutex::Lock _l(_networks_m);
  474. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  475. if (!buf)
  476. return (ZT_VirtualNetworkList *)0;
  477. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  478. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  479. nl->networkCount = 0;
  480. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  481. uint64_t *k = (uint64_t *)0;
  482. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  483. while (i.next(k,v))
  484. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  485. return nl;
  486. }
  487. void Node::freeQueryResult(void *qr)
  488. {
  489. if (qr)
  490. ::free(qr);
  491. }
  492. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  493. {
  494. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  495. Mutex::Lock _l(_directPaths_m);
  496. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  497. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  498. return 1;
  499. }
  500. }
  501. return 0;
  502. }
  503. void Node::clearLocalInterfaceAddresses()
  504. {
  505. Mutex::Lock _l(_directPaths_m);
  506. _directPaths.clear();
  507. }
  508. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  509. {
  510. try {
  511. if (RR->identity.address().toInt() != dest) {
  512. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  513. outp.append(typeId);
  514. outp.append(data,len);
  515. outp.compress();
  516. RR->sw->send(tptr,outp,true);
  517. return 1;
  518. }
  519. } catch ( ... ) {}
  520. return 0;
  521. }
  522. void Node::setNetconfMaster(void *networkControllerInstance)
  523. {
  524. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  525. if (networkControllerInstance)
  526. RR->localNetworkController->init(RR->identity,this);
  527. }
  528. /****************************************************************************/
  529. /* Node methods used only within node/ */
  530. /****************************************************************************/
  531. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  532. {
  533. if (!Path::isAddressValidForPath(remoteAddress))
  534. return false;
  535. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  536. return false;
  537. {
  538. Mutex::Lock _l(_networks_m);
  539. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  540. uint64_t *k = (uint64_t *)0;
  541. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  542. while (i.next(k,v)) {
  543. if ((*v)->hasConfig()) {
  544. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  545. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  546. return false;
  547. }
  548. }
  549. }
  550. }
  551. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  552. }
  553. uint64_t Node::prng()
  554. {
  555. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  556. uint64_t x = _prngState[0];
  557. const uint64_t y = _prngState[1];
  558. _prngState[0] = y;
  559. x ^= x << 23;
  560. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  561. _prngState[1] = z;
  562. return z + y;
  563. }
  564. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  565. {
  566. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  567. return ZT_RESULT_OK;
  568. }
  569. World Node::planet() const
  570. {
  571. return RR->topology->planet();
  572. }
  573. std::vector<World> Node::moons() const
  574. {
  575. return RR->topology->moons();
  576. }
  577. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  578. {
  579. _localControllerAuthorizations_m.lock();
  580. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  581. _localControllerAuthorizations_m.unlock();
  582. if (destination == RR->identity.address()) {
  583. SharedPtr<Network> n(network(nwid));
  584. if (!n) return;
  585. n->setConfiguration((void *)0,nc,true);
  586. } else {
  587. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  588. try {
  589. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  590. uint64_t configUpdateId = prng();
  591. if (!configUpdateId) ++configUpdateId;
  592. const unsigned int totalSize = dconf->sizeBytes();
  593. unsigned int chunkIndex = 0;
  594. while (chunkIndex < totalSize) {
  595. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  596. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  597. if (requestPacketId) {
  598. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  599. outp.append(requestPacketId);
  600. }
  601. const unsigned int sigStart = outp.size();
  602. outp.append(nwid);
  603. outp.append((uint16_t)chunkLen);
  604. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  605. outp.append((uint8_t)0); // no flags
  606. outp.append((uint64_t)configUpdateId);
  607. outp.append((uint32_t)totalSize);
  608. outp.append((uint32_t)chunkIndex);
  609. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  610. outp.append((uint8_t)1);
  611. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  612. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  613. outp.compress();
  614. RR->sw->send((void *)0,outp,true);
  615. chunkIndex += chunkLen;
  616. }
  617. }
  618. delete dconf;
  619. } catch ( ... ) {
  620. delete dconf;
  621. throw;
  622. }
  623. }
  624. }
  625. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  626. {
  627. if (destination == RR->identity.address()) {
  628. SharedPtr<Network> n(network(rev.networkId()));
  629. if (!n) return;
  630. n->addCredential((void *)0,RR->identity.address(),rev);
  631. } else {
  632. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  633. outp.append((uint8_t)0x00);
  634. outp.append((uint16_t)0);
  635. outp.append((uint16_t)0);
  636. outp.append((uint16_t)1);
  637. rev.serialize(outp);
  638. outp.append((uint16_t)0);
  639. RR->sw->send((void *)0,outp,true);
  640. }
  641. }
  642. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  643. {
  644. if (destination == RR->identity.address()) {
  645. SharedPtr<Network> n(network(nwid));
  646. if (!n) return;
  647. switch(errorCode) {
  648. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  649. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  650. n->setNotFound();
  651. break;
  652. case NetworkController::NC_ERROR_ACCESS_DENIED:
  653. n->setAccessDenied();
  654. break;
  655. default: break;
  656. }
  657. } else if (requestPacketId) {
  658. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  659. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  660. outp.append(requestPacketId);
  661. switch(errorCode) {
  662. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  663. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  664. default:
  665. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  666. break;
  667. case NetworkController::NC_ERROR_ACCESS_DENIED:
  668. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  669. break;
  670. }
  671. outp.append(nwid);
  672. RR->sw->send((void *)0,outp,true);
  673. } // else we can't send an ERROR() in response to nothing, so discard
  674. }
  675. } // namespace ZeroTier
  676. /****************************************************************************/
  677. /* CAPI bindings */
  678. /****************************************************************************/
  679. extern "C" {
  680. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  681. {
  682. *node = (ZT_Node *)0;
  683. try {
  684. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  685. return ZT_RESULT_OK;
  686. } catch (std::bad_alloc &exc) {
  687. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  688. } catch (std::runtime_error &exc) {
  689. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  690. } catch ( ... ) {
  691. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  692. }
  693. }
  694. void ZT_Node_delete(ZT_Node *node)
  695. {
  696. try {
  697. delete (reinterpret_cast<ZeroTier::Node *>(node));
  698. } catch ( ... ) {}
  699. }
  700. enum ZT_ResultCode ZT_Node_processWirePacket(
  701. ZT_Node *node,
  702. void *tptr,
  703. int64_t now,
  704. int64_t localSocket,
  705. const struct sockaddr_storage *remoteAddress,
  706. const void *packetData,
  707. unsigned int packetLength,
  708. volatile int64_t *nextBackgroundTaskDeadline)
  709. {
  710. try {
  711. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  712. } catch (std::bad_alloc &exc) {
  713. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  714. } catch ( ... ) {
  715. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  716. }
  717. }
  718. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  719. ZT_Node *node,
  720. void *tptr,
  721. int64_t now,
  722. uint64_t nwid,
  723. uint64_t sourceMac,
  724. uint64_t destMac,
  725. unsigned int etherType,
  726. unsigned int vlanId,
  727. const void *frameData,
  728. unsigned int frameLength,
  729. volatile int64_t *nextBackgroundTaskDeadline)
  730. {
  731. try {
  732. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  733. } catch (std::bad_alloc &exc) {
  734. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  735. } catch ( ... ) {
  736. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  737. }
  738. }
  739. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  740. {
  741. try {
  742. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  743. } catch (std::bad_alloc &exc) {
  744. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  745. } catch ( ... ) {
  746. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  747. }
  748. }
  749. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  750. {
  751. try {
  752. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  753. } catch (std::bad_alloc &exc) {
  754. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  755. } catch ( ... ) {
  756. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  757. }
  758. }
  759. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  760. {
  761. try {
  762. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  763. } catch (std::bad_alloc &exc) {
  764. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  765. } catch ( ... ) {
  766. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  767. }
  768. }
  769. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  770. {
  771. try {
  772. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  773. } catch (std::bad_alloc &exc) {
  774. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  775. } catch ( ... ) {
  776. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  777. }
  778. }
  779. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  780. {
  781. try {
  782. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  783. } catch (std::bad_alloc &exc) {
  784. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  785. } catch ( ... ) {
  786. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  787. }
  788. }
  789. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  790. {
  791. try {
  792. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  793. } catch ( ... ) {
  794. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  795. }
  796. }
  797. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  798. {
  799. try {
  800. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  801. } catch ( ... ) {
  802. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  803. }
  804. }
  805. uint64_t ZT_Node_address(ZT_Node *node)
  806. {
  807. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  808. }
  809. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  810. {
  811. try {
  812. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  813. } catch ( ... ) {}
  814. }
  815. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  816. {
  817. try {
  818. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  819. } catch ( ... ) {
  820. return (ZT_PeerList *)0;
  821. }
  822. }
  823. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  824. {
  825. try {
  826. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  827. } catch ( ... ) {
  828. return (ZT_VirtualNetworkConfig *)0;
  829. }
  830. }
  831. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  832. {
  833. try {
  834. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  835. } catch ( ... ) {
  836. return (ZT_VirtualNetworkList *)0;
  837. }
  838. }
  839. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  840. {
  841. try {
  842. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  843. } catch ( ... ) {}
  844. }
  845. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  846. {
  847. try {
  848. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  849. } catch ( ... ) {
  850. return 0;
  851. }
  852. }
  853. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  854. {
  855. try {
  856. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  857. } catch ( ... ) {}
  858. }
  859. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  860. {
  861. try {
  862. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  863. } catch ( ... ) {
  864. return 0;
  865. }
  866. }
  867. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  868. {
  869. try {
  870. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  871. } catch ( ... ) {}
  872. }
  873. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  874. {
  875. try {
  876. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  877. } catch ( ... ) {
  878. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  879. }
  880. }
  881. void ZT_version(int *major,int *minor,int *revision)
  882. {
  883. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  884. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  885. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  886. }
  887. } // extern "C"