Node.cpp 25 KB

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