Node.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 "Network.hpp"
  65. #include "MulticastGroup.hpp"
  66. #include "Mutex.hpp"
  67. #include "Multicaster.hpp"
  68. #include "Service.hpp"
  69. #include "SoftwareUpdater.hpp"
  70. #include "Buffer.hpp"
  71. #include "AntiRecursion.hpp"
  72. #include "RoutingTable.hpp"
  73. #include "HttpClient.hpp"
  74. namespace ZeroTier {
  75. struct _NodeImpl
  76. {
  77. RuntimeEnvironment renv;
  78. unsigned int udpPort,tcpPort;
  79. std::string reasonForTerminationStr;
  80. volatile Node::ReasonForTermination reasonForTermination;
  81. volatile bool started;
  82. volatile bool running;
  83. volatile bool resynchronize;
  84. volatile bool disableRootTopologyUpdates;
  85. // This function performs final node tear-down
  86. inline Node::ReasonForTermination terminate()
  87. {
  88. RuntimeEnvironment *_r = &renv;
  89. LOG("terminating: %s",reasonForTerminationStr.c_str());
  90. renv.shutdownInProgress = true;
  91. Thread::sleep(500);
  92. running = false;
  93. #ifndef __WINDOWS__
  94. delete renv.netconfService;
  95. #endif
  96. delete renv.updater; renv.updater = (SoftwareUpdater *)0;
  97. delete renv.nc; renv.nc = (NodeConfig *)0; // shut down all networks, close taps, etc.
  98. delete renv.topology; renv.topology = (Topology *)0; // now we no longer need routing info
  99. delete renv.sm; renv.sm = (SocketManager *)0; // close all sockets
  100. delete renv.sw; renv.sw = (Switch *)0; // order matters less from here down
  101. delete renv.mc; renv.mc = (Multicaster *)0;
  102. delete renv.antiRec; renv.antiRec = (AntiRecursion *)0;
  103. delete renv.http; renv.http = (HttpClient *)0;
  104. delete renv.prng; renv.prng = (CMWC4096 *)0;
  105. delete renv.log; renv.log = (Logger *)0; // but stop logging last of all
  106. return reasonForTermination;
  107. }
  108. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  109. {
  110. reasonForTerminationStr = rstr;
  111. reasonForTermination = r;
  112. return terminate();
  113. }
  114. };
  115. #ifndef __WINDOWS__ // "services" are not supported on Windows
  116. static void _netconfServiceMessageHandler(void *renv,Service &svc,const Dictionary &msg)
  117. {
  118. if (!renv)
  119. return; // sanity check
  120. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)renv;
  121. try {
  122. //TRACE("from netconf:\n%s",msg.toString().c_str());
  123. const std::string &type = msg.get("type");
  124. if (type == "ready") {
  125. LOG("received 'ready' from netconf.service, sending netconf-init with identity information...");
  126. Dictionary initMessage;
  127. initMessage["type"] = "netconf-init";
  128. initMessage["netconfId"] = _r->identity.toString(true);
  129. _r->netconfService->send(initMessage);
  130. } else if (type == "netconf-response") {
  131. uint64_t inRePacketId = strtoull(msg.get("requestId").c_str(),(char **)0,16);
  132. uint64_t nwid = strtoull(msg.get("nwid").c_str(),(char **)0,16);
  133. Address peerAddress(msg.get("peer").c_str());
  134. if (peerAddress) {
  135. if (msg.contains("error")) {
  136. Packet::ErrorCode errCode = Packet::ERROR_INVALID_REQUEST;
  137. const std::string &err = msg.get("error");
  138. if (err == "OBJ_NOT_FOUND")
  139. errCode = Packet::ERROR_OBJ_NOT_FOUND;
  140. else if (err == "ACCESS_DENIED")
  141. errCode = Packet::ERROR_NETWORK_ACCESS_DENIED_;
  142. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_ERROR);
  143. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  144. outp.append(inRePacketId);
  145. outp.append((unsigned char)errCode);
  146. outp.append(nwid);
  147. _r->sw->send(outp,true);
  148. } else if (msg.contains("netconf")) {
  149. const std::string &netconf = msg.get("netconf");
  150. if (netconf.length() < 2048) { // sanity check
  151. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_OK);
  152. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  153. outp.append(inRePacketId);
  154. outp.append(nwid);
  155. outp.append((uint16_t)netconf.length());
  156. outp.append(netconf.data(),netconf.length());
  157. outp.compress();
  158. _r->sw->send(outp,true);
  159. }
  160. }
  161. }
  162. } else if (type == "netconf-push") {
  163. if (msg.contains("to")) {
  164. Dictionary to(msg.get("to")); // key: peer address, value: comma-delimited network list
  165. for(Dictionary::iterator t(to.begin());t!=to.end();++t) {
  166. Address ztaddr(t->first);
  167. if (ztaddr) {
  168. Packet outp(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  169. char *saveptr = (char *)0;
  170. // Note: this loop trashes t->second, which is quasi-legal C++ but
  171. // shouldn't break anything as long as we don't try to use 'to'
  172. // for anything interesting after doing this.
  173. for(char *p=Utils::stok(const_cast<char *>(t->second.c_str()),",",&saveptr);(p);p=Utils::stok((char *)0,",",&saveptr)) {
  174. uint64_t nwid = Utils::hexStrToU64(p);
  175. if (nwid) {
  176. if ((outp.size() + sizeof(uint64_t)) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  177. _r->sw->send(outp,true);
  178. outp.reset(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  179. }
  180. outp.append(nwid);
  181. }
  182. }
  183. if (outp.payloadLength())
  184. _r->sw->send(outp,true);
  185. }
  186. }
  187. }
  188. }
  189. } catch (std::exception &exc) {
  190. LOG("unexpected exception parsing response from netconf service: %s",exc.what());
  191. } catch ( ... ) {
  192. LOG("unexpected exception parsing response from netconf service: unknown exception");
  193. }
  194. }
  195. #endif // !__WINDOWS__
  196. Node::Node(
  197. const char *hp,
  198. EthernetTapFactory *tf,
  199. RoutingTable *rt,
  200. unsigned int udpPort,
  201. unsigned int tcpPort,
  202. bool resetIdentity)
  203. throw() :
  204. _impl(new _NodeImpl)
  205. {
  206. _NodeImpl *impl = (_NodeImpl *)_impl;
  207. if ((hp)&&(hp[0]))
  208. impl->renv.homePath = hp;
  209. else impl->renv.homePath = ZT_DEFAULTS.defaultHomePath;
  210. impl->renv.tapFactory = tf;
  211. impl->renv.routingTable = rt;
  212. if (resetIdentity) {
  213. // Forget identity and peer database, peer keys, etc.
  214. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  215. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  216. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "peers.persist").c_str());
  217. // Truncate network config information in networks.d but leave the files since we
  218. // still want to remember any networks we have joined. This will force those networks
  219. // to be reconfigured with our newly regenerated identity after startup.
  220. std::string networksDotD(impl->renv.homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  221. std::map< std::string,bool > nwfiles(Utils::listDirectory(networksDotD.c_str()));
  222. for(std::map<std::string,bool>::iterator nwf(nwfiles.begin());nwf!=nwfiles.end();++nwf) {
  223. FILE *trun = fopen((networksDotD + ZT_PATH_SEPARATOR_S + nwf->first).c_str(),"w");
  224. if (trun)
  225. fclose(trun);
  226. }
  227. }
  228. impl->udpPort = udpPort & 0xffff;
  229. impl->tcpPort = tcpPort & 0xffff;
  230. impl->reasonForTermination = Node::NODE_RUNNING;
  231. impl->started = false;
  232. impl->running = false;
  233. impl->resynchronize = false;
  234. impl->disableRootTopologyUpdates = false;
  235. }
  236. Node::~Node()
  237. {
  238. delete (_NodeImpl *)_impl;
  239. }
  240. static void _CBztTraffic(const SharedPtr<Socket> &fromSock,void *arg,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  241. {
  242. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)arg;
  243. if ((_r->sw)&&(!_r->shutdownInProgress))
  244. _r->sw->onRemotePacket(fromSock,from,data);
  245. }
  246. static void _cbHandleGetRootTopology(void *arg,int code,const std::string &url,const std::string &body)
  247. {
  248. RuntimeEnvironment *_r = (RuntimeEnvironment *)arg;
  249. if (_r->shutdownInProgress)
  250. return;
  251. if ((code != 200)||(body.length() == 0)) {
  252. TRACE("failed to retrieve %s",url.c_str());
  253. return;
  254. }
  255. try {
  256. Dictionary rt(body);
  257. if (!Topology::authenticateRootTopology(rt)) {
  258. LOG("discarded invalid root topology update from %s (signature check failed)",url.c_str());
  259. return;
  260. }
  261. {
  262. std::string rootTopologyPath(_r->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
  263. std::string rootTopology;
  264. if (Utils::readFile(rootTopologyPath.c_str(),rootTopology)) {
  265. Dictionary alreadyHave(rootTopology);
  266. if (alreadyHave == rt) {
  267. TRACE("retrieved root topology from %s but no change (same as on disk)",url.c_str());
  268. return;
  269. } else if (alreadyHave.signatureTimestamp() > rt.signatureTimestamp()) {
  270. TRACE("retrieved root topology from %s but no change (ours is newer)",url.c_str());
  271. return;
  272. }
  273. }
  274. Utils::writeFile(rootTopologyPath.c_str(),body);
  275. }
  276. _r->topology->setSupernodes(Dictionary(rt.get("supernodes")));
  277. } catch ( ... ) {
  278. LOG("discarded invalid root topology update from %s (format invalid)",url.c_str());
  279. return;
  280. }
  281. }
  282. Node::ReasonForTermination Node::run()
  283. throw()
  284. {
  285. _NodeImpl *impl = (_NodeImpl *)_impl;
  286. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  287. impl->started = true;
  288. impl->running = true;
  289. try {
  290. #ifdef ZT_LOG_STDOUT
  291. _r->log = new Logger((const char *)0,(const char *)0,0);
  292. #else
  293. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  294. #endif
  295. LOG("starting version %s",versionString());
  296. // Create non-crypto PRNG right away in case other code in init wants to use it
  297. _r->prng = new CMWC4096();
  298. // Read identity public and secret, generating if not present
  299. bool gotId = false;
  300. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  301. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  302. std::string idser;
  303. if (Utils::readFile(identitySecretPath.c_str(),idser))
  304. gotId = _r->identity.fromString(idser);
  305. if ((gotId)&&(!_r->identity.locallyValidate()))
  306. gotId = false;
  307. if (gotId) {
  308. // Make sure identity.public matches identity.secret
  309. idser = std::string();
  310. Utils::readFile(identityPublicPath.c_str(),idser);
  311. std::string pubid(_r->identity.toString(false));
  312. if (idser != pubid) {
  313. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  314. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  315. }
  316. } else {
  317. LOG("no identity found or identity invalid, generating one... this might take a few seconds...");
  318. _r->identity.generate();
  319. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  320. idser = _r->identity.toString(true);
  321. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  322. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  323. idser = _r->identity.toString(false);
  324. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  325. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  326. }
  327. Utils::lockDownFile(identitySecretPath.c_str(),false);
  328. // Make sure networks.d exists
  329. {
  330. std::string networksDotD(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  331. #ifdef __WINDOWS__
  332. CreateDirectoryA(networksDotD.c_str(),NULL);
  333. #else
  334. mkdir(networksDotD.c_str(),0700);
  335. #endif
  336. }
  337. // Read configuration authentication token, generating if not present
  338. std::string configAuthTokenPath(_r->homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  339. std::string configAuthToken;
  340. if (!Utils::readFile(configAuthTokenPath.c_str(),configAuthToken)) {
  341. configAuthToken = "";
  342. unsigned int sr = 0;
  343. for(unsigned int i=0;i<24;++i) {
  344. Utils::getSecureRandom(&sr,sizeof(sr));
  345. configAuthToken.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[sr % 62]);
  346. }
  347. if (!Utils::writeFile(configAuthTokenPath.c_str(),configAuthToken))
  348. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write authtoken.secret (home path not writable?)");
  349. }
  350. Utils::lockDownFile(configAuthTokenPath.c_str(),false);
  351. _r->http = new HttpClient();
  352. _r->antiRec = new AntiRecursion();
  353. _r->mc = new Multicaster();
  354. _r->sw = new Switch(_r);
  355. _r->sm = new SocketManager(impl->udpPort,impl->tcpPort,&_CBztTraffic,_r);
  356. _r->topology = new Topology(_r,Utils::fileExists((_r->homePath + ZT_PATH_SEPARATOR_S + "iddb.d").c_str()));
  357. try {
  358. _r->nc = new NodeConfig(_r,configAuthToken.c_str());
  359. } catch (std::exception &exc) {
  360. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unable to initialize IPC socket: is ZeroTier One already running?");
  361. }
  362. _r->node = this;
  363. #ifdef ZT_AUTO_UPDATE
  364. if (ZT_DEFAULTS.updateLatestNfoURL.length()) {
  365. _r->updater = new SoftwareUpdater(_r);
  366. _r->updater->cleanOldUpdates(); // clean out updates.d on startup
  367. } else {
  368. LOG("WARNING: unable to enable software updates: latest .nfo URL from ZT_DEFAULTS is empty (does this platform actually support software updates?)");
  369. }
  370. #endif
  371. // Initialize root topology from defaults or root-toplogy file in home path on disk
  372. std::string rootTopologyPath(_r->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
  373. std::string rootTopology;
  374. if (!Utils::readFile(rootTopologyPath.c_str(),rootTopology))
  375. rootTopology = ZT_DEFAULTS.defaultRootTopology;
  376. try {
  377. Dictionary rt(rootTopology);
  378. if (Topology::authenticateRootTopology(rt)) {
  379. // Set supernodes if root topology signature is valid
  380. _r->topology->setSupernodes(Dictionary(rt.get("supernodes",""))); // set supernodes from root-topology
  381. // If root-topology contains noupdate=1, disable further updates and only use what was on disk
  382. impl->disableRootTopologyUpdates = (Utils::strToInt(rt.get("noupdate","0").c_str()) > 0);
  383. } else {
  384. // Revert to built-in defaults if root topology fails signature check
  385. LOG("%s failed signature check, using built-in defaults instead",rootTopologyPath.c_str());
  386. Utils::rm(rootTopologyPath.c_str());
  387. _r->topology->setSupernodes(Dictionary(Dictionary(ZT_DEFAULTS.defaultRootTopology).get("supernodes","")));
  388. impl->disableRootTopologyUpdates = false;
  389. }
  390. } catch ( ... ) {
  391. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"invalid root-topology format");
  392. }
  393. } catch (std::bad_alloc &exc) {
  394. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  395. } catch (std::runtime_error &exc) {
  396. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  397. } catch ( ... ) {
  398. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  399. }
  400. // Start external service subprocesses, which is only used by special nodes
  401. // right now and isn't available on Windows.
  402. #ifndef __WINDOWS__
  403. try {
  404. std::string netconfServicePath(_r->homePath + ZT_PATH_SEPARATOR_S + "services.d" + ZT_PATH_SEPARATOR_S + "netconf.service");
  405. if (Utils::fileExists(netconfServicePath.c_str())) {
  406. LOG("netconf.d/netconf.service appears to exist, starting...");
  407. _r->netconfService = new Service(_r,"netconf",netconfServicePath.c_str(),&_netconfServiceMessageHandler,_r);
  408. Dictionary initMessage;
  409. initMessage["type"] = "netconf-init";
  410. initMessage["netconfId"] = _r->identity.toString(true);
  411. _r->netconfService->send(initMessage);
  412. }
  413. } catch ( ... ) {
  414. LOG("unexpected exception attempting to start services");
  415. }
  416. #endif
  417. // Core I/O loop
  418. try {
  419. /* Shut down if this file exists but fails to open. This is used on Mac to
  420. * shut down automatically on .app deletion by symlinking this to the
  421. * Info.plist file inside the ZeroTier One application. This causes the
  422. * service to die when the user throws away the app, allowing uninstallation
  423. * in the natural Mac way. */
  424. std::string shutdownIfUnreadablePath(_r->homePath + ZT_PATH_SEPARATOR_S + "shutdownIfUnreadable");
  425. uint64_t lastNetworkAutoconfCheck = Utils::now() - 5000ULL; // check autoconf again after 5s for startup
  426. uint64_t lastPingCheck = 0;
  427. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  428. uint64_t lastNetworkFingerprintCheck = 0;
  429. uint64_t lastMulticastCheck = 0;
  430. uint64_t lastSupernodePingCheck = 0;
  431. uint64_t lastBeacon = 0;
  432. uint64_t lastRootTopologyFetch = 0;
  433. long lastDelayDelta = 0;
  434. uint64_t networkConfigurationFingerprint = 0;
  435. _r->timeOfLastResynchronize = Utils::now();
  436. while (impl->reasonForTermination == NODE_RUNNING) {
  437. /* This is how the service automatically shuts down when the OSX .app is
  438. * thrown in the trash. It's not used on any other platform for now but
  439. * could do similar things. It's disabled on Windows since it doesn't really
  440. * work there. */
  441. #ifdef __UNIX_LIKE__
  442. if (Utils::fileExists(shutdownIfUnreadablePath.c_str(),false)) {
  443. FILE *tmpf = fopen(shutdownIfUnreadablePath.c_str(),"r");
  444. if (!tmpf)
  445. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"shutdownIfUnreadable exists but is not readable");
  446. fclose(tmpf);
  447. }
  448. #endif
  449. uint64_t now = Utils::now();
  450. bool resynchronize = false;
  451. // If it looks like the computer slept and woke, resynchronize.
  452. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  453. resynchronize = true;
  454. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  455. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  456. }
  457. // If our network environment looks like it changed, resynchronize.
  458. if ((resynchronize)||((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY)) {
  459. lastNetworkFingerprintCheck = now;
  460. uint64_t fp = _r->routingTable->networkEnvironmentFingerprint(_r->nc->networkTapDeviceNames());
  461. if (fp != networkConfigurationFingerprint) {
  462. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  463. networkConfigurationFingerprint = fp;
  464. resynchronize = true;
  465. }
  466. }
  467. // Supernodes do not resynchronize unless explicitly ordered via SIGHUP.
  468. if ((resynchronize)&&(_r->topology->amSupernode()))
  469. resynchronize = false;
  470. // Check for SIGHUP / force resync.
  471. if (impl->resynchronize) {
  472. impl->resynchronize = false;
  473. resynchronize = true;
  474. LOG("resynchronize forced by user, syncing with network");
  475. }
  476. if (resynchronize) {
  477. _r->tcpTunnelingEnabled = false; // turn off TCP tunneling master switch at first, will be reenabled on persistent UDP failure
  478. _r->timeOfLastResynchronize = now;
  479. }
  480. /* Supernodes are pinged separately and more aggressively. The
  481. * ZT_STARTUP_AGGRO parameter sets a limit on how rapidly they are
  482. * tried, while PingSupernodesThatNeedPing contains the logic for
  483. * determining if they need PING. */
  484. if ((now - lastSupernodePingCheck) >= ZT_STARTUP_AGGRO) {
  485. lastSupernodePingCheck = now;
  486. uint64_t lastReceiveFromAnySupernode = 0; // function object result paramter
  487. _r->topology->eachSupernodePeer(Topology::FindMostRecentDirectReceiveTimestamp(lastReceiveFromAnySupernode));
  488. // Turn on TCP tunneling master switch if we haven't heard anything since before
  489. // the last resynchronize and we've been trying long enough.
  490. uint64_t tlr = _r->timeOfLastResynchronize;
  491. if ((lastReceiveFromAnySupernode < tlr)&&((now - tlr) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT)) {
  492. TRACE("network still unreachable after %u ms, TCP TUNNELING ENABLED",(unsigned int)ZT_TCP_TUNNEL_FAILOVER_TIMEOUT);
  493. _r->tcpTunnelingEnabled = true;
  494. }
  495. _r->topology->eachSupernodePeer(Topology::PingSupernodesThatNeedPing(_r,now));
  496. }
  497. if (resynchronize) {
  498. /* Send NOP to all peers on resynchronize, directly to supernodes and
  499. * indirectly to regular nodes (to trigger RENDEZVOUS). Also clear
  500. * learned paths since they're likely no longer valid, and close
  501. * TCP sockets since they're also likely invalid. */
  502. _r->sm->closeTcpSockets();
  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())&&((now - lastPingCheck) >= ZT_PING_CHECK_DELAY)) {
  527. lastPingCheck = now;
  528. try {
  529. _r->topology->eachPeer(Topology::PingPeersThatNeedPing(_r,now));
  530. } catch (std::exception &exc) {
  531. LOG("unexpected exception running ping check cycle: %s",exc.what());
  532. } catch ( ... ) {
  533. LOG("unexpected exception running ping check cycle: (unkonwn)");
  534. }
  535. }
  536. }
  537. // Update network configurations when needed.
  538. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  539. lastNetworkAutoconfCheck = now;
  540. std::vector< SharedPtr<Network> > nets(_r->nc->networks());
  541. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  542. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  543. (*n)->requestConfiguration();
  544. }
  545. }
  546. // Do periodic tasks in submodules.
  547. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  548. lastClean = now;
  549. _r->mc->clean();
  550. _r->topology->clean();
  551. _r->nc->clean();
  552. if (_r->updater)
  553. _r->updater->checkIfMaxIntervalExceeded(now);
  554. }
  555. // Send beacons to physical local LANs
  556. if ((resynchronize)||((now - lastBeacon) >= ZT_BEACON_INTERVAL)) {
  557. lastBeacon = now;
  558. char bcn[ZT_PROTO_BEACON_LENGTH];
  559. void *bcnptr = bcn;
  560. *((uint32_t *)(bcnptr)) = _r->prng->next32();
  561. bcnptr = bcn + 4;
  562. *((uint32_t *)(bcnptr)) = _r->prng->next32();
  563. _r->identity.address().copyTo(bcn + ZT_PROTO_BEACON_IDX_ADDRESS,ZT_ADDRESS_LENGTH);
  564. TRACE("sending LAN beacon to %s",ZT_DEFAULTS.v4Broadcast.toString().c_str());
  565. _r->antiRec->logOutgoingZT(bcn,ZT_PROTO_BEACON_LENGTH);
  566. _r->sm->send(ZT_DEFAULTS.v4Broadcast,false,false,bcn,ZT_PROTO_BEACON_LENGTH);
  567. }
  568. // Check for updates to root topology (supernodes) periodically
  569. if ((now - lastRootTopologyFetch) >= ZT_UPDATE_ROOT_TOPOLOGY_CHECK_INTERVAL) {
  570. lastRootTopologyFetch = now;
  571. if (!impl->disableRootTopologyUpdates) {
  572. TRACE("fetching root topology from %s",ZT_DEFAULTS.rootTopologyUpdateURL.c_str());
  573. _r->http->GET(ZT_DEFAULTS.rootTopologyUpdateURL,HttpClient::NO_HEADERS,60,&_cbHandleGetRootTopology,_r);
  574. }
  575. }
  576. // Sleep for loop interval or until something interesting happens.
  577. try {
  578. unsigned long delay = std::min((unsigned long)ZT_MAX_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  579. uint64_t start = Utils::now();
  580. _r->sm->poll(delay);
  581. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  582. } catch (std::exception &exc) {
  583. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  584. } catch ( ... ) {
  585. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  586. }
  587. }
  588. } catch ( ... ) {
  589. LOG("FATAL: unexpected exception in core loop: unknown exception");
  590. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  591. }
  592. return impl->terminate();
  593. }
  594. const char *Node::terminationMessage() const
  595. throw()
  596. {
  597. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  598. return (const char *)0;
  599. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  600. }
  601. void Node::terminate(ReasonForTermination reason,const char *reasonText)
  602. throw()
  603. {
  604. ((_NodeImpl *)_impl)->reasonForTermination = reason;
  605. ((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
  606. ((_NodeImpl *)_impl)->renv.sm->whack();
  607. }
  608. void Node::resync()
  609. throw()
  610. {
  611. ((_NodeImpl *)_impl)->resynchronize = true;
  612. ((_NodeImpl *)_impl)->renv.sm->whack();
  613. }
  614. bool Node::online()
  615. throw()
  616. {
  617. _NodeImpl *impl = (_NodeImpl *)_impl;
  618. if (!impl->running)
  619. return false;
  620. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  621. uint64_t now = Utils::now();
  622. uint64_t since = _r->timeOfLastResynchronize;
  623. std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
  624. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  625. uint64_t lastRec = (*sn)->lastDirectReceive();
  626. if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
  627. return true;
  628. }
  629. return false;
  630. }
  631. void Node::join(uint64_t nwid)
  632. throw()
  633. {
  634. _NodeImpl *impl = (_NodeImpl *)_impl;
  635. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  636. _r->nc->join(nwid);
  637. }
  638. void Node::leave(uint64_t nwid)
  639. throw()
  640. {
  641. _NodeImpl *impl = (_NodeImpl *)_impl;
  642. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  643. _r->nc->leave(nwid);
  644. }
  645. struct GatherPeerStatistics
  646. {
  647. uint64_t now;
  648. ZT1_Node_Status *status;
  649. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  650. {
  651. ++status->knownPeers;
  652. if (p->hasActiveDirectPath(now))
  653. ++status->directlyConnectedPeers;
  654. if (p->alive(now))
  655. ++status->alivePeers;
  656. }
  657. };
  658. void Node::status(ZT1_Node_Status *status)
  659. throw()
  660. {
  661. _NodeImpl *impl = (_NodeImpl *)_impl;
  662. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  663. memset(status,0,sizeof(ZT1_Node_Status));
  664. Utils::scopy(status->publicIdentity,sizeof(status->publicIdentity),_r->identity.toString(false).c_str());
  665. _r->identity.address().toString(status->address,sizeof(status->address));
  666. status->rawAddress = _r->identity.address().toInt();
  667. status->knownPeers = 0;
  668. status->supernodes = _r->topology->numSupernodes();
  669. status->directlyConnectedPeers = 0;
  670. status->alivePeers = 0;
  671. GatherPeerStatistics gps;
  672. gps.now = Utils::now();
  673. gps.status = status;
  674. _r->topology->eachPeer(gps);
  675. if (status->alivePeers > 0) {
  676. double dlsr = (double)status->directlyConnectedPeers / (double)status->alivePeers;
  677. if (dlsr > 1.0) dlsr = 1.0;
  678. if (dlsr < 0.0) dlsr = 0.0;
  679. status->directLinkSuccessRate = (float)dlsr;
  680. } else status->directLinkSuccessRate = 1.0f; // no connections to no active peers == 100% success at nothing
  681. status->online = online();
  682. status->running = impl->running;
  683. }
  684. struct CollectPeersAndPaths
  685. {
  686. std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > > data;
  687. inline void operator()(Topology &t,const SharedPtr<Peer> &p) { data.push_back(std::pair< SharedPtr<Peer>,std::vector<Path> >(p,p->paths())); }
  688. };
  689. struct SortPeersAndPathsInAscendingAddressOrder
  690. {
  691. inline bool operator()(const std::pair< SharedPtr<Peer>,std::vector<Path> > &a,const std::pair< SharedPtr<Peer>,std::vector<Path> > &b) const { return (a.first->address() < b.first->address()); }
  692. };
  693. ZT1_Node_PeerList *Node::listPeers()
  694. throw()
  695. {
  696. _NodeImpl *impl = (_NodeImpl *)_impl;
  697. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  698. CollectPeersAndPaths pp;
  699. _r->topology->eachPeer(pp);
  700. std::sort(pp.data.begin(),pp.data.end(),SortPeersAndPathsInAscendingAddressOrder());
  701. unsigned int returnBufSize = sizeof(ZT1_Node_PeerList);
  702. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p)
  703. returnBufSize += sizeof(ZT1_Node_Peer) + (sizeof(ZT1_Node_PhysicalPath) * p->second.size());
  704. char *buf = (char *)::malloc(returnBufSize);
  705. if (!buf)
  706. return (ZT1_Node_PeerList *)0;
  707. memset(buf,0,returnBufSize);
  708. ZT1_Node_PeerList *pl = (ZT1_Node_PeerList *)buf;
  709. buf += sizeof(ZT1_Node_PeerList);
  710. pl->peers = (ZT1_Node_Peer *)buf;
  711. buf += (sizeof(ZT1_Node_Peer) * pp.data.size());
  712. pl->numPeers = 0;
  713. uint64_t now = Utils::now();
  714. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p) {
  715. ZT1_Node_Peer *prec = &(pl->peers[pl->numPeers++]);
  716. if (p->first->remoteVersionKnown())
  717. Utils::snprintf(prec->remoteVersion,sizeof(prec->remoteVersion),"%u.%u.%u",p->first->remoteVersionMajor(),p->first->remoteVersionMinor(),p->first->remoteVersionRevision());
  718. p->first->address().toString(prec->address,sizeof(prec->address));
  719. prec->rawAddress = p->first->address().toInt();
  720. prec->latency = p->first->latency();
  721. prec->paths = (ZT1_Node_PhysicalPath *)buf;
  722. buf += sizeof(ZT1_Node_PhysicalPath) * p->second.size();
  723. prec->numPaths = 0;
  724. for(std::vector<Path>::iterator pi(p->second.begin());pi!=p->second.end();++pi) {
  725. ZT1_Node_PhysicalPath *path = &(prec->paths[prec->numPaths++]);
  726. path->type = static_cast<typeof(path->type)>(pi->type());
  727. if (pi->address().isV6()) {
  728. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  729. memcpy(path->address.bits,pi->address().rawIpData(),16);
  730. // TODO: zoneIndex not supported yet, but should be once echo-location works w/V6
  731. } else {
  732. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  733. memcpy(path->address.bits,pi->address().rawIpData(),4);
  734. }
  735. path->address.port = pi->address().port();
  736. Utils::scopy(path->address.ascii,sizeof(path->address.ascii),pi->address().toIpString().c_str());
  737. path->lastSend = (pi->lastSend() > 0) ? ((long)(now - pi->lastSend())) : (long)-1;
  738. path->lastReceive = (pi->lastReceived() > 0) ? ((long)(now - pi->lastReceived())) : (long)-1;
  739. path->lastPing = (pi->lastPing() > 0) ? ((long)(now - pi->lastPing())) : (long)-1;
  740. path->active = pi->active(now);
  741. path->fixed = pi->fixed();
  742. }
  743. }
  744. return pl;
  745. }
  746. // Fills out everything but ips[] and numIps, which must be done more manually
  747. static void _fillNetworkQueryResultBuffer(const SharedPtr<Network> &network,const SharedPtr<NetworkConfig> &nconf,ZT1_Node_Network *nbuf)
  748. {
  749. nbuf->nwid = network->id();
  750. Utils::snprintf(nbuf->nwidHex,sizeof(nbuf->nwidHex),"%.16llx",(unsigned long long)network->id());
  751. if (nconf) {
  752. Utils::scopy(nbuf->name,sizeof(nbuf->name),nconf->name().c_str());
  753. Utils::scopy(nbuf->description,sizeof(nbuf->description),nconf->description().c_str());
  754. }
  755. Utils::scopy(nbuf->device,sizeof(nbuf->device),network->tapDeviceName().c_str());
  756. Utils::scopy(nbuf->statusStr,sizeof(nbuf->statusStr),Network::statusString(network->status()));
  757. network->mac().toString(nbuf->macStr,sizeof(nbuf->macStr));
  758. network->mac().copyTo(nbuf->mac,sizeof(nbuf->mac));
  759. uint64_t lcu = network->lastConfigUpdate();
  760. if (lcu > 0)
  761. nbuf->configAge = (long)(Utils::now() - lcu);
  762. else nbuf->configAge = -1;
  763. nbuf->status = static_cast<typeof(nbuf->status)>(network->status());
  764. nbuf->enabled = network->enabled();
  765. nbuf->isPrivate = (nconf) ? nconf->isPrivate() : true;
  766. }
  767. ZT1_Node_Network *Node::getNetworkStatus(uint64_t nwid)
  768. throw()
  769. {
  770. _NodeImpl *impl = (_NodeImpl *)_impl;
  771. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  772. SharedPtr<Network> network(_r->nc->network(nwid));
  773. if (!network)
  774. return (ZT1_Node_Network *)0;
  775. SharedPtr<NetworkConfig> nconf(network->config2());
  776. std::set<InetAddress> ips(network->ips());
  777. char *buf = (char *)::malloc(sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  778. if (!buf)
  779. return (ZT1_Node_Network *)0;
  780. memset(buf,0,sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  781. ZT1_Node_Network *nbuf = (ZT1_Node_Network *)buf;
  782. buf += sizeof(ZT1_Node_Network);
  783. _fillNetworkQueryResultBuffer(network,nconf,nbuf);
  784. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  785. nbuf->numIps = 0;
  786. for(std::set<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  787. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  788. if (ip->isV6()) {
  789. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  790. memcpy(ipb->bits,ip->rawIpData(),16);
  791. } else {
  792. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  793. memcpy(ipb->bits,ip->rawIpData(),4);
  794. }
  795. ipb->port = ip->port();
  796. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  797. }
  798. return nbuf;
  799. }
  800. ZT1_Node_NetworkList *Node::listNetworks()
  801. throw()
  802. {
  803. _NodeImpl *impl = (_NodeImpl *)_impl;
  804. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  805. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  806. std::vector< SharedPtr<NetworkConfig> > nconfs(networks.size());
  807. std::vector< std::set<InetAddress> > ipsv(networks.size());
  808. unsigned long returnBufSize = sizeof(ZT1_Node_NetworkList);
  809. for(unsigned long i=0;i<networks.size();++i) {
  810. nconfs[i] = networks[i]->config2();
  811. ipsv[i] = networks[i]->ips();
  812. returnBufSize += sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ipsv[i].size());
  813. }
  814. char *buf = (char *)::malloc(returnBufSize);
  815. if (!buf)
  816. return (ZT1_Node_NetworkList *)0;
  817. memset(buf,0,returnBufSize);
  818. ZT1_Node_NetworkList *nl = (ZT1_Node_NetworkList *)buf;
  819. buf += sizeof(ZT1_Node_NetworkList);
  820. nl->networks = (ZT1_Node_Network *)buf;
  821. buf += sizeof(ZT1_Node_Network) * networks.size();
  822. for(unsigned long i=0;i<networks.size();++i) {
  823. ZT1_Node_Network *nbuf = &(nl->networks[nl->numNetworks++]);
  824. _fillNetworkQueryResultBuffer(networks[i],nconfs[i],nbuf);
  825. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  826. buf += sizeof(ZT1_Node_PhysicalAddress);
  827. nbuf->numIps = 0;
  828. for(std::set<InetAddress>::iterator ip(ipsv[i].begin());ip!=ipsv[i].end();++ip) {
  829. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  830. if (ip->isV6()) {
  831. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  832. memcpy(ipb->bits,ip->rawIpData(),16);
  833. } else {
  834. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  835. memcpy(ipb->bits,ip->rawIpData(),4);
  836. }
  837. ipb->port = ip->port();
  838. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  839. }
  840. }
  841. return nl;
  842. }
  843. void Node::freeQueryResult(void *qr)
  844. throw()
  845. {
  846. ::free(qr);
  847. }
  848. bool Node::updateCheck()
  849. throw()
  850. {
  851. _NodeImpl *impl = (_NodeImpl *)_impl;
  852. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  853. if (_r->updater) {
  854. _r->updater->checkNow();
  855. return true;
  856. }
  857. return false;
  858. }
  859. class _VersionStringMaker
  860. {
  861. public:
  862. char vs[32];
  863. _VersionStringMaker()
  864. {
  865. Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  866. }
  867. ~_VersionStringMaker() {}
  868. };
  869. static const _VersionStringMaker __versionString;
  870. const char *Node::versionString() throw() { return __versionString.vs; }
  871. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  872. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  873. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  874. } // namespace ZeroTier