Node.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 "Salsa20.hpp"
  57. #include "HMAC.hpp"
  58. #include "RuntimeEnvironment.hpp"
  59. #include "NodeConfig.hpp"
  60. #include "Defaults.hpp"
  61. #include "SysEnv.hpp"
  62. #include "Network.hpp"
  63. #include "MulticastGroup.hpp"
  64. #include "Mutex.hpp"
  65. #include "Multicaster.hpp"
  66. #include "CMWC4096.hpp"
  67. #include "../version.h"
  68. namespace ZeroTier {
  69. struct _LocalClientImpl
  70. {
  71. unsigned char key[32];
  72. UdpSocket *sock;
  73. void (*resultHandler)(void *,unsigned long,const char *);
  74. void *arg;
  75. InetAddress localDestAddr;
  76. Mutex inUseLock;
  77. };
  78. static void _CBlocalClientHandler(UdpSocket *sock,void *arg,const InetAddress &remoteAddr,const void *data,unsigned int len)
  79. {
  80. _LocalClientImpl *impl = (_LocalClientImpl *)arg;
  81. if (!impl)
  82. return;
  83. if (!impl->resultHandler)
  84. return; // sanity check
  85. Mutex::Lock _l(impl->inUseLock);
  86. try {
  87. unsigned long convId = 0;
  88. std::vector<std::string> results;
  89. if (!NodeConfig::decodeControlMessagePacket(impl->key,data,len,convId,results))
  90. return;
  91. for(std::vector<std::string>::iterator r(results.begin());r!=results.end();++r)
  92. impl->resultHandler(impl->arg,convId,r->c_str());
  93. } catch ( ... ) {}
  94. }
  95. Node::LocalClient::LocalClient(const char *authToken,void (*resultHandler)(void *,unsigned long,const char *),void *arg)
  96. throw() :
  97. _impl((void *)0)
  98. {
  99. _LocalClientImpl *impl = new _LocalClientImpl;
  100. UdpSocket *sock = (UdpSocket *)0;
  101. for(unsigned int i=0;i<5000;++i) {
  102. try {
  103. sock = new UdpSocket(true,32768 + (rand() % 20000),false,&_CBlocalClientHandler,impl);
  104. break;
  105. } catch ( ... ) {
  106. sock = (UdpSocket *)0;
  107. }
  108. }
  109. // If socket fails to bind, there's a big problem like missing IPv4 stack
  110. if (sock) {
  111. SHA256_CTX sha;
  112. SHA256_Init(&sha);
  113. SHA256_Update(&sha,authToken,strlen(authToken));
  114. SHA256_Final(impl->key,&sha);
  115. impl->sock = sock;
  116. impl->resultHandler = resultHandler;
  117. impl->arg = arg;
  118. impl->localDestAddr = InetAddress::LO4;
  119. impl->localDestAddr.setPort(ZT_CONTROL_UDP_PORT);
  120. _impl = impl;
  121. } else delete impl;
  122. }
  123. Node::LocalClient::~LocalClient()
  124. {
  125. if (_impl) {
  126. ((_LocalClientImpl *)_impl)->inUseLock.lock();
  127. delete ((_LocalClientImpl *)_impl)->sock;
  128. ((_LocalClientImpl *)_impl)->inUseLock.unlock();
  129. delete ((_LocalClientImpl *)_impl);
  130. }
  131. }
  132. unsigned long Node::LocalClient::send(const char *command)
  133. throw()
  134. {
  135. if (!_impl)
  136. return 0;
  137. _LocalClientImpl *impl = (_LocalClientImpl *)_impl;
  138. Mutex::Lock _l(impl->inUseLock);
  139. try {
  140. uint32_t convId = (uint32_t)rand();
  141. if (!convId)
  142. convId = 1;
  143. std::vector<std::string> tmp;
  144. tmp.push_back(std::string(command));
  145. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > packets(NodeConfig::encodeControlMessage(impl->key,convId,tmp));
  146. for(std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> >::iterator p(packets.begin());p!=packets.end();++p)
  147. impl->sock->send(impl->localDestAddr,p->data(),p->size(),-1);
  148. return convId;
  149. } catch ( ... ) {
  150. return 0;
  151. }
  152. }
  153. struct _NodeImpl
  154. {
  155. RuntimeEnvironment renv;
  156. std::string reasonForTerminationStr;
  157. Node::ReasonForTermination reasonForTermination;
  158. volatile bool started;
  159. volatile bool running;
  160. volatile bool terminateNow;
  161. // Helper used to rapidly terminate from run()
  162. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  163. {
  164. RuntimeEnvironment *_r = &renv;
  165. LOG("terminating: %s",rstr);
  166. reasonForTerminationStr = rstr;
  167. reasonForTermination = r;
  168. running = false;
  169. return r;
  170. }
  171. };
  172. Node::Node(const char *hp)
  173. throw() :
  174. _impl(new _NodeImpl)
  175. {
  176. _NodeImpl *impl = (_NodeImpl *)_impl;
  177. impl->renv.homePath = hp;
  178. impl->reasonForTermination = Node::NODE_RUNNING;
  179. impl->started = false;
  180. impl->running = false;
  181. impl->terminateNow = false;
  182. }
  183. Node::~Node()
  184. {
  185. _NodeImpl *impl = (_NodeImpl *)_impl;
  186. delete impl->renv.sysEnv;
  187. delete impl->renv.topology;
  188. delete impl->renv.sw;
  189. delete impl->renv.multicaster;
  190. delete impl->renv.demarc;
  191. delete impl->renv.nc;
  192. delete impl->renv.prng;
  193. delete impl->renv.log;
  194. delete impl;
  195. }
  196. /**
  197. * Execute node in current thread
  198. *
  199. * This does not return until the node shuts down. Shutdown may be caused
  200. * by an internally detected condition such as a new upgrade being
  201. * available or a fatal error, or it may be signaled externally using
  202. * the terminate() method.
  203. *
  204. * @return Reason for termination
  205. */
  206. Node::ReasonForTermination Node::run()
  207. throw()
  208. {
  209. _NodeImpl *impl = (_NodeImpl *)_impl;
  210. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  211. impl->started = true;
  212. impl->running = true;
  213. try {
  214. #ifdef ZT_LOG_STDOUT
  215. _r->log = new Logger((const char *)0,(const char *)0,0);
  216. #else
  217. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  218. #endif
  219. TRACE("initializing...");
  220. // Create non-crypto PRNG right away in case other code in init wants to use it
  221. _r->prng = new CMWC4096();
  222. bool gotId = false;
  223. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  224. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  225. std::string idser;
  226. if (Utils::readFile(identitySecretPath.c_str(),idser))
  227. gotId = _r->identity.fromString(idser);
  228. if (gotId) {
  229. // Make sure identity.public matches identity.secret
  230. idser = std::string();
  231. Utils::readFile(identityPublicPath.c_str(),idser);
  232. std::string pubid(_r->identity.toString(false));
  233. if (idser != pubid) {
  234. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  235. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  236. }
  237. } else {
  238. LOG("no identity found, generating one... this might take a few seconds...");
  239. _r->identity.generate();
  240. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  241. idser = _r->identity.toString(true);
  242. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  243. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  244. idser = _r->identity.toString(false);
  245. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  246. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  247. }
  248. Utils::lockDownFile(identitySecretPath.c_str(),false);
  249. // Clean up some obsolete files if present -- this will be removed later
  250. unlink((_r->homePath + ZT_PATH_SEPARATOR_S + "status").c_str());
  251. unlink((_r->homePath + ZT_PATH_SEPARATOR_S + "thisdeviceismine").c_str());
  252. // Load or generate config authentication secret
  253. std::string configAuthTokenPath(_r->homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  254. std::string configAuthToken;
  255. if (!Utils::readFile(configAuthTokenPath.c_str(),configAuthToken)) {
  256. configAuthToken = "";
  257. unsigned int sr = 0;
  258. for(unsigned int i=0;i<24;++i) {
  259. Utils::getSecureRandom(&sr,sizeof(sr));
  260. configAuthToken.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[sr % 62]);
  261. }
  262. if (!Utils::writeFile(configAuthTokenPath.c_str(),configAuthToken))
  263. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write authtoken.secret (home path not writable?)");
  264. }
  265. Utils::lockDownFile(configAuthTokenPath.c_str(),false);
  266. // Create the core objects in RuntimeEnvironment: node config, demarcation
  267. // point, switch, network topology database, and system environment
  268. // watcher.
  269. try {
  270. _r->nc = new NodeConfig(_r,configAuthToken.c_str());
  271. } catch ( ... ) {
  272. // An exception here currently means that another instance of ZeroTier
  273. // One is running.
  274. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"another instance of ZeroTier One appears to be running, or local control UDP port cannot be bound");
  275. }
  276. _r->demarc = new Demarc(_r);
  277. _r->multicaster = new Multicaster();
  278. _r->sw = new Switch(_r);
  279. _r->topology = new Topology(_r,(_r->homePath + ZT_PATH_SEPARATOR_S + "peer.db").c_str());
  280. _r->sysEnv = new SysEnv(_r);
  281. // TODO: make configurable
  282. bool boundPort = false;
  283. for(unsigned int p=ZT_DEFAULT_UDP_PORT;p<(ZT_DEFAULT_UDP_PORT + 128);++p) {
  284. if (_r->demarc->bindLocalUdp(p)) {
  285. boundPort = true;
  286. break;
  287. }
  288. }
  289. if (!boundPort)
  290. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not bind any local UDP ports");
  291. // TODO: bootstrap off network so we don't have to update code for
  292. // changes in supernodes.
  293. _r->topology->setSupernodes(ZT_DEFAULTS.supernodes);
  294. } catch (std::bad_alloc &exc) {
  295. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  296. } catch (std::runtime_error &exc) {
  297. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  298. } catch ( ... ) {
  299. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  300. }
  301. try {
  302. uint64_t lastPingCheck = 0;
  303. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  304. uint64_t lastNetworkFingerprintCheck = 0;
  305. uint64_t lastAutoconfigureCheck = 0;
  306. uint64_t networkConfigurationFingerprint = _r->sysEnv->getNetworkConfigurationFingerprint();
  307. uint64_t lastMulticastCheck = 0;
  308. uint64_t lastMulticastAnnounceAll = 0;
  309. long lastDelayDelta = 0;
  310. LOG("%s starting version %s",_r->identity.address().toString().c_str(),versionString());
  311. while (!impl->terminateNow) {
  312. uint64_t now = Utils::now();
  313. bool pingAll = false; // set to true to force a ping of *all* known direct links
  314. // Detect sleep/wake by looking for delay loop pauses that are longer
  315. // than we intended to pause.
  316. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  317. lastNetworkFingerprintCheck = 0; // force network environment check
  318. lastMulticastCheck = 0; // force multicast group check on taps
  319. pingAll = true;
  320. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  321. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  322. }
  323. // Periodically check our network environment, sending pings out to all
  324. // our direct links if things look like we got a different address.
  325. if ((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY) {
  326. lastNetworkFingerprintCheck = now;
  327. uint64_t fp = _r->sysEnv->getNetworkConfigurationFingerprint();
  328. if (fp != networkConfigurationFingerprint) {
  329. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  330. networkConfigurationFingerprint = fp;
  331. pingAll = true;
  332. lastAutoconfigureCheck = 0; // check autoconf after network config change
  333. lastMulticastCheck = 0; // check multicast group membership after network config change
  334. _r->nc->whackAllTaps(); // call whack() on all tap devices
  335. }
  336. }
  337. // Periodically check for changes in our local multicast subscriptions and broadcast
  338. // those changes to peers.
  339. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  340. lastMulticastCheck = now;
  341. bool announceAll = ((now - lastMulticastAnnounceAll) >= ZT_MULTICAST_LIKE_ANNOUNCE_ALL_PERIOD);
  342. try {
  343. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  344. {
  345. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  346. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  347. if (((*nw)->updateMulticastGroups())||(announceAll))
  348. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  349. }
  350. }
  351. if (toAnnounce.size()) {
  352. _r->sw->announceMulticastGroups(toAnnounce);
  353. // Only update lastMulticastAnnounceAll if we've announced something. This keeps
  354. // the announceAll condition true during startup when there are no multicast
  355. // groups until there is at least one. Technically this shouldn't be required as
  356. // updateMulticastGroups() should return true on any change, but why not?
  357. if (announceAll)
  358. lastMulticastAnnounceAll = now;
  359. }
  360. } catch (std::exception &exc) {
  361. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  362. } catch ( ... ) {
  363. LOG("unexpected exception announcing multicast groups: (unknown)");
  364. }
  365. }
  366. if ((now - lastPingCheck) >= ZT_PING_CHECK_DELAY) {
  367. lastPingCheck = now;
  368. try {
  369. if (_r->topology->amSupernode()) {
  370. // Supernodes do not ping anyone but each other. They also don't
  371. // send firewall openers, since they aren't ever firewalled.
  372. std::vector< SharedPtr<Peer> > sns(_r->topology->supernodePeers());
  373. for(std::vector< SharedPtr<Peer> >::const_iterator p(sns.begin());p!=sns.end();++p) {
  374. if ((now - (*p)->lastDirectSend()) > ZT_PEER_DIRECT_PING_DELAY)
  375. _r->sw->sendHELLO((*p)->address());
  376. }
  377. } else {
  378. std::vector< SharedPtr<Peer> > needPing,needFirewallOpener;
  379. if (pingAll) {
  380. _r->topology->eachPeer(Topology::CollectPeersWithActiveDirectPath(needPing));
  381. } else {
  382. _r->topology->eachPeer(Topology::CollectPeersThatNeedPing(needPing));
  383. _r->topology->eachPeer(Topology::CollectPeersThatNeedFirewallOpener(needFirewallOpener));
  384. }
  385. for(std::vector< SharedPtr<Peer> >::iterator p(needPing.begin());p!=needPing.end();++p) {
  386. try {
  387. _r->sw->sendHELLO((*p)->address());
  388. } catch (std::exception &exc) {
  389. LOG("unexpected exception sending HELLO to %s: %s",(*p)->address().toString().c_str());
  390. } catch ( ... ) {
  391. LOG("unexpected exception sending HELLO to %s: (unknown)",(*p)->address().toString().c_str());
  392. }
  393. }
  394. for(std::vector< SharedPtr<Peer> >::iterator p(needFirewallOpener.begin());p!=needFirewallOpener.end();++p) {
  395. try {
  396. (*p)->sendFirewallOpener(_r,now);
  397. } catch (std::exception &exc) {
  398. LOG("unexpected exception sending firewall opener to %s: %s",(*p)->address().toString().c_str(),exc.what());
  399. } catch ( ... ) {
  400. LOG("unexpected exception sending firewall opener to %s: (unknown)",(*p)->address().toString().c_str());
  401. }
  402. }
  403. }
  404. } catch (std::exception &exc) {
  405. LOG("unexpected exception running ping check cycle: %s",exc.what());
  406. } catch ( ... ) {
  407. LOG("unexpected exception running ping check cycle: (unkonwn)");
  408. }
  409. }
  410. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  411. lastClean = now;
  412. _r->topology->clean();
  413. _r->nc->cleanAllNetworks();
  414. }
  415. try {
  416. unsigned long delay = std::min((unsigned long)ZT_MIN_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  417. uint64_t start = Utils::now();
  418. _r->mainLoopWaitCondition.wait(delay);
  419. lastDelayDelta = (long)(Utils::now() - start) - (long)delay;
  420. } catch (std::exception &exc) {
  421. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  422. } catch ( ... ) {
  423. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  424. }
  425. }
  426. } catch ( ... ) {
  427. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  428. }
  429. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"normal termination");
  430. }
  431. const char *Node::reasonForTermination() const
  432. throw()
  433. {
  434. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  435. return (const char *)0;
  436. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  437. }
  438. void Node::terminate()
  439. throw()
  440. {
  441. ((_NodeImpl *)_impl)->terminateNow = true;
  442. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  443. }
  444. class _VersionStringMaker
  445. {
  446. public:
  447. char vs[32];
  448. _VersionStringMaker()
  449. {
  450. sprintf(vs,"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  451. }
  452. ~_VersionStringMaker() {}
  453. };
  454. static const _VersionStringMaker __versionString;
  455. const char *Node::versionString() throw() { return __versionString.vs; }
  456. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  457. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  458. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  459. // Scanned for by loader and/or updater to determine a binary's version
  460. const unsigned char EMBEDDED_VERSION_STAMP[20] = {
  461. 0x6d,0xfe,0xff,0x01,0x90,0xfa,0x89,0x57,0x88,0xa1,0xaa,0xdc,0xdd,0xde,0xb0,0x33,
  462. ZEROTIER_ONE_VERSION_MAJOR,
  463. ZEROTIER_ONE_VERSION_MINOR,
  464. (unsigned char)(((unsigned int)ZEROTIER_ONE_VERSION_REVISION) & 0xff), /* little-endian */
  465. (unsigned char)((((unsigned int)ZEROTIER_ONE_VERSION_REVISION) >> 8) & 0xff)
  466. };
  467. } // namespace ZeroTier