Node.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. unsigned int securern = 0;
  175. for(unsigned int i=0;i<24;++i) {
  176. Utils::getSecureRandom(&securern,sizeof(securern));
  177. _r->ownershipVerificationSecret.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[securern % 62]);
  178. }
  179. _r->ownershipVerificationSecret.append(ZT_EOL_S);
  180. if (!Utils::writeFile(ovsPath.c_str(),_r->ownershipVerificationSecret))
  181. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write 'thisdeviceismine' (home path not writable?)");
  182. }
  183. Utils::lockDownFile(ovsPath.c_str(),false);
  184. _r->ownershipVerificationSecret = Utils::trim(_r->ownershipVerificationSecret); // trim off CR file is saved with
  185. unsigned char ovsDig[32];
  186. SHA256_CTX sha;
  187. SHA256_Init(&sha);
  188. SHA256_Update(&sha,_r->ownershipVerificationSecret.data(),_r->ownershipVerificationSecret.length());
  189. SHA256_Final(ovsDig,&sha);
  190. _r->ownershipVerificationSecretHash = Utils::base64Encode(ovsDig,32);
  191. // Create the core objects in RuntimeEnvironment: node config, demarcation
  192. // point, switch, network topology database, and system environment
  193. // watcher.
  194. _r->nc = new NodeConfig(_r,_r->autoconfUrlPrefix + _r->identity.address().toString());
  195. _r->demarc = new Demarc(_r);
  196. _r->multicaster = new Multicaster();
  197. _r->sw = new Switch(_r);
  198. _r->topology = new Topology(_r,(_r->homePath + ZT_PATH_SEPARATOR_S + "peer.db").c_str());
  199. _r->sysEnv = new SysEnv(_r);
  200. // TODO: make configurable
  201. bool boundPort = false;
  202. for(unsigned int p=ZT_DEFAULT_UDP_PORT;p<(ZT_DEFAULT_UDP_PORT + 128);++p) {
  203. if (_r->demarc->bindLocalUdp(p)) {
  204. boundPort = true;
  205. break;
  206. }
  207. }
  208. if (!boundPort)
  209. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not bind any local UDP ports");
  210. // TODO: bootstrap off network so we don't have to update code for
  211. // changes in supernodes.
  212. _r->topology->setSupernodes(ZT_DEFAULTS.supernodes);
  213. } catch (std::bad_alloc &exc) {
  214. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  215. } catch (std::runtime_error &exc) {
  216. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  217. } catch ( ... ) {
  218. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  219. }
  220. try {
  221. std::string statusPath(_r->homePath + ZT_PATH_SEPARATOR_S + "status");
  222. uint64_t lastPingCheck = 0;
  223. uint64_t lastTopologyClean = Utils::now(); // don't need to do this immediately
  224. uint64_t lastNetworkFingerprintCheck = 0;
  225. uint64_t lastAutoconfigureCheck = 0;
  226. uint64_t networkConfigurationFingerprint = _r->sysEnv->getNetworkConfigurationFingerprint();
  227. uint64_t lastMulticastCheck = 0;
  228. uint64_t lastMulticastAnnounceAll = 0;
  229. uint64_t lastStatusUpdate = 0;
  230. long lastDelayDelta = 0;
  231. LOG("%s starting version %s",_r->identity.address().toString().c_str(),versionString());
  232. while (!impl->terminateNow) {
  233. uint64_t now = Utils::now();
  234. bool pingAll = false; // set to true to force a ping of *all* known direct links
  235. // Detect sleep/wake by looking for delay loop pauses that are longer
  236. // than we intended to pause.
  237. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  238. lastNetworkFingerprintCheck = 0; // force network environment check
  239. lastMulticastCheck = 0; // force multicast group check on taps
  240. pingAll = true;
  241. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  242. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  243. }
  244. // Periodically check our network environment, sending pings out to all
  245. // our direct links if things look like we got a different address.
  246. if ((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY) {
  247. lastNetworkFingerprintCheck = now;
  248. uint64_t fp = _r->sysEnv->getNetworkConfigurationFingerprint();
  249. if (fp != networkConfigurationFingerprint) {
  250. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  251. networkConfigurationFingerprint = fp;
  252. pingAll = true;
  253. lastAutoconfigureCheck = 0; // check autoconf after network config change
  254. lastMulticastCheck = 0; // check multicast group membership after network config change
  255. _r->nc->whackAllTaps(); // call whack() on all tap devices
  256. }
  257. }
  258. if ((now - lastAutoconfigureCheck) >= ZT_AUTOCONFIGURE_CHECK_DELAY) {
  259. // It seems odd to only do this simple check every so often, but the purpose is to
  260. // delay between calls to refreshConfiguration() enough that the previous attempt
  261. // has time to either succeed or fail. Otherwise we'll block the whole loop, since
  262. // config update is guarded by a Mutex.
  263. lastAutoconfigureCheck = now;
  264. if ((now - _r->nc->lastAutoconfigure()) >= ZT_AUTOCONFIGURE_INTERVAL)
  265. _r->nc->refreshConfiguration(); // happens in background
  266. }
  267. // Periodically check for changes in our local multicast subscriptions and broadcast
  268. // those changes to peers.
  269. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  270. lastMulticastCheck = now;
  271. bool announceAll = ((now - lastMulticastAnnounceAll) >= ZT_MULTICAST_LIKE_ANNOUNCE_ALL_PERIOD);
  272. try {
  273. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  274. {
  275. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  276. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  277. if (((*nw)->updateMulticastGroups())||(announceAll))
  278. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  279. }
  280. }
  281. if (toAnnounce.size()) {
  282. _r->sw->announceMulticastGroups(toAnnounce);
  283. // Only update lastMulticastAnnounceAll if we've announced something. This keeps
  284. // the announceAll condition true during startup when there are no multicast
  285. // groups until there is at least one. Technically this shouldn't be required as
  286. // updateMulticastGroups() should return true on any change, but why not?
  287. if (announceAll)
  288. lastMulticastAnnounceAll = now;
  289. }
  290. } catch (std::exception &exc) {
  291. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  292. } catch ( ... ) {
  293. LOG("unexpected exception announcing multicast groups: (unknown)");
  294. }
  295. }
  296. if ((now - lastPingCheck) >= ZT_PING_CHECK_DELAY) {
  297. lastPingCheck = now;
  298. try {
  299. if (_r->topology->isSupernode(_r->identity.address())) {
  300. // The only difference in how supernodes behave is here: they only
  301. // actively ping each other and only passively listen for pings
  302. // from anyone else. They also don't send firewall openers, since
  303. // they're never firewalled.
  304. std::vector< SharedPtr<Peer> > sns(_r->topology->supernodePeers());
  305. for(std::vector< SharedPtr<Peer> >::const_iterator p(sns.begin());p!=sns.end();++p) {
  306. if ((now - (*p)->lastDirectSend()) > ZT_PEER_DIRECT_PING_DELAY)
  307. _r->sw->sendHELLO((*p)->address());
  308. }
  309. } else {
  310. std::vector< SharedPtr<Peer> > needPing,needFirewallOpener;
  311. if (pingAll) {
  312. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(needPing));
  313. } else {
  314. _r->topology->eachPeer(Topology::CollectPeersThatNeedPing(needPing));
  315. _r->topology->eachPeer(Topology::CollectPeersThatNeedFirewallOpener(needFirewallOpener));
  316. }
  317. for(std::vector< SharedPtr<Peer> >::iterator p(needPing.begin());p!=needPing.end();++p) {
  318. try {
  319. _r->sw->sendHELLO((*p)->address());
  320. } catch (std::exception &exc) {
  321. LOG("unexpected exception sending HELLO to %s: %s",(*p)->address().toString().c_str());
  322. } catch ( ... ) {
  323. LOG("unexpected exception sending HELLO to %s: (unknown)",(*p)->address().toString().c_str());
  324. }
  325. }
  326. for(std::vector< SharedPtr<Peer> >::iterator p(needFirewallOpener.begin());p!=needFirewallOpener.end();++p) {
  327. try {
  328. (*p)->sendFirewallOpener(_r,now);
  329. } catch (std::exception &exc) {
  330. LOG("unexpected exception sending firewall opener to %s: %s",(*p)->address().toString().c_str(),exc.what());
  331. } catch ( ... ) {
  332. LOG("unexpected exception sending firewall opener to %s: (unknown)",(*p)->address().toString().c_str());
  333. }
  334. }
  335. }
  336. } catch (std::exception &exc) {
  337. LOG("unexpected exception running ping check cycle: %s",exc.what());
  338. } catch ( ... ) {
  339. LOG("unexpected exception running ping check cycle: (unkonwn)");
  340. }
  341. }
  342. if ((now - lastTopologyClean) >= ZT_TOPOLOGY_CLEAN_PERIOD) {
  343. lastTopologyClean = now;
  344. _r->topology->clean(); // happens in background
  345. }
  346. if (((now - lastStatusUpdate) >= ZT_STATUS_OUTPUT_PERIOD)||(impl->updateStatusNow)) {
  347. lastStatusUpdate = now;
  348. impl->updateStatusNow = false;
  349. FILE *statusf = ::fopen(statusPath.c_str(),"w");
  350. if (statusf) {
  351. try {
  352. _r->topology->eachPeer(Topology::DumpPeerStatistics(statusf));
  353. } catch ( ... ) {
  354. TRACE("unexpected exception updating status dump");
  355. }
  356. ::fclose(statusf);
  357. }
  358. }
  359. try {
  360. unsigned long delay = std::min((unsigned long)ZT_MIN_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  361. uint64_t start = Utils::now();
  362. _r->mainLoopWaitCondition.wait(delay);
  363. lastDelayDelta = (long)(Utils::now() - start) - (long)delay;
  364. } catch (std::exception &exc) {
  365. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  366. } catch ( ... ) {
  367. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  368. }
  369. }
  370. } catch ( ... ) {
  371. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  372. }
  373. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"normal termination");
  374. }
  375. const char *Node::reasonForTermination() const
  376. throw()
  377. {
  378. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  379. return (const char *)0;
  380. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  381. }
  382. void Node::terminate()
  383. throw()
  384. {
  385. ((_NodeImpl *)_impl)->terminateNow = true;
  386. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  387. }
  388. void Node::updateStatusNow()
  389. throw()
  390. {
  391. ((_NodeImpl *)_impl)->updateStatusNow = true;
  392. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  393. }
  394. class _VersionStringMaker
  395. {
  396. public:
  397. char vs[32];
  398. _VersionStringMaker()
  399. {
  400. sprintf(vs,"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  401. }
  402. ~_VersionStringMaker() {}
  403. };
  404. static const _VersionStringMaker __versionString;
  405. const char *Node::versionString() throw() { return __versionString.vs; }
  406. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  407. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  408. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  409. // Scanned for by loader and/or updater to determine a binary's version
  410. const unsigned char EMBEDDED_VERSION_STAMP[20] = {
  411. 0x6d,0xfe,0xff,0x01,0x90,0xfa,0x89,0x57,0x88,0xa1,0xaa,0xdc,0xdd,0xde,0xb0,0x33,
  412. ZEROTIER_ONE_VERSION_MAJOR,
  413. ZEROTIER_ONE_VERSION_MINOR,
  414. (unsigned char)(((unsigned int)ZEROTIER_ONE_VERSION_REVISION) & 0xff), /* little-endian */
  415. (unsigned char)((((unsigned int)ZEROTIER_ONE_VERSION_REVISION) >> 8) & 0xff)
  416. };
  417. } // namespace ZeroTier