Node.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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 "Multicaster.hpp"
  67. #include "Mutex.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 *RR = &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 *RR = (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"] = RR->identity.toString(true);
  129. RR->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,RR->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. RR->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,RR->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. RR->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,RR->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. RR->sw->send(outp,true);
  178. outp.reset(ztaddr,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  179. }
  180. outp.append(nwid);
  181. }
  182. }
  183. if (outp.payloadLength())
  184. RR->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 *RR = (const RuntimeEnvironment *)arg;
  243. if ((RR->sw)&&(!RR->shutdownInProgress))
  244. RR->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 *RR = (RuntimeEnvironment *)arg;
  249. if (RR->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(RR->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. RR->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 *RR = (RuntimeEnvironment *)&(impl->renv);
  287. impl->started = true;
  288. impl->running = true;
  289. try {
  290. #ifdef ZT_LOG_STDOUT
  291. RR->log = new Logger((const char *)0,(const char *)0,0);
  292. #else
  293. RR->log = new Logger((RR->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. RR->prng = new CMWC4096();
  298. // Read identity public and secret, generating if not present
  299. {
  300. bool gotId = false;
  301. std::string identitySecretPath(RR->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  302. std::string identityPublicPath(RR->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  303. std::string idser;
  304. if (Utils::readFile(identitySecretPath.c_str(),idser))
  305. gotId = RR->identity.fromString(idser);
  306. if ((gotId)&&(!RR->identity.locallyValidate()))
  307. gotId = false;
  308. if (gotId) {
  309. // Make sure identity.public matches identity.secret
  310. idser = std::string();
  311. Utils::readFile(identityPublicPath.c_str(),idser);
  312. std::string pubid(RR->identity.toString(false));
  313. if (idser != pubid) {
  314. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  315. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  316. }
  317. } else {
  318. LOG("no identity found or identity invalid, generating one... this might take a few seconds...");
  319. RR->identity.generate();
  320. LOG("generated new identity: %s",RR->identity.address().toString().c_str());
  321. idser = RR->identity.toString(true);
  322. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  323. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  324. idser = RR->identity.toString(false);
  325. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  326. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  327. }
  328. Utils::lockDownFile(identitySecretPath.c_str(),false);
  329. }
  330. // Make sure networks.d exists
  331. {
  332. std::string networksDotD(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  333. #ifdef __WINDOWS__
  334. CreateDirectoryA(networksDotD.c_str(),NULL);
  335. #else
  336. mkdir(networksDotD.c_str(),0700);
  337. #endif
  338. }
  339. RR->http = new HttpClient();
  340. RR->antiRec = new AntiRecursion();
  341. RR->mc = new Multicaster(RR);
  342. RR->sw = new Switch(RR);
  343. RR->sm = new SocketManager(impl->udpPort,impl->tcpPort,&_CBztTraffic,RR);
  344. RR->topology = new Topology(RR,Utils::fileExists((RR->homePath + ZT_PATH_SEPARATOR_S + "iddb.d").c_str()));
  345. try {
  346. RR->nc = new NodeConfig(RR);
  347. } catch (std::exception &exc) {
  348. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unable to initialize IPC socket: is ZeroTier One already running?");
  349. }
  350. RR->node = this;
  351. #ifdef ZT_AUTO_UPDATE
  352. if (ZT_DEFAULTS.updateLatestNfoURL.length()) {
  353. RR->updater = new SoftwareUpdater(RR);
  354. RR->updater->cleanOldUpdates(); // clean out updates.d on startup
  355. } else {
  356. LOG("WARNING: unable to enable software updates: latest .nfo URL from ZT_DEFAULTS is empty (does this platform actually support software updates?)");
  357. }
  358. #endif
  359. // Initialize root topology from defaults or root-toplogy file in home path on disk
  360. {
  361. std::string rootTopologyPath(RR->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
  362. std::string rootTopology;
  363. if (!Utils::readFile(rootTopologyPath.c_str(),rootTopology))
  364. rootTopology = ZT_DEFAULTS.defaultRootTopology;
  365. try {
  366. Dictionary rt(rootTopology);
  367. if (Topology::authenticateRootTopology(rt)) {
  368. // Set supernodes if root topology signature is valid
  369. RR->topology->setSupernodes(Dictionary(rt.get("supernodes",""))); // set supernodes from root-topology
  370. // If root-topology contains noupdate=1, disable further updates and only use what was on disk
  371. impl->disableRootTopologyUpdates = (Utils::strToInt(rt.get("noupdate","0").c_str()) > 0);
  372. } else {
  373. // Revert to built-in defaults if root topology fails signature check
  374. LOG("%s failed signature check, using built-in defaults instead",rootTopologyPath.c_str());
  375. Utils::rm(rootTopologyPath.c_str());
  376. RR->topology->setSupernodes(Dictionary(Dictionary(ZT_DEFAULTS.defaultRootTopology).get("supernodes","")));
  377. impl->disableRootTopologyUpdates = false;
  378. }
  379. } catch ( ... ) {
  380. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"invalid root-topology format");
  381. }
  382. }
  383. } catch (std::bad_alloc &exc) {
  384. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  385. } catch (std::runtime_error &exc) {
  386. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  387. } catch ( ... ) {
  388. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  389. }
  390. // Start external service subprocesses, which is only used by special nodes
  391. // right now and isn't available on Windows.
  392. #ifndef __WINDOWS__
  393. try {
  394. std::string netconfServicePath(RR->homePath + ZT_PATH_SEPARATOR_S + "services.d" + ZT_PATH_SEPARATOR_S + "netconf.service");
  395. if (Utils::fileExists(netconfServicePath.c_str())) {
  396. LOG("netconf.d/netconf.service appears to exist, starting...");
  397. RR->netconfService = new Service(RR,"netconf",netconfServicePath.c_str(),&_netconfServiceMessageHandler,RR);
  398. Dictionary initMessage;
  399. initMessage["type"] = "netconf-init";
  400. initMessage["netconfId"] = RR->identity.toString(true);
  401. RR->netconfService->send(initMessage);
  402. }
  403. } catch ( ... ) {
  404. LOG("unexpected exception attempting to start services");
  405. }
  406. #endif
  407. // Core I/O loop
  408. try {
  409. /* Shut down if this file exists but fails to open. This is used on Mac to
  410. * shut down automatically on .app deletion by symlinking this to the
  411. * Info.plist file inside the ZeroTier One application. This causes the
  412. * service to die when the user throws away the app, allowing uninstallation
  413. * in the natural Mac way. */
  414. std::string shutdownIfUnreadablePath(RR->homePath + ZT_PATH_SEPARATOR_S + "shutdownIfUnreadable");
  415. uint64_t lastNetworkAutoconfCheck = Utils::now() - 5000ULL; // check autoconf again after 5s for startup
  416. uint64_t lastPingCheck = 0;
  417. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  418. uint64_t lastNetworkFingerprintCheck = 0;
  419. uint64_t lastMulticastCheck = 0;
  420. uint64_t lastSupernodePingCheck = 0;
  421. uint64_t lastBeacon = 0;
  422. uint64_t lastRootTopologyFetch = 0;
  423. uint64_t lastShutdownIfUnreadableCheck = 0;
  424. long lastDelayDelta = 0;
  425. uint64_t networkConfigurationFingerprint = 0;
  426. RR->timeOfLastResynchronize = Utils::now();
  427. // We are up and running
  428. RR->initialized = true;
  429. while (impl->reasonForTermination == NODE_RUNNING) {
  430. uint64_t now = Utils::now();
  431. bool resynchronize = false;
  432. /* This is how the service automatically shuts down when the OSX .app is
  433. * thrown in the trash. It's not used on any other platform for now but
  434. * could do similar things. It's disabled on Windows since it doesn't really
  435. * work there. */
  436. #ifdef __UNIX_LIKE__
  437. if ((now - lastShutdownIfUnreadableCheck) > 10000) {
  438. lastShutdownIfUnreadableCheck = now;
  439. if (Utils::fileExists(shutdownIfUnreadablePath.c_str(),false)) {
  440. int tmpfd = ::open(shutdownIfUnreadablePath.c_str(),O_RDONLY,0);
  441. if (tmpfd < 0) {
  442. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"shutdownIfUnreadable exists but is not readable");
  443. } else ::close(tmpfd);
  444. }
  445. }
  446. #endif
  447. // If it looks like the computer slept and woke, resynchronize.
  448. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  449. resynchronize = true;
  450. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  451. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  452. }
  453. // If our network environment looks like it changed, resynchronize.
  454. if ((resynchronize)||((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY)) {
  455. lastNetworkFingerprintCheck = now;
  456. uint64_t fp = RR->routingTable->networkEnvironmentFingerprint(RR->nc->networkTapDeviceNames());
  457. if (fp != networkConfigurationFingerprint) {
  458. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  459. networkConfigurationFingerprint = fp;
  460. resynchronize = true;
  461. }
  462. }
  463. // Supernodes do not resynchronize unless explicitly ordered via SIGHUP.
  464. if ((resynchronize)&&(RR->topology->amSupernode()))
  465. resynchronize = false;
  466. // Check for SIGHUP / force resync.
  467. if (impl->resynchronize) {
  468. impl->resynchronize = false;
  469. resynchronize = true;
  470. LOG("resynchronize forced by user, syncing with network");
  471. }
  472. if (resynchronize) {
  473. RR->tcpTunnelingEnabled = false; // turn off TCP tunneling master switch at first, will be reenabled on persistent UDP failure
  474. RR->timeOfLastResynchronize = now;
  475. }
  476. /* Supernodes are pinged separately and more aggressively. The
  477. * ZT_STARTUP_AGGRO parameter sets a limit on how rapidly they are
  478. * tried, while PingSupernodesThatNeedPing contains the logic for
  479. * determining if they need PING. */
  480. if ((now - lastSupernodePingCheck) >= ZT_STARTUP_AGGRO) {
  481. lastSupernodePingCheck = now;
  482. uint64_t lastReceiveFromAnySupernode = 0; // function object result paramter
  483. RR->topology->eachSupernodePeer(Topology::FindMostRecentDirectReceiveTimestamp(lastReceiveFromAnySupernode));
  484. // Turn on TCP tunneling master switch if we haven't heard anything since before
  485. // the last resynchronize and we've been trying long enough.
  486. uint64_t tlr = RR->timeOfLastResynchronize;
  487. if ((lastReceiveFromAnySupernode < tlr)&&((now - tlr) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT)) {
  488. TRACE("network still unreachable after %u ms, TCP TUNNELING ENABLED",(unsigned int)ZT_TCP_TUNNEL_FAILOVER_TIMEOUT);
  489. RR->tcpTunnelingEnabled = true;
  490. }
  491. RR->topology->eachSupernodePeer(Topology::PingSupernodesThatNeedPing(RR,now));
  492. }
  493. if (resynchronize) {
  494. /* Send NOP to all peers on resynchronize, directly to supernodes and
  495. * indirectly to regular nodes (to trigger RENDEZVOUS). Also clear
  496. * learned paths since they're likely no longer valid, and close
  497. * TCP sockets since they're also likely invalid. */
  498. RR->sm->closeTcpSockets();
  499. RR->topology->eachPeer(Topology::ResetActivePeers(RR,now));
  500. } else {
  501. /* Periodically check for changes in our local multicast subscriptions
  502. * and broadcast those changes to directly connected peers. */
  503. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  504. lastMulticastCheck = now;
  505. try {
  506. std::vector< SharedPtr<Network> > networks(RR->nc->networks());
  507. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw)
  508. (*nw)->updateMulticastGroups();
  509. } catch (std::exception &exc) {
  510. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  511. } catch ( ... ) {
  512. LOG("unexpected exception announcing multicast groups: (unknown)");
  513. }
  514. }
  515. /* Periodically ping all our non-stale direct peers unless we're a supernode.
  516. * Supernodes only ping each other (which is done above). */
  517. if ((!RR->topology->amSupernode())&&((now - lastPingCheck) >= ZT_PING_CHECK_DELAY)) {
  518. lastPingCheck = now;
  519. try {
  520. RR->topology->eachPeer(Topology::PingPeersThatNeedPing(RR,now));
  521. } catch (std::exception &exc) {
  522. LOG("unexpected exception running ping check cycle: %s",exc.what());
  523. } catch ( ... ) {
  524. LOG("unexpected exception running ping check cycle: (unkonwn)");
  525. }
  526. }
  527. }
  528. // Update network configurations when needed.
  529. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  530. lastNetworkAutoconfCheck = now;
  531. std::vector< SharedPtr<Network> > nets(RR->nc->networks());
  532. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  533. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  534. (*n)->requestConfiguration();
  535. }
  536. }
  537. // Do periodic tasks in submodules.
  538. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  539. lastClean = now;
  540. RR->topology->clean(now);
  541. RR->mc->clean(now);
  542. RR->nc->clean();
  543. if (RR->updater)
  544. RR->updater->checkIfMaxIntervalExceeded(now);
  545. }
  546. // Send beacons to physical local LANs
  547. if ((resynchronize)||((now - lastBeacon) >= ZT_BEACON_INTERVAL)) {
  548. lastBeacon = now;
  549. char bcn[ZT_PROTO_BEACON_LENGTH];
  550. void *bcnptr = bcn;
  551. *((uint32_t *)(bcnptr)) = RR->prng->next32();
  552. bcnptr = bcn + 4;
  553. *((uint32_t *)(bcnptr)) = RR->prng->next32();
  554. RR->identity.address().copyTo(bcn + ZT_PROTO_BEACON_IDX_ADDRESS,ZT_ADDRESS_LENGTH);
  555. TRACE("sending LAN beacon to %s",ZT_DEFAULTS.v4Broadcast.toString().c_str());
  556. RR->antiRec->logOutgoingZT(bcn,ZT_PROTO_BEACON_LENGTH);
  557. RR->sm->send(ZT_DEFAULTS.v4Broadcast,false,false,bcn,ZT_PROTO_BEACON_LENGTH);
  558. }
  559. // Check for updates to root topology (supernodes) periodically
  560. if ((now - lastRootTopologyFetch) >= ZT_UPDATE_ROOT_TOPOLOGY_CHECK_INTERVAL) {
  561. lastRootTopologyFetch = now;
  562. if (!impl->disableRootTopologyUpdates) {
  563. TRACE("fetching root topology from %s",ZT_DEFAULTS.rootTopologyUpdateURL.c_str());
  564. RR->http->GET(ZT_DEFAULTS.rootTopologyUpdateURL,HttpClient::NO_HEADERS,60,&_cbHandleGetRootTopology,RR);
  565. }
  566. }
  567. // Sleep for loop interval or until something interesting happens.
  568. try {
  569. unsigned long delay = std::min((unsigned long)ZT_MAX_SERVICE_LOOP_INTERVAL,RR->sw->doTimerTasks());
  570. uint64_t start = Utils::now();
  571. RR->sm->poll(delay);
  572. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  573. } catch (std::exception &exc) {
  574. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  575. } catch ( ... ) {
  576. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  577. }
  578. }
  579. } catch ( ... ) {
  580. LOG("FATAL: unexpected exception in core loop: unknown exception");
  581. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  582. }
  583. return impl->terminate();
  584. }
  585. const char *Node::terminationMessage() const
  586. throw()
  587. {
  588. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  589. return (const char *)0;
  590. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  591. }
  592. void Node::terminate(ReasonForTermination reason,const char *reasonText)
  593. throw()
  594. {
  595. ((_NodeImpl *)_impl)->reasonForTermination = reason;
  596. ((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
  597. ((_NodeImpl *)_impl)->renv.sm->whack();
  598. }
  599. void Node::resync()
  600. throw()
  601. {
  602. ((_NodeImpl *)_impl)->resynchronize = true;
  603. ((_NodeImpl *)_impl)->renv.sm->whack();
  604. }
  605. bool Node::online()
  606. throw()
  607. {
  608. _NodeImpl *impl = (_NodeImpl *)_impl;
  609. if (!impl->running)
  610. return false;
  611. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  612. uint64_t now = Utils::now();
  613. uint64_t since = RR->timeOfLastResynchronize;
  614. std::vector< SharedPtr<Peer> > snp(RR->topology->supernodePeers());
  615. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  616. uint64_t lastRec = (*sn)->lastDirectReceive();
  617. if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
  618. return true;
  619. }
  620. return false;
  621. }
  622. bool Node::started()
  623. throw()
  624. {
  625. _NodeImpl *impl = (_NodeImpl *)_impl;
  626. return impl->started;
  627. }
  628. bool Node::running()
  629. throw()
  630. {
  631. _NodeImpl *impl = (_NodeImpl *)_impl;
  632. return impl->running;
  633. }
  634. bool Node::initialized()
  635. throw()
  636. {
  637. _NodeImpl *impl = (_NodeImpl *)_impl;
  638. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  639. return ((RR)&&(RR->initialized));
  640. }
  641. uint64_t Node::address()
  642. throw()
  643. {
  644. _NodeImpl *impl = (_NodeImpl *)_impl;
  645. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  646. if ((!RR)||(!RR->initialized))
  647. return 0;
  648. return RR->identity.address().toInt();
  649. }
  650. void Node::join(uint64_t nwid)
  651. throw()
  652. {
  653. _NodeImpl *impl = (_NodeImpl *)_impl;
  654. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  655. RR->nc->join(nwid);
  656. }
  657. void Node::leave(uint64_t nwid)
  658. throw()
  659. {
  660. _NodeImpl *impl = (_NodeImpl *)_impl;
  661. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  662. RR->nc->leave(nwid);
  663. }
  664. struct GatherPeerStatistics
  665. {
  666. uint64_t now;
  667. ZT1_Node_Status *status;
  668. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  669. {
  670. ++status->knownPeers;
  671. if (p->hasActiveDirectPath(now))
  672. ++status->directlyConnectedPeers;
  673. if (p->alive(now))
  674. ++status->alivePeers;
  675. }
  676. };
  677. void Node::status(ZT1_Node_Status *status)
  678. throw()
  679. {
  680. _NodeImpl *impl = (_NodeImpl *)_impl;
  681. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  682. memset(status,0,sizeof(ZT1_Node_Status));
  683. Utils::scopy(status->publicIdentity,sizeof(status->publicIdentity),RR->identity.toString(false).c_str());
  684. RR->identity.address().toString(status->address,sizeof(status->address));
  685. status->rawAddress = RR->identity.address().toInt();
  686. status->knownPeers = 0;
  687. status->supernodes = RR->topology->numSupernodes();
  688. status->directlyConnectedPeers = 0;
  689. status->alivePeers = 0;
  690. GatherPeerStatistics gps;
  691. gps.now = Utils::now();
  692. gps.status = status;
  693. RR->topology->eachPeer<GatherPeerStatistics &>(gps);
  694. if (status->alivePeers > 0) {
  695. double dlsr = (double)status->directlyConnectedPeers / (double)status->alivePeers;
  696. if (dlsr > 1.0) dlsr = 1.0;
  697. if (dlsr < 0.0) dlsr = 0.0;
  698. status->directLinkSuccessRate = (float)dlsr;
  699. } else status->directLinkSuccessRate = 1.0f; // no connections to no active peers == 100% success at nothing
  700. status->online = online();
  701. status->running = impl->running;
  702. }
  703. struct CollectPeersAndPaths
  704. {
  705. std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > > data;
  706. inline void operator()(Topology &t,const SharedPtr<Peer> &p) { this->data.push_back(std::pair< SharedPtr<Peer>,std::vector<Path> >(p,p->paths())); }
  707. };
  708. struct SortPeersAndPathsInAscendingAddressOrder
  709. {
  710. 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()); }
  711. };
  712. ZT1_Node_PeerList *Node::listPeers()
  713. throw()
  714. {
  715. _NodeImpl *impl = (_NodeImpl *)_impl;
  716. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  717. CollectPeersAndPaths pp;
  718. RR->topology->eachPeer<CollectPeersAndPaths &>(pp);
  719. std::sort(pp.data.begin(),pp.data.end(),SortPeersAndPathsInAscendingAddressOrder());
  720. unsigned int returnBufSize = sizeof(ZT1_Node_PeerList);
  721. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p)
  722. returnBufSize += sizeof(ZT1_Node_Peer) + (sizeof(ZT1_Node_PhysicalPath) * p->second.size());
  723. char *buf = (char *)::malloc(returnBufSize);
  724. if (!buf)
  725. return (ZT1_Node_PeerList *)0;
  726. memset(buf,0,returnBufSize);
  727. ZT1_Node_PeerList *pl = (ZT1_Node_PeerList *)buf;
  728. buf += sizeof(ZT1_Node_PeerList);
  729. pl->peers = (ZT1_Node_Peer *)buf;
  730. buf += (sizeof(ZT1_Node_Peer) * pp.data.size());
  731. pl->numPeers = 0;
  732. uint64_t now = Utils::now();
  733. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p) {
  734. ZT1_Node_Peer *prec = &(pl->peers[pl->numPeers++]);
  735. if (p->first->remoteVersionKnown())
  736. Utils::snprintf(prec->remoteVersion,sizeof(prec->remoteVersion),"%u.%u.%u",p->first->remoteVersionMajor(),p->first->remoteVersionMinor(),p->first->remoteVersionRevision());
  737. p->first->address().toString(prec->address,sizeof(prec->address));
  738. prec->rawAddress = p->first->address().toInt();
  739. prec->latency = p->first->latency();
  740. prec->paths = (ZT1_Node_PhysicalPath *)buf;
  741. buf += sizeof(ZT1_Node_PhysicalPath) * p->second.size();
  742. prec->numPaths = 0;
  743. for(std::vector<Path>::iterator pi(p->second.begin());pi!=p->second.end();++pi) {
  744. ZT1_Node_PhysicalPath *path = &(prec->paths[prec->numPaths++]);
  745. path->type = static_cast<typeof(path->type)>(pi->type());
  746. if (pi->address().isV6()) {
  747. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  748. memcpy(path->address.bits,pi->address().rawIpData(),16);
  749. // TODO: zoneIndex not supported yet, but should be once echo-location works w/V6
  750. } else {
  751. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  752. memcpy(path->address.bits,pi->address().rawIpData(),4);
  753. }
  754. path->address.port = pi->address().port();
  755. Utils::scopy(path->address.ascii,sizeof(path->address.ascii),pi->address().toIpString().c_str());
  756. path->lastSend = (pi->lastSend() > 0) ? ((long)(now - pi->lastSend())) : (long)-1;
  757. path->lastReceive = (pi->lastReceived() > 0) ? ((long)(now - pi->lastReceived())) : (long)-1;
  758. path->lastPing = (pi->lastPing() > 0) ? ((long)(now - pi->lastPing())) : (long)-1;
  759. path->active = pi->active(now);
  760. path->fixed = pi->fixed();
  761. }
  762. }
  763. return pl;
  764. }
  765. // Fills out everything but ips[] and numIps, which must be done more manually
  766. static void _fillNetworkQueryResultBuffer(const SharedPtr<Network> &network,const SharedPtr<NetworkConfig> &nconf,ZT1_Node_Network *nbuf)
  767. {
  768. nbuf->nwid = network->id();
  769. Utils::snprintf(nbuf->nwidHex,sizeof(nbuf->nwidHex),"%.16llx",(unsigned long long)network->id());
  770. if (nconf) {
  771. Utils::scopy(nbuf->name,sizeof(nbuf->name),nconf->name().c_str());
  772. Utils::scopy(nbuf->description,sizeof(nbuf->description),nconf->description().c_str());
  773. }
  774. Utils::scopy(nbuf->device,sizeof(nbuf->device),network->tapDeviceName().c_str());
  775. Utils::scopy(nbuf->statusStr,sizeof(nbuf->statusStr),Network::statusString(network->status()));
  776. network->mac().toString(nbuf->macStr,sizeof(nbuf->macStr));
  777. network->mac().copyTo(nbuf->mac,sizeof(nbuf->mac));
  778. uint64_t lcu = network->lastConfigUpdate();
  779. if (lcu > 0)
  780. nbuf->configAge = (long)(Utils::now() - lcu);
  781. else nbuf->configAge = -1;
  782. nbuf->status = static_cast<typeof(nbuf->status)>(network->status());
  783. nbuf->enabled = network->enabled();
  784. nbuf->isPrivate = (nconf) ? nconf->isPrivate() : true;
  785. }
  786. ZT1_Node_Network *Node::getNetworkStatus(uint64_t nwid)
  787. throw()
  788. {
  789. _NodeImpl *impl = (_NodeImpl *)_impl;
  790. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  791. SharedPtr<Network> network(RR->nc->network(nwid));
  792. if (!network)
  793. return (ZT1_Node_Network *)0;
  794. SharedPtr<NetworkConfig> nconf(network->config2());
  795. std::set<InetAddress> ips(network->ips());
  796. char *buf = (char *)::malloc(sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  797. if (!buf)
  798. return (ZT1_Node_Network *)0;
  799. memset(buf,0,sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  800. ZT1_Node_Network *nbuf = (ZT1_Node_Network *)buf;
  801. buf += sizeof(ZT1_Node_Network);
  802. _fillNetworkQueryResultBuffer(network,nconf,nbuf);
  803. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  804. nbuf->numIps = 0;
  805. for(std::set<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  806. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  807. if (ip->isV6()) {
  808. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  809. memcpy(ipb->bits,ip->rawIpData(),16);
  810. } else {
  811. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  812. memcpy(ipb->bits,ip->rawIpData(),4);
  813. }
  814. ipb->port = ip->port();
  815. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  816. }
  817. return nbuf;
  818. }
  819. ZT1_Node_NetworkList *Node::listNetworks()
  820. throw()
  821. {
  822. _NodeImpl *impl = (_NodeImpl *)_impl;
  823. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  824. std::vector< SharedPtr<Network> > networks(RR->nc->networks());
  825. std::vector< SharedPtr<NetworkConfig> > nconfs(networks.size());
  826. std::vector< std::set<InetAddress> > ipsv(networks.size());
  827. unsigned long returnBufSize = sizeof(ZT1_Node_NetworkList);
  828. for(unsigned long i=0;i<networks.size();++i) {
  829. nconfs[i] = networks[i]->config2();
  830. ipsv[i] = networks[i]->ips();
  831. returnBufSize += sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ipsv[i].size());
  832. }
  833. char *buf = (char *)::malloc(returnBufSize);
  834. if (!buf)
  835. return (ZT1_Node_NetworkList *)0;
  836. memset(buf,0,returnBufSize);
  837. ZT1_Node_NetworkList *nl = (ZT1_Node_NetworkList *)buf;
  838. buf += sizeof(ZT1_Node_NetworkList);
  839. nl->networks = (ZT1_Node_Network *)buf;
  840. buf += sizeof(ZT1_Node_Network) * networks.size();
  841. for(unsigned long i=0;i<networks.size();++i) {
  842. ZT1_Node_Network *nbuf = &(nl->networks[nl->numNetworks++]);
  843. _fillNetworkQueryResultBuffer(networks[i],nconfs[i],nbuf);
  844. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  845. buf += sizeof(ZT1_Node_PhysicalAddress);
  846. nbuf->numIps = 0;
  847. for(std::set<InetAddress>::iterator ip(ipsv[i].begin());ip!=ipsv[i].end();++ip) {
  848. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  849. if (ip->isV6()) {
  850. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  851. memcpy(ipb->bits,ip->rawIpData(),16);
  852. } else {
  853. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  854. memcpy(ipb->bits,ip->rawIpData(),4);
  855. }
  856. ipb->port = ip->port();
  857. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  858. }
  859. }
  860. return nl;
  861. }
  862. void Node::freeQueryResult(void *qr)
  863. throw()
  864. {
  865. if (qr)
  866. ::free(qr);
  867. }
  868. bool Node::updateCheck()
  869. throw()
  870. {
  871. _NodeImpl *impl = (_NodeImpl *)_impl;
  872. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  873. if (RR->updater) {
  874. RR->updater->checkNow();
  875. return true;
  876. }
  877. return false;
  878. }
  879. class _VersionStringMaker
  880. {
  881. public:
  882. char vs[32];
  883. _VersionStringMaker()
  884. {
  885. Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  886. }
  887. ~_VersionStringMaker() {}
  888. };
  889. static const _VersionStringMaker __versionString;
  890. const char *Node::versionString() throw() { return __versionString.vs; }
  891. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  892. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  893. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  894. } // namespace ZeroTier