Node.cpp 25 KB

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