Node.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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(Bond) + (((sizeof(Bond) & 0xf) != 0) ? (16 - (sizeof(Bond) & 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) Bond(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->~Bond();
  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->~Bond();
  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. // Process background bond tasks
  229. unsigned long bondCheckInterval = ZT_PING_CHECK_INVERVAL;
  230. if (RR->bc->inUse()) {
  231. bondCheckInterval = std::max(RR->bc->minReqMonitorInterval(), ZT_CORE_TIMER_TASK_GRANULARITY);
  232. if ((now - _lastGratuitousPingCheck) >= ZT_CORE_TIMER_TASK_GRANULARITY) {
  233. _lastGratuitousPingCheck = now;
  234. RR->bc->processBackgroundTasks(tptr, now);
  235. }
  236. }
  237. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  238. const int64_t timeSinceLastPingCheck = now - _lastPingCheck;
  239. if (timeSinceLastPingCheck >= timeUntilNextPingCheck) {
  240. try {
  241. _lastPingCheck = now;
  242. // Get designated VL1 upstreams
  243. Hashtable< Address,std::vector<InetAddress> > alwaysContact;
  244. RR->topology->getUpstreamsToContact(alwaysContact);
  245. // Uncomment to dump stats
  246. /*
  247. for(unsigned int i=0;i<32;i++) {
  248. if (_stats.inVerbCounts[i] > 0)
  249. printf("%.2x\t%12lld %lld\n",i,(unsigned long long)_stats.inVerbCounts[i],(unsigned long long)_stats.inVerbBytes[i]);
  250. }
  251. printf("\n");
  252. */
  253. // Check last receive time on designated upstreams to see if we seem to be online
  254. int64_t lastReceivedFromUpstream = 0;
  255. {
  256. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  257. Address *upstreamAddress = (Address *)0;
  258. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  259. while (i.next(upstreamAddress,upstreamStableEndpoints)) {
  260. SharedPtr<Peer> p(RR->topology->getPeerNoCache(*upstreamAddress));
  261. if (p)
  262. lastReceivedFromUpstream = std::max(p->lastReceive(),lastReceivedFromUpstream);
  263. }
  264. }
  265. // Clean up any old local controller auth memorizations.
  266. {
  267. _localControllerAuthorizations_m.lock();
  268. Hashtable< _LocalControllerAuth,int64_t >::Iterator i(_localControllerAuthorizations);
  269. _LocalControllerAuth *k = (_LocalControllerAuth *)0;
  270. int64_t *v = (int64_t *)0;
  271. while (i.next(k,v)) {
  272. if ((*v - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  273. _localControllerAuthorizations.erase(*k);
  274. }
  275. _localControllerAuthorizations_m.unlock();
  276. }
  277. // Get peers we should stay connected to according to network configs
  278. // Also get networks and whether they need config so we only have to do one pass over networks
  279. std::vector< std::pair< SharedPtr<Network>,bool > > networkConfigNeeded;
  280. {
  281. Mutex::Lock l(_networks_m);
  282. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  283. uint64_t *nwid = (uint64_t *)0;
  284. SharedPtr<Network> *network = (SharedPtr<Network> *)0;
  285. while (i.next(nwid,network)) {
  286. (*network)->config().alwaysContactAddresses(alwaysContact);
  287. networkConfigNeeded.push_back( std::pair< SharedPtr<Network>,bool >(*network,(((now - (*network)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!(*network)->hasConfig()))) );
  288. }
  289. }
  290. // Ping active peers, upstreams, and others that we should always contact
  291. _PingPeersThatNeedPing pfunc(RR,tptr,alwaysContact,now);
  292. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  293. // Run WHOIS to create Peer for alwaysContact addresses that could not be contacted
  294. {
  295. Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
  296. Address *upstreamAddress = (Address *)0;
  297. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  298. while (i.next(upstreamAddress,upstreamStableEndpoints))
  299. RR->sw->requestWhois(tptr,now,*upstreamAddress);
  300. }
  301. // Refresh network config or broadcast network updates to members as needed
  302. for(std::vector< std::pair< SharedPtr<Network>,bool > >::const_iterator n(networkConfigNeeded.begin());n!=networkConfigNeeded.end();++n) {
  303. if (n->second)
  304. n->first->requestConfiguration(tptr);
  305. n->first->sendUpdatesToMembers(tptr);
  306. }
  307. // Update online status, post status change as event
  308. const bool oldOnline = _online;
  309. _online = (((now - lastReceivedFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amUpstream()));
  310. if (oldOnline != _online)
  311. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  312. } catch ( ... ) {
  313. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  314. }
  315. } else {
  316. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  317. }
  318. if ((now - _lastMemoizedTraceSettings) >= (ZT_HOUSEKEEPING_PERIOD / 4)) {
  319. _lastMemoizedTraceSettings = now;
  320. RR->t->updateMemoizedSettings();
  321. }
  322. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  323. _lastHousekeepingRun = now;
  324. try {
  325. RR->topology->doPeriodicTasks(tptr,now);
  326. RR->sa->clean(now);
  327. RR->mc->clean(now);
  328. } catch ( ... ) {
  329. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  330. }
  331. }
  332. try {
  333. *nextBackgroundTaskDeadline = now + (int64_t)std::max(std::min(bondCheckInterval,std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now))),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  334. } catch ( ... ) {
  335. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  336. }
  337. return ZT_RESULT_OK;
  338. }
  339. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  340. {
  341. Mutex::Lock _l(_networks_m);
  342. SharedPtr<Network> &nw = _networks[nwid];
  343. if (!nw)
  344. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  345. return ZT_RESULT_OK;
  346. }
  347. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  348. {
  349. ZT_VirtualNetworkConfig ctmp;
  350. void **nUserPtr = (void **)0;
  351. {
  352. Mutex::Lock _l(_networks_m);
  353. SharedPtr<Network> *nw = _networks.get(nwid);
  354. RR->sw->removeNetworkQoSControlBlock(nwid);
  355. if (!nw)
  356. return ZT_RESULT_OK;
  357. if (uptr)
  358. *uptr = (*nw)->userPtr();
  359. (*nw)->externalConfig(&ctmp);
  360. (*nw)->destroy();
  361. nUserPtr = (*nw)->userPtr();
  362. }
  363. if (nUserPtr)
  364. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  365. {
  366. Mutex::Lock _l(_networks_m);
  367. _networks.erase(nwid);
  368. }
  369. uint64_t tmp[2];
  370. tmp[0] = nwid; tmp[1] = 0;
  371. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  372. return ZT_RESULT_OK;
  373. }
  374. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  375. {
  376. SharedPtr<Network> nw(this->network(nwid));
  377. if (nw) {
  378. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  379. return ZT_RESULT_OK;
  380. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  381. }
  382. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  383. {
  384. SharedPtr<Network> nw(this->network(nwid));
  385. if (nw) {
  386. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  387. return ZT_RESULT_OK;
  388. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  389. }
  390. ZT_ResultCode Node::orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  391. {
  392. RR->topology->addMoon(tptr,moonWorldId,Address(moonSeed));
  393. return ZT_RESULT_OK;
  394. }
  395. ZT_ResultCode Node::deorbit(void *tptr,uint64_t moonWorldId)
  396. {
  397. RR->topology->removeMoon(tptr,moonWorldId);
  398. return ZT_RESULT_OK;
  399. }
  400. uint64_t Node::address() const
  401. {
  402. return RR->identity.address().toInt();
  403. }
  404. void Node::status(ZT_NodeStatus *status) const
  405. {
  406. status->address = RR->identity.address().toInt();
  407. status->publicIdentity = RR->publicIdentityStr;
  408. status->secretIdentity = RR->secretIdentityStr;
  409. status->online = _online ? 1 : 0;
  410. }
  411. ZT_PeerList *Node::peers() const
  412. {
  413. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  414. std::sort(peers.begin(),peers.end());
  415. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  416. if (!buf)
  417. return (ZT_PeerList *)0;
  418. ZT_PeerList *pl = (ZT_PeerList *)buf;
  419. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  420. pl->peerCount = 0;
  421. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  422. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  423. p->address = pi->second->address().toInt();
  424. p->isBonded = 0;
  425. if (pi->second->remoteVersionKnown()) {
  426. p->versionMajor = pi->second->remoteVersionMajor();
  427. p->versionMinor = pi->second->remoteVersionMinor();
  428. p->versionRev = pi->second->remoteVersionRevision();
  429. } else {
  430. p->versionMajor = -1;
  431. p->versionMinor = -1;
  432. p->versionRev = -1;
  433. }
  434. p->latency = pi->second->latency(_now);
  435. if (p->latency >= 0xffff)
  436. p->latency = -1;
  437. p->role = RR->topology->role(pi->second->identity().address());
  438. std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
  439. SharedPtr<Path> bestp(pi->second->getAppropriatePath(_now,false));
  440. p->pathCount = 0;
  441. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  442. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  443. p->paths[p->pathCount].localSocket = (*path)->localSocket();
  444. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  445. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  446. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  447. p->paths[p->pathCount].expired = 0;
  448. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  449. p->paths[p->pathCount].scope = (*path)->ipScope();
  450. ++p->pathCount;
  451. }
  452. if (pi->second->bond()) {
  453. p->isBonded = pi->second->bond();
  454. p->bondingPolicy = pi->second->bond()->policy();
  455. p->isHealthy = pi->second->bond()->isHealthy();
  456. p->numAliveLinks = pi->second->bond()->getNumAliveLinks();
  457. p->numTotalLinks = pi->second->bond()->getNumTotalLinks();
  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, const void *errorData, unsigned int errorDataSize)
  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(nullptr);
  653. break;
  654. case NetworkController::NC_ERROR_ACCESS_DENIED:
  655. n->setAccessDenied(nullptr);
  656. break;
  657. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED: {
  658. fprintf(stderr, "\n\nGot auth required\n\n");
  659. break;
  660. }
  661. default: break;
  662. }
  663. } else if (requestPacketId) {
  664. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  665. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  666. outp.append(requestPacketId);
  667. switch(errorCode) {
  668. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  669. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  670. default:
  671. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  672. break;
  673. case NetworkController::NC_ERROR_ACCESS_DENIED:
  674. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  675. break;
  676. case NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED:
  677. outp.append((unsigned char)Packet::ERROR_NETWORK_AUTHENTICATION_REQUIRED);
  678. break;
  679. }
  680. outp.append(nwid);
  681. if ((errorData)&&(errorDataSize > 0)&&(errorDataSize <= 0xffff)) {
  682. outp.append((uint16_t)errorDataSize);
  683. outp.append(errorData, errorDataSize);
  684. }
  685. RR->sw->send((void *)0,outp,true);
  686. } // else we can't send an ERROR() in response to nothing, so discard
  687. }
  688. } // namespace ZeroTier
  689. /****************************************************************************/
  690. /* CAPI bindings */
  691. /****************************************************************************/
  692. extern "C" {
  693. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  694. {
  695. *node = (ZT_Node *)0;
  696. try {
  697. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  698. return ZT_RESULT_OK;
  699. } catch (std::bad_alloc &exc) {
  700. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  701. } catch (std::runtime_error &exc) {
  702. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  703. } catch ( ... ) {
  704. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  705. }
  706. }
  707. void ZT_Node_delete(ZT_Node *node)
  708. {
  709. try {
  710. delete (reinterpret_cast<ZeroTier::Node *>(node));
  711. } catch ( ... ) {}
  712. }
  713. enum ZT_ResultCode ZT_Node_processWirePacket(
  714. ZT_Node *node,
  715. void *tptr,
  716. int64_t now,
  717. int64_t localSocket,
  718. const struct sockaddr_storage *remoteAddress,
  719. const void *packetData,
  720. unsigned int packetLength,
  721. volatile int64_t *nextBackgroundTaskDeadline)
  722. {
  723. try {
  724. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  725. } catch (std::bad_alloc &exc) {
  726. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  727. } catch ( ... ) {
  728. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  729. }
  730. }
  731. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  732. ZT_Node *node,
  733. void *tptr,
  734. int64_t now,
  735. uint64_t nwid,
  736. uint64_t sourceMac,
  737. uint64_t destMac,
  738. unsigned int etherType,
  739. unsigned int vlanId,
  740. const void *frameData,
  741. unsigned int frameLength,
  742. volatile int64_t *nextBackgroundTaskDeadline)
  743. {
  744. try {
  745. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  746. } catch (std::bad_alloc &exc) {
  747. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  748. } catch ( ... ) {
  749. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  750. }
  751. }
  752. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  753. {
  754. try {
  755. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  756. } catch (std::bad_alloc &exc) {
  757. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  758. } catch ( ... ) {
  759. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  760. }
  761. }
  762. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  763. {
  764. try {
  765. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  766. } catch (std::bad_alloc &exc) {
  767. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  768. } catch ( ... ) {
  769. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  770. }
  771. }
  772. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  773. {
  774. try {
  775. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  776. } catch (std::bad_alloc &exc) {
  777. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  778. } catch ( ... ) {
  779. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  780. }
  781. }
  782. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  783. {
  784. try {
  785. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  786. } catch (std::bad_alloc &exc) {
  787. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  788. } catch ( ... ) {
  789. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  790. }
  791. }
  792. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  793. {
  794. try {
  795. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  796. } catch (std::bad_alloc &exc) {
  797. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  798. } catch ( ... ) {
  799. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  800. }
  801. }
  802. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  803. {
  804. try {
  805. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  806. } catch ( ... ) {
  807. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  808. }
  809. }
  810. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  811. {
  812. try {
  813. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  814. } catch ( ... ) {
  815. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  816. }
  817. }
  818. uint64_t ZT_Node_address(ZT_Node *node)
  819. {
  820. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  821. }
  822. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  823. {
  824. try {
  825. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  826. } catch ( ... ) {}
  827. }
  828. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  829. {
  830. try {
  831. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  832. } catch ( ... ) {
  833. return (ZT_PeerList *)0;
  834. }
  835. }
  836. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  837. {
  838. try {
  839. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  840. } catch ( ... ) {
  841. return (ZT_VirtualNetworkConfig *)0;
  842. }
  843. }
  844. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  845. {
  846. try {
  847. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  848. } catch ( ... ) {
  849. return (ZT_VirtualNetworkList *)0;
  850. }
  851. }
  852. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  853. {
  854. try {
  855. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  856. } catch ( ... ) {}
  857. }
  858. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  859. {
  860. try {
  861. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  862. } catch ( ... ) {
  863. return 0;
  864. }
  865. }
  866. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  867. {
  868. try {
  869. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  870. } catch ( ... ) {}
  871. }
  872. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  873. {
  874. try {
  875. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  876. } catch ( ... ) {
  877. return 0;
  878. }
  879. }
  880. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  881. {
  882. try {
  883. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  884. } catch ( ... ) {}
  885. }
  886. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  887. {
  888. try {
  889. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  890. } catch ( ... ) {
  891. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  892. }
  893. }
  894. void ZT_version(int *major,int *minor,int *revision)
  895. {
  896. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  897. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  898. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  899. }
  900. } // extern "C"