Node.cpp 32 KB

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