Node.cpp 17 KB

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