Node.cpp 30 KB

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