Node.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. #ifdef _WIN32
  39. #include <Windows.h>
  40. #else
  41. #include <fcntl.h>
  42. #include <unistd.h>
  43. #include <signal.h>
  44. #include <sys/file.h>
  45. #endif
  46. #include "Condition.hpp"
  47. #include "Node.hpp"
  48. #include "Topology.hpp"
  49. #include "Demarc.hpp"
  50. #include "Switch.hpp"
  51. #include "Utils.hpp"
  52. #include "EthernetTap.hpp"
  53. #include "Logger.hpp"
  54. #include "Constants.hpp"
  55. #include "InetAddress.hpp"
  56. #include "Pack.hpp"
  57. #include "RuntimeEnvironment.hpp"
  58. #include "NodeConfig.hpp"
  59. #include "Defaults.hpp"
  60. #include "SysEnv.hpp"
  61. #include "Network.hpp"
  62. #include "MulticastGroup.hpp"
  63. #include "Mutex.hpp"
  64. #include "Multicaster.hpp"
  65. #include "CMWC4096.hpp"
  66. #include "../version.h"
  67. namespace ZeroTier {
  68. struct _NodeImpl
  69. {
  70. RuntimeEnvironment renv;
  71. std::string reasonForTerminationStr;
  72. Node::ReasonForTermination reasonForTermination;
  73. volatile bool started;
  74. volatile bool running;
  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)
  88. throw() :
  89. _impl(new _NodeImpl)
  90. {
  91. _NodeImpl *impl = (_NodeImpl *)_impl;
  92. impl->renv.homePath = hp;
  93. impl->reasonForTermination = Node::NODE_RUNNING;
  94. impl->started = false;
  95. impl->running = false;
  96. impl->terminateNow = false;
  97. }
  98. Node::~Node()
  99. {
  100. _NodeImpl *impl = (_NodeImpl *)_impl;
  101. delete impl->renv.sysEnv;
  102. delete impl->renv.topology;
  103. delete impl->renv.sw;
  104. delete impl->renv.multicaster;
  105. delete impl->renv.demarc;
  106. delete impl->renv.nc;
  107. delete impl->renv.prng;
  108. delete impl->renv.log;
  109. delete impl;
  110. }
  111. /**
  112. * Execute node in current thread
  113. *
  114. * This does not return until the node shuts down. Shutdown may be caused
  115. * by an internally detected condition such as a new upgrade being
  116. * available or a fatal error, or it may be signaled externally using
  117. * the terminate() method.
  118. *
  119. * @return Reason for termination
  120. */
  121. Node::ReasonForTermination Node::run()
  122. throw()
  123. {
  124. _NodeImpl *impl = (_NodeImpl *)_impl;
  125. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  126. impl->started = true;
  127. impl->running = true;
  128. try {
  129. #ifdef ZT_LOG_STDOUT
  130. _r->log = new Logger((const char *)0,(const char *)0,0);
  131. #else
  132. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  133. #endif
  134. TRACE("initializing...");
  135. // Create non-crypto PRNG right away in case other code in init wants to use it
  136. _r->prng = new CMWC4096();
  137. bool gotId = false;
  138. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  139. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  140. std::string idser;
  141. if (Utils::readFile(identitySecretPath.c_str(),idser))
  142. gotId = _r->identity.fromString(idser);
  143. if (gotId) {
  144. // Make sure identity.public matches identity.secret
  145. idser = std::string();
  146. Utils::readFile(identityPublicPath.c_str(),idser);
  147. std::string pubid(_r->identity.toString(false));
  148. if (idser != pubid) {
  149. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  150. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  151. }
  152. } else {
  153. LOG("no identity found, generating one... this might take a few seconds...");
  154. _r->identity.generate();
  155. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  156. idser = _r->identity.toString(true);
  157. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  158. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  159. idser = _r->identity.toString(false);
  160. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  161. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  162. }
  163. Utils::lockDownFile(identitySecretPath.c_str(),false);
  164. // Clean up some obsolete files if present -- this will be removed later
  165. unlink((_r->homePath + ZT_PATH_SEPARATOR_S + "status").c_str());
  166. unlink((_r->homePath + ZT_PATH_SEPARATOR_S + "thisdeviceismine").c_str());
  167. // Load or generate config authentication secret
  168. std::string configAuthTokenPath(_r->homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  169. std::string configAuthToken;
  170. if (!Utils::readFile(configAuthTokenPath.c_str(),configAuthToken)) {
  171. configAuthToken = "";
  172. unsigned int sr = 0;
  173. for(unsigned int i=0;i<24;++i) {
  174. Utils::getSecureRandom(&sr,sizeof(sr));
  175. configAuthToken.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[sr % 62]);
  176. }
  177. if (!Utils::writeFile(configAuthTokenPath.c_str(),configAuthToken))
  178. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write authtoken.secret (home path not writable?)");
  179. }
  180. Utils::lockDownFile(configAuthTokenPath.c_str(),false);
  181. // Create the core objects in RuntimeEnvironment: node config, demarcation
  182. // point, switch, network topology database, and system environment
  183. // watcher.
  184. try {
  185. _r->nc = new NodeConfig(_r,configAuthToken.c_str());
  186. } catch ( ... ) {
  187. // An exception here currently means that another instance of ZeroTier
  188. // One is running.
  189. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"another instance of ZeroTier One appears to be running, or local control UDP port cannot be bound");
  190. }
  191. _r->demarc = new Demarc(_r);
  192. _r->multicaster = new Multicaster();
  193. _r->sw = new Switch(_r);
  194. _r->topology = new Topology(_r,(_r->homePath + ZT_PATH_SEPARATOR_S + "peer.db").c_str());
  195. _r->sysEnv = new SysEnv(_r);
  196. // TODO: make configurable
  197. bool boundPort = false;
  198. for(unsigned int p=ZT_DEFAULT_UDP_PORT;p<(ZT_DEFAULT_UDP_PORT + 128);++p) {
  199. if (_r->demarc->bindLocalUdp(p)) {
  200. boundPort = true;
  201. break;
  202. }
  203. }
  204. if (!boundPort)
  205. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not bind any local UDP ports");
  206. // TODO: bootstrap off network so we don't have to update code for
  207. // changes in supernodes.
  208. _r->topology->setSupernodes(ZT_DEFAULTS.supernodes);
  209. } catch (std::bad_alloc &exc) {
  210. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  211. } catch (std::runtime_error &exc) {
  212. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  213. } catch ( ... ) {
  214. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  215. }
  216. try {
  217. uint64_t lastPingCheck = 0;
  218. uint64_t lastTopologyClean = Utils::now(); // don't need to do this immediately
  219. uint64_t lastNetworkFingerprintCheck = 0;
  220. uint64_t lastAutoconfigureCheck = 0;
  221. uint64_t networkConfigurationFingerprint = _r->sysEnv->getNetworkConfigurationFingerprint();
  222. uint64_t lastMulticastCheck = 0;
  223. uint64_t lastMulticastAnnounceAll = 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, resyncing with network",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. _r->nc->whackAllTaps(); // call whack() on all tap devices
  250. }
  251. }
  252. // Periodically check for changes in our local multicast subscriptions and broadcast
  253. // those changes to peers.
  254. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  255. lastMulticastCheck = now;
  256. bool announceAll = ((now - lastMulticastAnnounceAll) >= ZT_MULTICAST_LIKE_ANNOUNCE_ALL_PERIOD);
  257. try {
  258. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  259. {
  260. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  261. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  262. if (((*nw)->updateMulticastGroups())||(announceAll))
  263. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  264. }
  265. }
  266. if (toAnnounce.size()) {
  267. _r->sw->announceMulticastGroups(toAnnounce);
  268. // Only update lastMulticastAnnounceAll if we've announced something. This keeps
  269. // the announceAll condition true during startup when there are no multicast
  270. // groups until there is at least one. Technically this shouldn't be required as
  271. // updateMulticastGroups() should return true on any change, but why not?
  272. if (announceAll)
  273. lastMulticastAnnounceAll = now;
  274. }
  275. } catch (std::exception &exc) {
  276. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  277. } catch ( ... ) {
  278. LOG("unexpected exception announcing multicast groups: (unknown)");
  279. }
  280. }
  281. if ((now - lastPingCheck) >= ZT_PING_CHECK_DELAY) {
  282. lastPingCheck = now;
  283. try {
  284. if (_r->topology->isSupernode(_r->identity.address())) {
  285. // The only difference in how supernodes behave is here: they only
  286. // actively ping each other and only passively listen for pings
  287. // from anyone else. They also don't send firewall openers, since
  288. // they're never firewalled.
  289. std::vector< SharedPtr<Peer> > sns(_r->topology->supernodePeers());
  290. for(std::vector< SharedPtr<Peer> >::const_iterator p(sns.begin());p!=sns.end();++p) {
  291. if ((now - (*p)->lastDirectSend()) > ZT_PEER_DIRECT_PING_DELAY)
  292. _r->sw->sendHELLO((*p)->address());
  293. }
  294. } else {
  295. std::vector< SharedPtr<Peer> > needPing,needFirewallOpener;
  296. if (pingAll) {
  297. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(needPing));
  298. } else {
  299. _r->topology->eachPeer(Topology::CollectPeersThatNeedPing(needPing));
  300. _r->topology->eachPeer(Topology::CollectPeersThatNeedFirewallOpener(needFirewallOpener));
  301. }
  302. for(std::vector< SharedPtr<Peer> >::iterator p(needPing.begin());p!=needPing.end();++p) {
  303. try {
  304. _r->sw->sendHELLO((*p)->address());
  305. } catch (std::exception &exc) {
  306. LOG("unexpected exception sending HELLO to %s: %s",(*p)->address().toString().c_str());
  307. } catch ( ... ) {
  308. LOG("unexpected exception sending HELLO to %s: (unknown)",(*p)->address().toString().c_str());
  309. }
  310. }
  311. for(std::vector< SharedPtr<Peer> >::iterator p(needFirewallOpener.begin());p!=needFirewallOpener.end();++p) {
  312. try {
  313. (*p)->sendFirewallOpener(_r,now);
  314. } catch (std::exception &exc) {
  315. LOG("unexpected exception sending firewall opener to %s: %s",(*p)->address().toString().c_str(),exc.what());
  316. } catch ( ... ) {
  317. LOG("unexpected exception sending firewall opener to %s: (unknown)",(*p)->address().toString().c_str());
  318. }
  319. }
  320. }
  321. } catch (std::exception &exc) {
  322. LOG("unexpected exception running ping check cycle: %s",exc.what());
  323. } catch ( ... ) {
  324. LOG("unexpected exception running ping check cycle: (unkonwn)");
  325. }
  326. }
  327. if ((now - lastTopologyClean) >= ZT_TOPOLOGY_CLEAN_PERIOD) {
  328. lastTopologyClean = now;
  329. _r->topology->clean(); // happens in background
  330. }
  331. try {
  332. unsigned long delay = std::min((unsigned long)ZT_MIN_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  333. uint64_t start = Utils::now();
  334. _r->mainLoopWaitCondition.wait(delay);
  335. lastDelayDelta = (long)(Utils::now() - start) - (long)delay;
  336. } catch (std::exception &exc) {
  337. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  338. } catch ( ... ) {
  339. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  340. }
  341. }
  342. } catch ( ... ) {
  343. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  344. }
  345. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"normal termination");
  346. }
  347. const char *Node::reasonForTermination() const
  348. throw()
  349. {
  350. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  351. return (const char *)0;
  352. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  353. }
  354. void Node::terminate()
  355. throw()
  356. {
  357. ((_NodeImpl *)_impl)->terminateNow = true;
  358. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  359. }
  360. class _VersionStringMaker
  361. {
  362. public:
  363. char vs[32];
  364. _VersionStringMaker()
  365. {
  366. sprintf(vs,"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  367. }
  368. ~_VersionStringMaker() {}
  369. };
  370. static const _VersionStringMaker __versionString;
  371. const char *Node::versionString() throw() { return __versionString.vs; }
  372. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  373. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  374. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  375. // Scanned for by loader and/or updater to determine a binary's version
  376. const unsigned char EMBEDDED_VERSION_STAMP[20] = {
  377. 0x6d,0xfe,0xff,0x01,0x90,0xfa,0x89,0x57,0x88,0xa1,0xaa,0xdc,0xdd,0xde,0xb0,0x33,
  378. ZEROTIER_ONE_VERSION_MAJOR,
  379. ZEROTIER_ONE_VERSION_MINOR,
  380. (unsigned char)(((unsigned int)ZEROTIER_ONE_VERSION_REVISION) & 0xff), /* little-endian */
  381. (unsigned char)((((unsigned int)ZEROTIER_ONE_VERSION_REVISION) >> 8) & 0xff)
  382. };
  383. } // namespace ZeroTier