Node.cpp 29 KB

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