Node.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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: 2024-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. }
  459. }
  460. return pl;
  461. }
  462. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  463. {
  464. Mutex::Lock _l(_networks_m);
  465. const SharedPtr<Network> *nw = _networks.get(nwid);
  466. if (nw) {
  467. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  468. (*nw)->externalConfig(nc);
  469. return nc;
  470. }
  471. return (ZT_VirtualNetworkConfig *)0;
  472. }
  473. ZT_VirtualNetworkList *Node::networks() const
  474. {
  475. Mutex::Lock _l(_networks_m);
  476. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  477. if (!buf)
  478. return (ZT_VirtualNetworkList *)0;
  479. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  480. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  481. nl->networkCount = 0;
  482. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  483. uint64_t *k = (uint64_t *)0;
  484. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  485. while (i.next(k,v))
  486. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  487. return nl;
  488. }
  489. void Node::freeQueryResult(void *qr)
  490. {
  491. if (qr)
  492. ::free(qr);
  493. }
  494. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  495. {
  496. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  497. Mutex::Lock _l(_directPaths_m);
  498. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  499. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  500. return 1;
  501. }
  502. }
  503. return 0;
  504. }
  505. void Node::clearLocalInterfaceAddresses()
  506. {
  507. Mutex::Lock _l(_directPaths_m);
  508. _directPaths.clear();
  509. }
  510. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  511. {
  512. try {
  513. if (RR->identity.address().toInt() != dest) {
  514. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  515. outp.append(typeId);
  516. outp.append(data,len);
  517. outp.compress();
  518. RR->sw->send(tptr,outp,true);
  519. return 1;
  520. }
  521. } catch ( ... ) {}
  522. return 0;
  523. }
  524. void Node::setNetconfMaster(void *networkControllerInstance)
  525. {
  526. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  527. if (networkControllerInstance)
  528. RR->localNetworkController->init(RR->identity,this);
  529. }
  530. /****************************************************************************/
  531. /* Node methods used only within node/ */
  532. /****************************************************************************/
  533. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  534. {
  535. if (!Path::isAddressValidForPath(remoteAddress))
  536. return false;
  537. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  538. return false;
  539. {
  540. Mutex::Lock _l(_networks_m);
  541. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  542. uint64_t *k = (uint64_t *)0;
  543. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  544. while (i.next(k,v)) {
  545. if ((*v)->hasConfig()) {
  546. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  547. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  548. return false;
  549. }
  550. }
  551. }
  552. }
  553. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  554. }
  555. uint64_t Node::prng()
  556. {
  557. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  558. uint64_t x = _prngState[0];
  559. const uint64_t y = _prngState[1];
  560. _prngState[0] = y;
  561. x ^= x << 23;
  562. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  563. _prngState[1] = z;
  564. return z + y;
  565. }
  566. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  567. {
  568. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  569. return ZT_RESULT_OK;
  570. }
  571. World Node::planet() const
  572. {
  573. return RR->topology->planet();
  574. }
  575. std::vector<World> Node::moons() const
  576. {
  577. return RR->topology->moons();
  578. }
  579. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  580. {
  581. _localControllerAuthorizations_m.lock();
  582. _localControllerAuthorizations[_LocalControllerAuth(nwid,destination)] = now();
  583. _localControllerAuthorizations_m.unlock();
  584. if (destination == RR->identity.address()) {
  585. SharedPtr<Network> n(network(nwid));
  586. if (!n) return;
  587. n->setConfiguration((void *)0,nc,true);
  588. } else {
  589. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  590. try {
  591. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  592. uint64_t configUpdateId = prng();
  593. if (!configUpdateId) ++configUpdateId;
  594. const unsigned int totalSize = dconf->sizeBytes();
  595. unsigned int chunkIndex = 0;
  596. while (chunkIndex < totalSize) {
  597. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  598. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  599. if (requestPacketId) {
  600. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  601. outp.append(requestPacketId);
  602. }
  603. const unsigned int sigStart = outp.size();
  604. outp.append(nwid);
  605. outp.append((uint16_t)chunkLen);
  606. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  607. outp.append((uint8_t)0); // no flags
  608. outp.append((uint64_t)configUpdateId);
  609. outp.append((uint32_t)totalSize);
  610. outp.append((uint32_t)chunkIndex);
  611. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  612. outp.append((uint8_t)1);
  613. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  614. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  615. outp.compress();
  616. RR->sw->send((void *)0,outp,true);
  617. chunkIndex += chunkLen;
  618. }
  619. }
  620. delete dconf;
  621. } catch ( ... ) {
  622. delete dconf;
  623. throw;
  624. }
  625. }
  626. }
  627. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  628. {
  629. if (destination == RR->identity.address()) {
  630. SharedPtr<Network> n(network(rev.networkId()));
  631. if (!n) return;
  632. n->addCredential((void *)0,RR->identity.address(),rev);
  633. } else {
  634. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  635. outp.append((uint8_t)0x00);
  636. outp.append((uint16_t)0);
  637. outp.append((uint16_t)0);
  638. outp.append((uint16_t)1);
  639. rev.serialize(outp);
  640. outp.append((uint16_t)0);
  641. RR->sw->send((void *)0,outp,true);
  642. }
  643. }
  644. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  645. {
  646. if (destination == RR->identity.address()) {
  647. SharedPtr<Network> n(network(nwid));
  648. if (!n) return;
  649. switch(errorCode) {
  650. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  651. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  652. n->setNotFound();
  653. break;
  654. case NetworkController::NC_ERROR_ACCESS_DENIED:
  655. n->setAccessDenied();
  656. break;
  657. default: break;
  658. }
  659. } else if (requestPacketId) {
  660. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  661. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  662. outp.append(requestPacketId);
  663. switch(errorCode) {
  664. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  665. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  666. default:
  667. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  668. break;
  669. case NetworkController::NC_ERROR_ACCESS_DENIED:
  670. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  671. break;
  672. }
  673. outp.append(nwid);
  674. RR->sw->send((void *)0,outp,true);
  675. } // else we can't send an ERROR() in response to nothing, so discard
  676. }
  677. } // namespace ZeroTier
  678. /****************************************************************************/
  679. /* CAPI bindings */
  680. /****************************************************************************/
  681. extern "C" {
  682. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  683. {
  684. *node = (ZT_Node *)0;
  685. try {
  686. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  687. return ZT_RESULT_OK;
  688. } catch (std::bad_alloc &exc) {
  689. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  690. } catch (std::runtime_error &exc) {
  691. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  692. } catch ( ... ) {
  693. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  694. }
  695. }
  696. void ZT_Node_delete(ZT_Node *node)
  697. {
  698. try {
  699. delete (reinterpret_cast<ZeroTier::Node *>(node));
  700. } catch ( ... ) {}
  701. }
  702. enum ZT_ResultCode ZT_Node_processWirePacket(
  703. ZT_Node *node,
  704. void *tptr,
  705. int64_t now,
  706. int64_t localSocket,
  707. const struct sockaddr_storage *remoteAddress,
  708. const void *packetData,
  709. unsigned int packetLength,
  710. volatile int64_t *nextBackgroundTaskDeadline)
  711. {
  712. try {
  713. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  714. } catch (std::bad_alloc &exc) {
  715. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  716. } catch ( ... ) {
  717. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  718. }
  719. }
  720. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  721. ZT_Node *node,
  722. void *tptr,
  723. int64_t now,
  724. uint64_t nwid,
  725. uint64_t sourceMac,
  726. uint64_t destMac,
  727. unsigned int etherType,
  728. unsigned int vlanId,
  729. const void *frameData,
  730. unsigned int frameLength,
  731. volatile int64_t *nextBackgroundTaskDeadline)
  732. {
  733. try {
  734. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  735. } catch (std::bad_alloc &exc) {
  736. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  737. } catch ( ... ) {
  738. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  739. }
  740. }
  741. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  742. {
  743. try {
  744. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  745. } catch (std::bad_alloc &exc) {
  746. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  747. } catch ( ... ) {
  748. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  749. }
  750. }
  751. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  752. {
  753. try {
  754. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  755. } catch (std::bad_alloc &exc) {
  756. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  757. } catch ( ... ) {
  758. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  759. }
  760. }
  761. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  762. {
  763. try {
  764. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  765. } catch (std::bad_alloc &exc) {
  766. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  767. } catch ( ... ) {
  768. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  769. }
  770. }
  771. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  772. {
  773. try {
  774. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  775. } catch (std::bad_alloc &exc) {
  776. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  777. } catch ( ... ) {
  778. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  779. }
  780. }
  781. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  782. {
  783. try {
  784. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  785. } catch (std::bad_alloc &exc) {
  786. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  787. } catch ( ... ) {
  788. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  789. }
  790. }
  791. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  792. {
  793. try {
  794. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  795. } catch ( ... ) {
  796. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  797. }
  798. }
  799. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  800. {
  801. try {
  802. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  803. } catch ( ... ) {
  804. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  805. }
  806. }
  807. uint64_t ZT_Node_address(ZT_Node *node)
  808. {
  809. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  810. }
  811. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  812. {
  813. try {
  814. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  815. } catch ( ... ) {}
  816. }
  817. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  818. {
  819. try {
  820. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  821. } catch ( ... ) {
  822. return (ZT_PeerList *)0;
  823. }
  824. }
  825. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  826. {
  827. try {
  828. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  829. } catch ( ... ) {
  830. return (ZT_VirtualNetworkConfig *)0;
  831. }
  832. }
  833. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  834. {
  835. try {
  836. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  837. } catch ( ... ) {
  838. return (ZT_VirtualNetworkList *)0;
  839. }
  840. }
  841. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  842. {
  843. try {
  844. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  845. } catch ( ... ) {}
  846. }
  847. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  848. {
  849. try {
  850. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  851. } catch ( ... ) {
  852. return 0;
  853. }
  854. }
  855. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  856. {
  857. try {
  858. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  859. } catch ( ... ) {}
  860. }
  861. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  862. {
  863. try {
  864. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  865. } catch ( ... ) {
  866. return 0;
  867. }
  868. }
  869. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  870. {
  871. try {
  872. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  873. } catch ( ... ) {}
  874. }
  875. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  876. {
  877. try {
  878. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  879. } catch ( ... ) {
  880. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  881. }
  882. }
  883. void ZT_version(int *major,int *minor,int *revision)
  884. {
  885. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  886. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  887. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  888. }
  889. } // extern "C"