Node.cpp 17 KB

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