Node.cpp 30 KB

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