Node.cpp 24 KB

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