Node.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <errno.h>
  31. #include <map>
  32. #include <set>
  33. #include <utility>
  34. #include <algorithm>
  35. #include <list>
  36. #include <vector>
  37. #include <string>
  38. #ifndef _WIN32
  39. #include <fcntl.h>
  40. #include <unistd.h>
  41. #include <signal.h>
  42. #include <sys/file.h>
  43. #endif
  44. #include <openssl/sha.h>
  45. #include "Condition.hpp"
  46. #include "Node.hpp"
  47. #include "Topology.hpp"
  48. #include "Demarc.hpp"
  49. #include "Switch.hpp"
  50. #include "Utils.hpp"
  51. #include "EthernetTap.hpp"
  52. #include "Logger.hpp"
  53. #include "Constants.hpp"
  54. #include "InetAddress.hpp"
  55. #include "Pack.hpp"
  56. #include "RuntimeEnvironment.hpp"
  57. #include "NodeConfig.hpp"
  58. #include "Defaults.hpp"
  59. #include "SysEnv.hpp"
  60. #include "Network.hpp"
  61. #include "MulticastGroup.hpp"
  62. #include "Mutex.hpp"
  63. #include "Multicaster.hpp"
  64. #include "CMWC4096.hpp"
  65. #include "../version.h"
  66. namespace ZeroTier {
  67. struct _NodeImpl
  68. {
  69. RuntimeEnvironment renv;
  70. std::string reasonForTerminationStr;
  71. Node::ReasonForTermination reasonForTermination;
  72. volatile bool started;
  73. volatile bool running;
  74. volatile bool updateStatusNow;
  75. volatile bool terminateNow;
  76. // Helper used to rapidly terminate from run()
  77. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  78. {
  79. RuntimeEnvironment *_r = &renv;
  80. LOG("terminating: %s",rstr);
  81. reasonForTerminationStr = rstr;
  82. reasonForTermination = r;
  83. running = false;
  84. return r;
  85. }
  86. };
  87. Node::Node(const char *hp,const char *urlPrefix,const char *configAuthorityIdentity)
  88. throw() :
  89. _impl(new _NodeImpl)
  90. {
  91. _NodeImpl *impl = (_NodeImpl *)_impl;
  92. impl->renv.homePath = hp;
  93. impl->renv.autoconfUrlPrefix = urlPrefix;
  94. impl->renv.configAuthorityIdentityStr = configAuthorityIdentity;
  95. impl->reasonForTermination = Node::NODE_RUNNING;
  96. impl->started = false;
  97. impl->running = false;
  98. impl->updateStatusNow = false;
  99. impl->terminateNow = false;
  100. }
  101. Node::~Node()
  102. {
  103. _NodeImpl *impl = (_NodeImpl *)_impl;
  104. delete impl->renv.sysEnv;
  105. delete impl->renv.topology;
  106. delete impl->renv.sw;
  107. delete impl->renv.multicaster;
  108. delete impl->renv.demarc;
  109. delete impl->renv.nc;
  110. delete impl->renv.prng;
  111. delete impl->renv.log;
  112. delete impl;
  113. }
  114. /**
  115. * Execute node in current thread
  116. *
  117. * This does not return until the node shuts down. Shutdown may be caused
  118. * by an internally detected condition such as a new upgrade being
  119. * available or a fatal error, or it may be signaled externally using
  120. * the terminate() method.
  121. *
  122. * @return Reason for termination
  123. */
  124. Node::ReasonForTermination Node::run()
  125. throw()
  126. {
  127. _NodeImpl *impl = (_NodeImpl *)_impl;
  128. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  129. impl->started = true;
  130. impl->running = true;
  131. try {
  132. #ifdef ZT_LOG_STDOUT
  133. _r->log = new Logger((const char *)0,(const char *)0,0);
  134. #else
  135. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  136. #endif
  137. TRACE("initializing...");
  138. _r->prng = new CMWC4096();
  139. if (!_r->configAuthority.fromString(_r->configAuthorityIdentityStr))
  140. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"configuration authority identity is not valid");
  141. bool gotId = false;
  142. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  143. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  144. std::string idser;
  145. if (Utils::readFile(identitySecretPath.c_str(),idser))
  146. gotId = _r->identity.fromString(idser);
  147. if (gotId) {
  148. // Make sure identity.public matches identity.secret
  149. idser = std::string();
  150. Utils::readFile(identityPublicPath.c_str(),idser);
  151. std::string pubid(_r->identity.toString(false));
  152. if (idser != pubid) {
  153. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  154. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  155. }
  156. } else {
  157. LOG("no identity found, generating one... this might take a few seconds...");
  158. _r->identity.generate();
  159. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  160. idser = _r->identity.toString(true);
  161. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  162. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  163. idser = _r->identity.toString(false);
  164. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  165. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  166. }
  167. Utils::lockDownFile(identitySecretPath.c_str(),false);
  168. // Generate ownership verification secret, which can be presented to
  169. // a controlling web site (like ours) to prove ownership of a node and
  170. // permit its configuration to be centrally modified. When ZeroTier One
  171. // requests its config it sends a hash of this secret, and so the
  172. // config server can verify this hash to determine if the secret the
  173. // user presents is correct.
  174. std::string ovsPath(_r->homePath + ZT_PATH_SEPARATOR_S + "thisdeviceismine");
  175. if (((Utils::now() - Utils::getLastModified(ovsPath.c_str())) >= ZT_OVS_GENERATE_NEW_IF_OLDER_THAN)||(!Utils::readFile(ovsPath.c_str(),_r->ownershipVerificationSecret))) {
  176. _r->ownershipVerificationSecret = "";
  177. unsigned int securern = 0;
  178. for(unsigned int i=0;i<24;++i) {
  179. Utils::getSecureRandom(&securern,sizeof(securern));
  180. _r->ownershipVerificationSecret.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[securern % 62]);
  181. }
  182. _r->ownershipVerificationSecret.append(ZT_EOL_S);
  183. if (!Utils::writeFile(ovsPath.c_str(),_r->ownershipVerificationSecret))
  184. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write 'thisdeviceismine' (home path not writable?)");
  185. }
  186. Utils::lockDownFile(ovsPath.c_str(),false);
  187. _r->ownershipVerificationSecret = Utils::trim(_r->ownershipVerificationSecret); // trim off CR file is saved with
  188. unsigned char ovsDig[32];
  189. SHA256_CTX sha;
  190. SHA256_Init(&sha);
  191. SHA256_Update(&sha,_r->ownershipVerificationSecret.data(),_r->ownershipVerificationSecret.length());
  192. SHA256_Final(ovsDig,&sha);
  193. _r->ownershipVerificationSecretHash = Utils::base64Encode(ovsDig,32);
  194. // Create the core objects in RuntimeEnvironment: node config, demarcation
  195. // point, switch, network topology database, and system environment
  196. // watcher.
  197. _r->nc = new NodeConfig(_r,_r->autoconfUrlPrefix + _r->identity.address().toString());
  198. _r->demarc = new Demarc(_r);
  199. _r->multicaster = new Multicaster();
  200. _r->sw = new Switch(_r);
  201. _r->topology = new Topology(_r,(_r->homePath + ZT_PATH_SEPARATOR_S + "peer.db").c_str());
  202. _r->sysEnv = new SysEnv(_r);
  203. // TODO: make configurable
  204. bool boundPort = false;
  205. for(unsigned int p=ZT_DEFAULT_UDP_PORT;p<(ZT_DEFAULT_UDP_PORT + 128);++p) {
  206. if (_r->demarc->bindLocalUdp(p)) {
  207. boundPort = true;
  208. break;
  209. }
  210. }
  211. if (!boundPort)
  212. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not bind any local UDP ports");
  213. // TODO: bootstrap off network so we don't have to update code for
  214. // changes in supernodes.
  215. _r->topology->setSupernodes(ZT_DEFAULTS.supernodes);
  216. } catch (std::bad_alloc &exc) {
  217. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  218. } catch (std::runtime_error &exc) {
  219. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  220. } catch ( ... ) {
  221. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  222. }
  223. try {
  224. std::string statusPath(_r->homePath + ZT_PATH_SEPARATOR_S + "status");
  225. uint64_t lastPingCheck = 0;
  226. uint64_t lastTopologyClean = Utils::now(); // don't need to do this immediately
  227. uint64_t lastNetworkFingerprintCheck = 0;
  228. uint64_t lastAutoconfigureCheck = 0;
  229. uint64_t networkConfigurationFingerprint = _r->sysEnv->getNetworkConfigurationFingerprint();
  230. uint64_t lastMulticastCheck = 0;
  231. uint64_t lastMulticastAnnounceAll = 0;
  232. uint64_t lastStatusUpdate = 0;
  233. long lastDelayDelta = 0;
  234. LOG("%s starting version %s",_r->identity.address().toString().c_str(),versionString());
  235. while (!impl->terminateNow) {
  236. uint64_t now = Utils::now();
  237. bool pingAll = false; // set to true to force a ping of *all* known direct links
  238. // Detect sleep/wake by looking for delay loop pauses that are longer
  239. // than we intended to pause.
  240. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  241. lastNetworkFingerprintCheck = 0; // force network environment check
  242. lastMulticastCheck = 0; // force multicast group check on taps
  243. pingAll = true;
  244. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  245. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  246. }
  247. // Periodically check our network environment, sending pings out to all
  248. // our direct links if things look like we got a different address.
  249. if ((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY) {
  250. lastNetworkFingerprintCheck = now;
  251. uint64_t fp = _r->sysEnv->getNetworkConfigurationFingerprint();
  252. if (fp != networkConfigurationFingerprint) {
  253. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  254. networkConfigurationFingerprint = fp;
  255. pingAll = true;
  256. lastAutoconfigureCheck = 0; // check autoconf after network config change
  257. lastMulticastCheck = 0; // check multicast group membership after network config change
  258. _r->nc->whackAllTaps(); // call whack() on all tap devices
  259. }
  260. }
  261. if ((now - lastAutoconfigureCheck) >= ZT_AUTOCONFIGURE_CHECK_DELAY) {
  262. // It seems odd to only do this simple check every so often, but the purpose is to
  263. // delay between calls to refreshConfiguration() enough that the previous attempt
  264. // has time to either succeed or fail. Otherwise we'll block the whole loop, since
  265. // config update is guarded by a Mutex.
  266. lastAutoconfigureCheck = now;
  267. if ((now - _r->nc->lastAutoconfigure()) >= ZT_AUTOCONFIGURE_INTERVAL)
  268. _r->nc->refreshConfiguration(); // happens in background
  269. }
  270. // Periodically check for changes in our local multicast subscriptions and broadcast
  271. // those changes to peers.
  272. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  273. lastMulticastCheck = now;
  274. bool announceAll = ((now - lastMulticastAnnounceAll) >= ZT_MULTICAST_LIKE_ANNOUNCE_ALL_PERIOD);
  275. try {
  276. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  277. {
  278. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  279. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  280. if (((*nw)->updateMulticastGroups())||(announceAll))
  281. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  282. }
  283. }
  284. if (toAnnounce.size()) {
  285. _r->sw->announceMulticastGroups(toAnnounce);
  286. // Only update lastMulticastAnnounceAll if we've announced something. This keeps
  287. // the announceAll condition true during startup when there are no multicast
  288. // groups until there is at least one. Technically this shouldn't be required as
  289. // updateMulticastGroups() should return true on any change, but why not?
  290. if (announceAll)
  291. lastMulticastAnnounceAll = now;
  292. }
  293. } catch (std::exception &exc) {
  294. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  295. } catch ( ... ) {
  296. LOG("unexpected exception announcing multicast groups: (unknown)");
  297. }
  298. }
  299. if ((now - lastPingCheck) >= ZT_PING_CHECK_DELAY) {
  300. lastPingCheck = now;
  301. try {
  302. if (_r->topology->isSupernode(_r->identity.address())) {
  303. // The only difference in how supernodes behave is here: they only
  304. // actively ping each other and only passively listen for pings
  305. // from anyone else. They also don't send firewall openers, since
  306. // they're never firewalled.
  307. std::vector< SharedPtr<Peer> > sns(_r->topology->supernodePeers());
  308. for(std::vector< SharedPtr<Peer> >::const_iterator p(sns.begin());p!=sns.end();++p) {
  309. if ((now - (*p)->lastDirectSend()) > ZT_PEER_DIRECT_PING_DELAY)
  310. _r->sw->sendHELLO((*p)->address());
  311. }
  312. } else {
  313. std::vector< SharedPtr<Peer> > needPing,needFirewallOpener;
  314. if (pingAll) {
  315. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(needPing));
  316. } else {
  317. _r->topology->eachPeer(Topology::CollectPeersThatNeedPing(needPing));
  318. _r->topology->eachPeer(Topology::CollectPeersThatNeedFirewallOpener(needFirewallOpener));
  319. }
  320. for(std::vector< SharedPtr<Peer> >::iterator p(needPing.begin());p!=needPing.end();++p) {
  321. try {
  322. _r->sw->sendHELLO((*p)->address());
  323. } catch (std::exception &exc) {
  324. LOG("unexpected exception sending HELLO to %s: %s",(*p)->address().toString().c_str());
  325. } catch ( ... ) {
  326. LOG("unexpected exception sending HELLO to %s: (unknown)",(*p)->address().toString().c_str());
  327. }
  328. }
  329. for(std::vector< SharedPtr<Peer> >::iterator p(needFirewallOpener.begin());p!=needFirewallOpener.end();++p) {
  330. try {
  331. (*p)->sendFirewallOpener(_r,now);
  332. } catch (std::exception &exc) {
  333. LOG("unexpected exception sending firewall opener to %s: %s",(*p)->address().toString().c_str(),exc.what());
  334. } catch ( ... ) {
  335. LOG("unexpected exception sending firewall opener to %s: (unknown)",(*p)->address().toString().c_str());
  336. }
  337. }
  338. }
  339. } catch (std::exception &exc) {
  340. LOG("unexpected exception running ping check cycle: %s",exc.what());
  341. } catch ( ... ) {
  342. LOG("unexpected exception running ping check cycle: (unkonwn)");
  343. }
  344. }
  345. if ((now - lastTopologyClean) >= ZT_TOPOLOGY_CLEAN_PERIOD) {
  346. lastTopologyClean = now;
  347. _r->topology->clean(); // happens in background
  348. }
  349. if (((now - lastStatusUpdate) >= ZT_STATUS_OUTPUT_PERIOD)||(impl->updateStatusNow)) {
  350. lastStatusUpdate = now;
  351. impl->updateStatusNow = false;
  352. FILE *statusf = ::fopen(statusPath.c_str(),"w");
  353. if (statusf) {
  354. try {
  355. _r->topology->eachPeer(Topology::DumpPeerStatistics(statusf));
  356. } catch ( ... ) {
  357. TRACE("unexpected exception updating status dump");
  358. }
  359. ::fclose(statusf);
  360. }
  361. }
  362. try {
  363. unsigned long delay = std::min((unsigned long)ZT_MIN_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  364. uint64_t start = Utils::now();
  365. _r->mainLoopWaitCondition.wait(delay);
  366. lastDelayDelta = (long)(Utils::now() - start) - (long)delay;
  367. } catch (std::exception &exc) {
  368. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  369. } catch ( ... ) {
  370. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  371. }
  372. }
  373. } catch ( ... ) {
  374. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  375. }
  376. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"normal termination");
  377. }
  378. const char *Node::reasonForTermination() const
  379. throw()
  380. {
  381. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  382. return (const char *)0;
  383. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  384. }
  385. void Node::terminate()
  386. throw()
  387. {
  388. ((_NodeImpl *)_impl)->terminateNow = true;
  389. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  390. }
  391. void Node::updateStatusNow()
  392. throw()
  393. {
  394. ((_NodeImpl *)_impl)->updateStatusNow = true;
  395. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  396. }
  397. class _VersionStringMaker
  398. {
  399. public:
  400. char vs[32];
  401. _VersionStringMaker()
  402. {
  403. sprintf(vs,"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  404. }
  405. ~_VersionStringMaker() {}
  406. };
  407. static const _VersionStringMaker __versionString;
  408. const char *Node::versionString() throw() { return __versionString.vs; }
  409. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  410. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  411. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  412. // Scanned for by loader and/or updater to determine a binary's version
  413. const unsigned char EMBEDDED_VERSION_STAMP[20] = {
  414. 0x6d,0xfe,0xff,0x01,0x90,0xfa,0x89,0x57,0x88,0xa1,0xaa,0xdc,0xdd,0xde,0xb0,0x33,
  415. ZEROTIER_ONE_VERSION_MAJOR,
  416. ZEROTIER_ONE_VERSION_MINOR,
  417. (unsigned char)(((unsigned int)ZEROTIER_ONE_VERSION_REVISION) & 0xff), /* little-endian */
  418. (unsigned char)((((unsigned int)ZEROTIER_ONE_VERSION_REVISION) >> 8) & 0xff)
  419. };
  420. } // namespace ZeroTier