Node.cpp 26 KB

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