Node.cpp 36 KB

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