Node.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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 <sys/stat.h>
  32. #include <map>
  33. #include <set>
  34. #include <utility>
  35. #include <algorithm>
  36. #include <list>
  37. #include <vector>
  38. #include <string>
  39. #include "Constants.hpp"
  40. #ifdef __WINDOWS__
  41. #include <WinSock2.h>
  42. #include <Windows.h>
  43. #include <ShlObj.h>
  44. #else
  45. #include <fcntl.h>
  46. #include <unistd.h>
  47. #include <signal.h>
  48. #include <sys/file.h>
  49. #endif
  50. #include "../version.h"
  51. #include "Node.hpp"
  52. #include "RuntimeEnvironment.hpp"
  53. #include "Logger.hpp"
  54. #include "Utils.hpp"
  55. #include "Defaults.hpp"
  56. #include "Identity.hpp"
  57. #include "Topology.hpp"
  58. #include "SocketManager.hpp"
  59. #include "Switch.hpp"
  60. #include "EthernetTap.hpp"
  61. #include "CMWC4096.hpp"
  62. #include "NodeConfig.hpp"
  63. #include "SysEnv.hpp"
  64. #include "Network.hpp"
  65. #include "MulticastGroup.hpp"
  66. #include "Mutex.hpp"
  67. #include "Multicaster.hpp"
  68. #include "Service.hpp"
  69. #include "SoftwareUpdater.hpp"
  70. #include "Buffer.hpp"
  71. #include "IpcConnection.hpp"
  72. #include "AntiRecursion.hpp"
  73. namespace ZeroTier {
  74. // ---------------------------------------------------------------------------
  75. struct _NodeControlClientImpl
  76. {
  77. void (*resultHandler)(void *,const char *);
  78. void *arg;
  79. IpcConnection *ipcc;
  80. std::string err;
  81. };
  82. static void _CBipcResultHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *result)
  83. {
  84. if ((event == IpcConnection::IPC_EVENT_COMMAND)&&(result)) {
  85. if (strcmp(result,"200 auth OK"))
  86. ((_NodeControlClientImpl *)arg)->resultHandler(((_NodeControlClientImpl *)arg)->arg,result);
  87. }
  88. }
  89. Node::NodeControlClient::NodeControlClient(const char *hp,void (*resultHandler)(void *,const char *),void *arg,const char *authToken)
  90. throw() :
  91. _impl((void *)new _NodeControlClientImpl)
  92. {
  93. _NodeControlClientImpl *impl = (_NodeControlClientImpl *)_impl;
  94. impl->ipcc = (IpcConnection *)0;
  95. if (!hp)
  96. hp = ZT_DEFAULTS.defaultHomePath.c_str();
  97. std::string at;
  98. if (authToken)
  99. at = authToken;
  100. else if (!Utils::readFile(authTokenDefaultSystemPath(),at)) {
  101. if (!Utils::readFile(authTokenDefaultUserPath(),at)) {
  102. impl->err = "no authentication token specified and authtoken.secret not readable";
  103. return;
  104. }
  105. }
  106. std::string myid;
  107. if (Utils::readFile((std::string(hp) + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),myid)) {
  108. std::string myaddr(myid.substr(0,myid.find(':')));
  109. if (myaddr.length() != 10)
  110. impl->err = "invalid address extracted from identity.public";
  111. else {
  112. try {
  113. impl->resultHandler = resultHandler;
  114. impl->arg = arg;
  115. impl->ipcc = new IpcConnection((std::string(ZT_IPC_ENDPOINT_BASE) + myaddr).c_str(),&_CBipcResultHandler,_impl);
  116. impl->ipcc->printf("auth %s"ZT_EOL_S,at.c_str());
  117. } catch ( ... ) {
  118. impl->ipcc = (IpcConnection *)0;
  119. impl->err = "failure connecting to running ZeroTier One service";
  120. }
  121. }
  122. } else impl->err = "unable to read identity.public";
  123. }
  124. Node::NodeControlClient::~NodeControlClient()
  125. {
  126. if (_impl) {
  127. delete ((_NodeControlClientImpl *)_impl)->ipcc;
  128. delete (_NodeControlClientImpl *)_impl;
  129. }
  130. }
  131. const char *Node::NodeControlClient::error() const
  132. throw()
  133. {
  134. if (((_NodeControlClientImpl *)_impl)->err.length())
  135. return ((_NodeControlClientImpl *)_impl)->err.c_str();
  136. return (const char *)0;
  137. }
  138. void Node::NodeControlClient::send(const char *command)
  139. throw()
  140. {
  141. try {
  142. if (((_NodeControlClientImpl *)_impl)->ipcc)
  143. ((_NodeControlClientImpl *)_impl)->ipcc->printf("%s"ZT_EOL_S,command);
  144. } catch ( ... ) {}
  145. }
  146. std::vector<std::string> Node::NodeControlClient::splitLine(const char *line)
  147. {
  148. return Utils::split(line," ","\\","\"");
  149. }
  150. const char *Node::NodeControlClient::authTokenDefaultUserPath()
  151. {
  152. static std::string dlp;
  153. static Mutex dlp_m;
  154. Mutex::Lock _l(dlp_m);
  155. #ifdef __WINDOWS__
  156. if (!dlp.length()) {
  157. char buf[16384];
  158. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_APPDATA,NULL,0,buf)))
  159. dlp = (std::string(buf) + "\\ZeroTier\\One\\authtoken.secret");
  160. }
  161. #else // not __WINDOWS__
  162. if (!dlp.length()) {
  163. const char *home = getenv("HOME");
  164. if (home) {
  165. #ifdef __APPLE__
  166. dlp = (std::string(home) + "/Library/Application Support/ZeroTier/One/authtoken.secret");
  167. #else
  168. dlp = (std::string(home) + "/.zeroTierOneAuthToken");
  169. #endif
  170. }
  171. }
  172. #endif // __WINDOWS__ or not __WINDOWS__
  173. return dlp.c_str();
  174. }
  175. const char *Node::NodeControlClient::authTokenDefaultSystemPath()
  176. {
  177. static std::string dsp;
  178. static Mutex dsp_m;
  179. Mutex::Lock _l(dsp_m);
  180. if (!dsp.length())
  181. dsp = (ZT_DEFAULTS.defaultHomePath + ZT_PATH_SEPARATOR_S"authtoken.secret");
  182. return dsp.c_str();
  183. }
  184. // ---------------------------------------------------------------------------
  185. struct _NodeImpl
  186. {
  187. RuntimeEnvironment renv;
  188. unsigned int udpPort,tcpPort;
  189. std::string reasonForTerminationStr;
  190. volatile Node::ReasonForTermination reasonForTermination;
  191. volatile bool started;
  192. volatile bool running;
  193. volatile bool resynchronize;
  194. inline Node::ReasonForTermination terminate()
  195. {
  196. RuntimeEnvironment *_r = &renv;
  197. LOG("terminating: %s",reasonForTerminationStr.c_str());
  198. renv.shutdownInProgress = true;
  199. Thread::sleep(500);
  200. running = false;
  201. #ifndef __WINDOWS__
  202. delete renv.netconfService;
  203. #endif
  204. delete renv.updater;
  205. delete renv.nc;
  206. delete renv.sysEnv;
  207. delete renv.topology;
  208. delete renv.sm;
  209. delete renv.sw;
  210. delete renv.mc;
  211. delete renv.antiRec;
  212. delete renv.prng;
  213. delete renv.log;
  214. return reasonForTermination;
  215. }
  216. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  217. {
  218. reasonForTerminationStr = rstr;
  219. reasonForTermination = r;
  220. return terminate();
  221. }
  222. };
  223. #ifndef __WINDOWS__
  224. static void _netconfServiceMessageHandler(void *renv,Service &svc,const Dictionary &msg)
  225. {
  226. if (!renv)
  227. return; // sanity check
  228. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)renv;
  229. try {
  230. //TRACE("from netconf:\n%s",msg.toString().c_str());
  231. const std::string &type = msg.get("type");
  232. if (type == "ready") {
  233. LOG("received 'ready' from netconf.service, sending netconf-init with identity information...");
  234. Dictionary initMessage;
  235. initMessage["type"] = "netconf-init";
  236. initMessage["netconfId"] = _r->identity.toString(true);
  237. _r->netconfService->send(initMessage);
  238. } else if (type == "netconf-response") {
  239. uint64_t inRePacketId = strtoull(msg.get("requestId").c_str(),(char **)0,16);
  240. uint64_t nwid = strtoull(msg.get("nwid").c_str(),(char **)0,16);
  241. Address peerAddress(msg.get("peer").c_str());
  242. if (peerAddress) {
  243. if (msg.contains("error")) {
  244. Packet::ErrorCode errCode = Packet::ERROR_INVALID_REQUEST;
  245. const std::string &err = msg.get("error");
  246. if (err == "OBJ_NOT_FOUND")
  247. errCode = Packet::ERROR_OBJ_NOT_FOUND;
  248. else if (err == "ACCESS_DENIED")
  249. errCode = Packet::ERROR_NETWORK_ACCESS_DENIED_;
  250. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_ERROR);
  251. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  252. outp.append(inRePacketId);
  253. outp.append((unsigned char)errCode);
  254. outp.append(nwid);
  255. _r->sw->send(outp,true);
  256. } else if (msg.contains("netconf")) {
  257. const std::string &netconf = msg.get("netconf");
  258. if (netconf.length() < 2048) { // sanity check
  259. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_OK);
  260. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  261. outp.append(inRePacketId);
  262. outp.append(nwid);
  263. outp.append((uint16_t)netconf.length());
  264. outp.append(netconf.data(),netconf.length());
  265. outp.compress();
  266. _r->sw->send(outp,true);
  267. }
  268. }
  269. }
  270. } else if (type == "netconf-push") {
  271. if (msg.contains("to")) {
  272. Dictionary to(msg.get("to")); // key: peer address, value: comma-delimited network list
  273. for(Dictionary::iterator t(to.begin());t!=to.end();++t) {
  274. Address ztaddr(t->first);
  275. if (ztaddr) {
  276. Packet outp(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  277. char *saveptr = (char *)0;
  278. // Note: this loop trashes t->second, which is quasi-legal C++ but
  279. // shouldn't break anything as long as we don't try to use 'to'
  280. // for anything interesting after doing this.
  281. for(char *p=Utils::stok(const_cast<char *>(t->second.c_str()),",",&saveptr);(p);p=Utils::stok((char *)0,",",&saveptr)) {
  282. uint64_t nwid = Utils::hexStrToU64(p);
  283. if (nwid) {
  284. if ((outp.size() + sizeof(uint64_t)) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  285. _r->sw->send(outp,true);
  286. outp.reset(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  287. }
  288. outp.append(nwid);
  289. }
  290. }
  291. if (outp.payloadLength())
  292. _r->sw->send(outp,true);
  293. }
  294. }
  295. }
  296. }
  297. } catch (std::exception &exc) {
  298. LOG("unexpected exception parsing response from netconf service: %s",exc.what());
  299. } catch ( ... ) {
  300. LOG("unexpected exception parsing response from netconf service: unknown exception");
  301. }
  302. }
  303. #endif // !__WINDOWS__
  304. Node::Node(const char *hp,unsigned int udpPort,unsigned int tcpPort,bool resetIdentity)
  305. throw() :
  306. _impl(new _NodeImpl)
  307. {
  308. _NodeImpl *impl = (_NodeImpl *)_impl;
  309. if ((hp)&&(hp[0]))
  310. impl->renv.homePath = hp;
  311. else impl->renv.homePath = ZT_DEFAULTS.defaultHomePath;
  312. if (resetIdentity) {
  313. // Forget identity and peer database, peer keys, etc.
  314. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  315. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  316. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "peers.persist").c_str());
  317. // Truncate network config information in networks.d but leave the files since we
  318. // still want to remember any networks we have joined. This will force re-config.
  319. std::string networksDotD(impl->renv.homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  320. std::map< std::string,bool > nwfiles(Utils::listDirectory(networksDotD.c_str()));
  321. for(std::map<std::string,bool>::iterator nwf(nwfiles.begin());nwf!=nwfiles.end();++nwf) {
  322. FILE *foo = fopen((networksDotD + ZT_PATH_SEPARATOR_S + nwf->first).c_str(),"w");
  323. if (foo)
  324. fclose(foo);
  325. }
  326. }
  327. impl->udpPort = udpPort & 0xffff;
  328. impl->tcpPort = tcpPort & 0xffff;
  329. impl->reasonForTermination = Node::NODE_RUNNING;
  330. impl->started = false;
  331. impl->running = false;
  332. impl->resynchronize = false;
  333. }
  334. Node::~Node()
  335. {
  336. delete (_NodeImpl *)_impl;
  337. }
  338. static void _CBztTraffic(const SharedPtr<Socket> &fromSock,void *arg,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  339. {
  340. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)arg;
  341. if ((_r->sw)&&(!_r->shutdownInProgress))
  342. _r->sw->onRemotePacket(fromSock,from,data);
  343. }
  344. Node::ReasonForTermination Node::run()
  345. throw()
  346. {
  347. _NodeImpl *impl = (_NodeImpl *)_impl;
  348. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  349. impl->started = true;
  350. impl->running = true;
  351. try {
  352. #ifdef ZT_LOG_STDOUT
  353. _r->log = new Logger((const char *)0,(const char *)0,0);
  354. #else
  355. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  356. #endif
  357. LOG("starting version %s",versionString());
  358. // Create non-crypto PRNG right away in case other code in init wants to use it
  359. _r->prng = new CMWC4096();
  360. bool gotId = false;
  361. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  362. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  363. std::string idser;
  364. if (Utils::readFile(identitySecretPath.c_str(),idser))
  365. gotId = _r->identity.fromString(idser);
  366. if ((gotId)&&(!_r->identity.locallyValidate()))
  367. gotId = false;
  368. if (gotId) {
  369. // Make sure identity.public matches identity.secret
  370. idser = std::string();
  371. Utils::readFile(identityPublicPath.c_str(),idser);
  372. std::string pubid(_r->identity.toString(false));
  373. if (idser != pubid) {
  374. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  375. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  376. }
  377. } else {
  378. LOG("no identity found or identity invalid, generating one... this might take a few seconds...");
  379. _r->identity.generate();
  380. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  381. idser = _r->identity.toString(true);
  382. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  383. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  384. idser = _r->identity.toString(false);
  385. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  386. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  387. }
  388. Utils::lockDownFile(identitySecretPath.c_str(),false);
  389. // Make sure networks.d exists
  390. {
  391. std::string networksDotD(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  392. #ifdef __WINDOWS__
  393. CreateDirectoryA(networksDotD.c_str(),NULL);
  394. #else
  395. mkdir(networksDotD.c_str(),0700);
  396. #endif
  397. }
  398. // Load or generate config authentication secret
  399. std::string configAuthTokenPath(_r->homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  400. std::string configAuthToken;
  401. if (!Utils::readFile(configAuthTokenPath.c_str(),configAuthToken)) {
  402. configAuthToken = "";
  403. unsigned int sr = 0;
  404. for(unsigned int i=0;i<24;++i) {
  405. Utils::getSecureRandom(&sr,sizeof(sr));
  406. configAuthToken.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[sr % 62]);
  407. }
  408. if (!Utils::writeFile(configAuthTokenPath.c_str(),configAuthToken))
  409. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write authtoken.secret (home path not writable?)");
  410. }
  411. Utils::lockDownFile(configAuthTokenPath.c_str(),false);
  412. // Create the objects that make up runtime state.
  413. _r->antiRec = new AntiRecursion();
  414. _r->mc = new Multicaster();
  415. _r->sw = new Switch(_r);
  416. _r->sm = new SocketManager(impl->udpPort,impl->tcpPort,&_CBztTraffic,_r);
  417. _r->topology = new Topology(_r,Utils::fileExists((_r->homePath + ZT_PATH_SEPARATOR_S + "iddb.d").c_str()));
  418. _r->sysEnv = new SysEnv();
  419. try {
  420. _r->nc = new NodeConfig(_r,configAuthToken.c_str());
  421. } catch (std::exception &exc) {
  422. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unable to initialize IPC socket: is ZeroTier One already running?");
  423. }
  424. _r->node = this;
  425. #ifdef ZT_AUTO_UPDATE
  426. if (ZT_DEFAULTS.updateLatestNfoURL.length()) {
  427. _r->updater = new SoftwareUpdater(_r);
  428. _r->updater->cleanOldUpdates(); // clean out updates.d on startup
  429. } else {
  430. LOG("WARNING: unable to enable software updates: latest .nfo URL from ZT_DEFAULTS is empty (does this platform actually support software updates?)");
  431. }
  432. #endif
  433. // Set initial supernode list
  434. _r->topology->setSupernodes(ZT_DEFAULTS.supernodes);
  435. } catch (std::bad_alloc &exc) {
  436. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  437. } catch (std::runtime_error &exc) {
  438. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  439. } catch ( ... ) {
  440. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  441. }
  442. // Start external service subprocesses, which is only used by special nodes
  443. // right now and isn't available on Windows.
  444. #ifndef __WINDOWS__
  445. try {
  446. std::string netconfServicePath(_r->homePath + ZT_PATH_SEPARATOR_S + "services.d" + ZT_PATH_SEPARATOR_S + "netconf.service");
  447. if (Utils::fileExists(netconfServicePath.c_str())) {
  448. LOG("netconf.d/netconf.service appears to exist, starting...");
  449. _r->netconfService = new Service(_r,"netconf",netconfServicePath.c_str(),&_netconfServiceMessageHandler,_r);
  450. Dictionary initMessage;
  451. initMessage["type"] = "netconf-init";
  452. initMessage["netconfId"] = _r->identity.toString(true);
  453. _r->netconfService->send(initMessage);
  454. }
  455. } catch ( ... ) {
  456. LOG("unexpected exception attempting to start services");
  457. }
  458. #endif
  459. // Core I/O loop
  460. try {
  461. /* Shut down if this file exists but fails to open. This is used on Mac to
  462. * shut down automatically on .app deletion by symlinking this to the
  463. * Info.plist file inside the ZeroTier One application. This causes the
  464. * service to die when the user throws away the app, allowing uninstallation
  465. * in the natural Mac way. */
  466. std::string shutdownIfUnreadablePath(_r->homePath + ZT_PATH_SEPARATOR_S + "shutdownIfUnreadable");
  467. uint64_t lastNetworkAutoconfCheck = Utils::now() - 5000ULL; // check autoconf again after 5s for startup
  468. uint64_t lastPingCheck = 0;
  469. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  470. uint64_t lastNetworkFingerprintCheck = 0;
  471. uint64_t lastMulticastCheck = 0;
  472. uint64_t lastSupernodePingCheck = 0;
  473. long lastDelayDelta = 0;
  474. uint64_t networkConfigurationFingerprint = 0;
  475. _r->timeOfLastResynchronize = Utils::now();
  476. while (impl->reasonForTermination == NODE_RUNNING) {
  477. /* This is how the service automatically shuts down when the OSX .app is
  478. * thrown in the trash. It's not used on any other platform for now but
  479. * could do similar things. It's disabled on Windows since it doesn't really
  480. * work there. */
  481. #ifdef __UNIX_LIKE__
  482. if (Utils::fileExists(shutdownIfUnreadablePath.c_str(),false)) {
  483. FILE *tmpf = fopen(shutdownIfUnreadablePath.c_str(),"r");
  484. if (!tmpf)
  485. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"shutdownIfUnreadable exists but is not readable");
  486. fclose(tmpf);
  487. }
  488. #endif
  489. uint64_t now = Utils::now();
  490. bool resynchronize = false;
  491. // If it looks like the computer slept and woke, resynchronize.
  492. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  493. resynchronize = true;
  494. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  495. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  496. }
  497. // If our network environment looks like it changed, resynchronize.
  498. if ((resynchronize)||((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY)) {
  499. lastNetworkFingerprintCheck = now;
  500. uint64_t fp = _r->sysEnv->getNetworkConfigurationFingerprint(_r->nc->networkTapDeviceNames());
  501. if (fp != networkConfigurationFingerprint) {
  502. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  503. networkConfigurationFingerprint = fp;
  504. resynchronize = true;
  505. }
  506. }
  507. // Supernodes do not resynchronize unless explicitly ordered via SIGHUP.
  508. if ((resynchronize)&&(_r->topology->amSupernode()))
  509. resynchronize = false;
  510. // Check for SIGHUP / force resync.
  511. if (impl->resynchronize) {
  512. impl->resynchronize = false;
  513. resynchronize = true;
  514. LOG("resynchronize forced by user, syncing with network");
  515. }
  516. if (resynchronize) {
  517. _r->tcpTunnelingEnabled = false; // turn off TCP tunneling master switch at first
  518. _r->timeOfLastResynchronize = now;
  519. }
  520. /* Supernodes are pinged separately and more aggressively. The
  521. * ZT_STARTUP_AGGRO parameter sets a limit on how rapidly they are
  522. * tried, while PingSupernodesThatNeedPing contains the logic for
  523. * determining if they need PING. */
  524. if ((now - lastSupernodePingCheck) >= ZT_STARTUP_AGGRO) {
  525. lastSupernodePingCheck = now;
  526. uint64_t lastReceiveFromAnySupernode = 0; // function object result paramter
  527. _r->topology->eachSupernodePeer(Topology::FindMostRecentDirectReceiveTimestamp(lastReceiveFromAnySupernode));
  528. // Turn on TCP tunneling master switch if we haven't heard anything since before
  529. // the last resynchronize and we've been trying long enough.
  530. uint64_t tlr = _r->timeOfLastResynchronize;
  531. if ((lastReceiveFromAnySupernode < tlr)&&((now - tlr) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT)) {
  532. TRACE("network still unreachable after %u ms, TCP TUNNELING ENABLED",(unsigned int)ZT_TCP_TUNNEL_FAILOVER_TIMEOUT);
  533. _r->tcpTunnelingEnabled = true;
  534. }
  535. _r->topology->eachSupernodePeer(Topology::PingSupernodesThatNeedPing(_r,now));
  536. }
  537. if (resynchronize) {
  538. /* Send NOP to all peers on resynchronize, directly to supernodes and
  539. * indirectly to regular nodes (to trigger RENDEZVOUS). Also clear
  540. * learned paths since they're likely no longer valid, and close
  541. * TCP sockets since they're also likely invalid. */
  542. _r->sm->closeTcpSockets();
  543. _r->topology->eachPeer(Topology::ResetActivePeers(_r,now));
  544. } else {
  545. /* Periodically check for changes in our local multicast subscriptions
  546. * and broadcast those changes to directly connected peers. */
  547. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  548. lastMulticastCheck = now;
  549. try {
  550. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  551. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  552. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  553. if ((*nw)->updateMulticastGroups())
  554. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  555. }
  556. if (toAnnounce.size())
  557. _r->sw->announceMulticastGroups(toAnnounce);
  558. } catch (std::exception &exc) {
  559. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  560. } catch ( ... ) {
  561. LOG("unexpected exception announcing multicast groups: (unknown)");
  562. }
  563. }
  564. /* Periodically ping all our non-stale direct peers unless we're a supernode.
  565. * Supernodes only ping each other (which is done above). */
  566. if (!_r->topology->amSupernode()) {
  567. if ((now - lastPingCheck) >= ZT_PING_CHECK_DELAY) {
  568. lastPingCheck = now;
  569. try {
  570. _r->topology->eachPeer(Topology::PingPeersThatNeedPing(_r,now));
  571. _r->topology->eachPeer(Topology::OpenPeersThatNeedFirewallOpener(_r,now));
  572. } catch (std::exception &exc) {
  573. LOG("unexpected exception running ping check cycle: %s",exc.what());
  574. } catch ( ... ) {
  575. LOG("unexpected exception running ping check cycle: (unkonwn)");
  576. }
  577. }
  578. }
  579. }
  580. // Update network configurations when needed.
  581. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  582. lastNetworkAutoconfCheck = now;
  583. std::vector< SharedPtr<Network> > nets(_r->nc->networks());
  584. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  585. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  586. (*n)->requestConfiguration();
  587. }
  588. }
  589. // Do periodic tasks in submodules.
  590. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  591. lastClean = now;
  592. _r->mc->clean();
  593. _r->topology->clean();
  594. _r->nc->clean();
  595. if (_r->updater)
  596. _r->updater->checkIfMaxIntervalExceeded(now);
  597. }
  598. // Sleep for loop interval or until something interesting happens.
  599. try {
  600. unsigned long delay = std::min((unsigned long)ZT_MAX_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  601. uint64_t start = Utils::now();
  602. _r->sm->poll(delay);
  603. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  604. } catch (std::exception &exc) {
  605. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  606. } catch ( ... ) {
  607. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  608. }
  609. }
  610. } catch ( ... ) {
  611. LOG("FATAL: unexpected exception in core loop: unknown exception");
  612. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  613. }
  614. return impl->terminate();
  615. }
  616. const char *Node::reasonForTermination() const
  617. throw()
  618. {
  619. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  620. return (const char *)0;
  621. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  622. }
  623. void Node::terminate(ReasonForTermination reason,const char *reasonText)
  624. throw()
  625. {
  626. ((_NodeImpl *)_impl)->reasonForTermination = reason;
  627. ((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
  628. ((_NodeImpl *)_impl)->renv.sm->whack();
  629. }
  630. void Node::resync()
  631. throw()
  632. {
  633. ((_NodeImpl *)_impl)->resynchronize = true;
  634. ((_NodeImpl *)_impl)->renv.sm->whack();
  635. }
  636. class _VersionStringMaker
  637. {
  638. public:
  639. char vs[32];
  640. _VersionStringMaker()
  641. {
  642. Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  643. }
  644. ~_VersionStringMaker() {}
  645. };
  646. static const _VersionStringMaker __versionString;
  647. const char *Node::versionString() throw() { return __versionString.vs; }
  648. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  649. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  650. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  651. } // namespace ZeroTier