Node.cpp 36 KB

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