Node.cpp 32 KB

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