Node.cpp 17 KB

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