Node.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. uint64_t lastShutdownIfUnreadableCheck = 0;
  424. long lastDelayDelta = 0;
  425. uint64_t networkConfigurationFingerprint = 0;
  426. _r->timeOfLastResynchronize = Utils::now();
  427. // We are up and running
  428. _r->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 = _r->routingTable->networkEnvironmentFingerprint(_r->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)&&(_r->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. _r->tcpTunnelingEnabled = false; // turn off TCP tunneling master switch at first, will be reenabled on persistent UDP failure
  474. _r->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. _r->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 = _r->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. _r->tcpTunnelingEnabled = true;
  490. }
  491. _r->topology->eachSupernodePeer(Topology::PingSupernodesThatNeedPing(_r,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. _r->sm->closeTcpSockets();
  499. _r->topology->eachPeer(Topology::ResetActivePeers(_r,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::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  507. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  508. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  509. if ((*nw)->updateMulticastGroups())
  510. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  511. }
  512. if (toAnnounce.size())
  513. _r->sw->announceMulticastGroups(toAnnounce);
  514. } catch (std::exception &exc) {
  515. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  516. } catch ( ... ) {
  517. LOG("unexpected exception announcing multicast groups: (unknown)");
  518. }
  519. }
  520. /* Periodically ping all our non-stale direct peers unless we're a supernode.
  521. * Supernodes only ping each other (which is done above). */
  522. if ((!_r->topology->amSupernode())&&((now - lastPingCheck) >= ZT_PING_CHECK_DELAY)) {
  523. lastPingCheck = now;
  524. try {
  525. _r->topology->eachPeer(Topology::PingPeersThatNeedPing(_r,now));
  526. } catch (std::exception &exc) {
  527. LOG("unexpected exception running ping check cycle: %s",exc.what());
  528. } catch ( ... ) {
  529. LOG("unexpected exception running ping check cycle: (unkonwn)");
  530. }
  531. }
  532. }
  533. // Update network configurations when needed.
  534. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  535. lastNetworkAutoconfCheck = now;
  536. std::vector< SharedPtr<Network> > nets(_r->nc->networks());
  537. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  538. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  539. (*n)->requestConfiguration();
  540. }
  541. }
  542. // Do periodic tasks in submodules.
  543. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  544. lastClean = now;
  545. _r->mc->clean();
  546. _r->topology->clean();
  547. _r->nc->clean();
  548. if (_r->updater)
  549. _r->updater->checkIfMaxIntervalExceeded(now);
  550. }
  551. // Send beacons to physical local LANs
  552. if ((resynchronize)||((now - lastBeacon) >= ZT_BEACON_INTERVAL)) {
  553. lastBeacon = now;
  554. char bcn[ZT_PROTO_BEACON_LENGTH];
  555. void *bcnptr = bcn;
  556. *((uint32_t *)(bcnptr)) = _r->prng->next32();
  557. bcnptr = bcn + 4;
  558. *((uint32_t *)(bcnptr)) = _r->prng->next32();
  559. _r->identity.address().copyTo(bcn + ZT_PROTO_BEACON_IDX_ADDRESS,ZT_ADDRESS_LENGTH);
  560. TRACE("sending LAN beacon to %s",ZT_DEFAULTS.v4Broadcast.toString().c_str());
  561. _r->antiRec->logOutgoingZT(bcn,ZT_PROTO_BEACON_LENGTH);
  562. _r->sm->send(ZT_DEFAULTS.v4Broadcast,false,false,bcn,ZT_PROTO_BEACON_LENGTH);
  563. }
  564. // Check for updates to root topology (supernodes) periodically
  565. if ((now - lastRootTopologyFetch) >= ZT_UPDATE_ROOT_TOPOLOGY_CHECK_INTERVAL) {
  566. lastRootTopologyFetch = now;
  567. if (!impl->disableRootTopologyUpdates) {
  568. TRACE("fetching root topology from %s",ZT_DEFAULTS.rootTopologyUpdateURL.c_str());
  569. _r->http->GET(ZT_DEFAULTS.rootTopologyUpdateURL,HttpClient::NO_HEADERS,60,&_cbHandleGetRootTopology,_r);
  570. }
  571. }
  572. // Sleep for loop interval or until something interesting happens.
  573. try {
  574. unsigned long delay = std::min((unsigned long)ZT_MAX_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  575. uint64_t start = Utils::now();
  576. _r->sm->poll(delay);
  577. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  578. } catch (std::exception &exc) {
  579. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  580. } catch ( ... ) {
  581. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  582. }
  583. }
  584. } catch ( ... ) {
  585. LOG("FATAL: unexpected exception in core loop: unknown exception");
  586. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  587. }
  588. return impl->terminate();
  589. }
  590. const char *Node::terminationMessage() const
  591. throw()
  592. {
  593. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  594. return (const char *)0;
  595. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  596. }
  597. void Node::terminate(ReasonForTermination reason,const char *reasonText)
  598. throw()
  599. {
  600. ((_NodeImpl *)_impl)->reasonForTermination = reason;
  601. ((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
  602. ((_NodeImpl *)_impl)->renv.sm->whack();
  603. }
  604. void Node::resync()
  605. throw()
  606. {
  607. ((_NodeImpl *)_impl)->resynchronize = true;
  608. ((_NodeImpl *)_impl)->renv.sm->whack();
  609. }
  610. bool Node::online()
  611. throw()
  612. {
  613. _NodeImpl *impl = (_NodeImpl *)_impl;
  614. if (!impl->running)
  615. return false;
  616. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  617. uint64_t now = Utils::now();
  618. uint64_t since = _r->timeOfLastResynchronize;
  619. std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
  620. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  621. uint64_t lastRec = (*sn)->lastDirectReceive();
  622. if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
  623. return true;
  624. }
  625. return false;
  626. }
  627. bool Node::started()
  628. throw()
  629. {
  630. _NodeImpl *impl = (_NodeImpl *)_impl;
  631. return impl->started;
  632. }
  633. bool Node::running()
  634. throw()
  635. {
  636. _NodeImpl *impl = (_NodeImpl *)_impl;
  637. return impl->running;
  638. }
  639. bool Node::initialized()
  640. throw()
  641. {
  642. _NodeImpl *impl = (_NodeImpl *)_impl;
  643. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  644. return ((_r)&&(_r->initialized));
  645. }
  646. uint64_t Node::address()
  647. throw()
  648. {
  649. _NodeImpl *impl = (_NodeImpl *)_impl;
  650. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  651. if ((!_r)||(!_r->initialized))
  652. return 0;
  653. return _r->identity.address().toInt();
  654. }
  655. void Node::join(uint64_t nwid)
  656. throw()
  657. {
  658. _NodeImpl *impl = (_NodeImpl *)_impl;
  659. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  660. _r->nc->join(nwid);
  661. }
  662. void Node::leave(uint64_t nwid)
  663. throw()
  664. {
  665. _NodeImpl *impl = (_NodeImpl *)_impl;
  666. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  667. _r->nc->leave(nwid);
  668. }
  669. struct GatherPeerStatistics
  670. {
  671. uint64_t now;
  672. ZT1_Node_Status *status;
  673. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  674. {
  675. ++status->knownPeers;
  676. if (p->hasActiveDirectPath(now))
  677. ++status->directlyConnectedPeers;
  678. if (p->alive(now))
  679. ++status->alivePeers;
  680. }
  681. };
  682. void Node::status(ZT1_Node_Status *status)
  683. throw()
  684. {
  685. _NodeImpl *impl = (_NodeImpl *)_impl;
  686. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  687. memset(status,0,sizeof(ZT1_Node_Status));
  688. Utils::scopy(status->publicIdentity,sizeof(status->publicIdentity),_r->identity.toString(false).c_str());
  689. _r->identity.address().toString(status->address,sizeof(status->address));
  690. status->rawAddress = _r->identity.address().toInt();
  691. status->knownPeers = 0;
  692. status->supernodes = _r->topology->numSupernodes();
  693. status->directlyConnectedPeers = 0;
  694. status->alivePeers = 0;
  695. GatherPeerStatistics gps;
  696. gps.now = Utils::now();
  697. gps.status = status;
  698. _r->topology->eachPeer<GatherPeerStatistics &>(gps);
  699. if (status->alivePeers > 0) {
  700. double dlsr = (double)status->directlyConnectedPeers / (double)status->alivePeers;
  701. if (dlsr > 1.0) dlsr = 1.0;
  702. if (dlsr < 0.0) dlsr = 0.0;
  703. status->directLinkSuccessRate = (float)dlsr;
  704. } else status->directLinkSuccessRate = 1.0f; // no connections to no active peers == 100% success at nothing
  705. status->online = online();
  706. status->running = impl->running;
  707. }
  708. struct CollectPeersAndPaths
  709. {
  710. std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > > data;
  711. inline void operator()(Topology &t,const SharedPtr<Peer> &p) { this->data.push_back(std::pair< SharedPtr<Peer>,std::vector<Path> >(p,p->paths())); }
  712. };
  713. struct SortPeersAndPathsInAscendingAddressOrder
  714. {
  715. 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()); }
  716. };
  717. ZT1_Node_PeerList *Node::listPeers()
  718. throw()
  719. {
  720. _NodeImpl *impl = (_NodeImpl *)_impl;
  721. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  722. CollectPeersAndPaths pp;
  723. _r->topology->eachPeer<CollectPeersAndPaths &>(pp);
  724. std::sort(pp.data.begin(),pp.data.end(),SortPeersAndPathsInAscendingAddressOrder());
  725. unsigned int returnBufSize = sizeof(ZT1_Node_PeerList);
  726. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p)
  727. returnBufSize += sizeof(ZT1_Node_Peer) + (sizeof(ZT1_Node_PhysicalPath) * p->second.size());
  728. char *buf = (char *)::malloc(returnBufSize);
  729. if (!buf)
  730. return (ZT1_Node_PeerList *)0;
  731. memset(buf,0,returnBufSize);
  732. ZT1_Node_PeerList *pl = (ZT1_Node_PeerList *)buf;
  733. buf += sizeof(ZT1_Node_PeerList);
  734. pl->peers = (ZT1_Node_Peer *)buf;
  735. buf += (sizeof(ZT1_Node_Peer) * pp.data.size());
  736. pl->numPeers = 0;
  737. uint64_t now = Utils::now();
  738. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p) {
  739. ZT1_Node_Peer *prec = &(pl->peers[pl->numPeers++]);
  740. if (p->first->remoteVersionKnown())
  741. Utils::snprintf(prec->remoteVersion,sizeof(prec->remoteVersion),"%u.%u.%u",p->first->remoteVersionMajor(),p->first->remoteVersionMinor(),p->first->remoteVersionRevision());
  742. p->first->address().toString(prec->address,sizeof(prec->address));
  743. prec->rawAddress = p->first->address().toInt();
  744. prec->latency = p->first->latency();
  745. prec->paths = (ZT1_Node_PhysicalPath *)buf;
  746. buf += sizeof(ZT1_Node_PhysicalPath) * p->second.size();
  747. prec->numPaths = 0;
  748. for(std::vector<Path>::iterator pi(p->second.begin());pi!=p->second.end();++pi) {
  749. ZT1_Node_PhysicalPath *path = &(prec->paths[prec->numPaths++]);
  750. path->type = static_cast<typeof(path->type)>(pi->type());
  751. if (pi->address().isV6()) {
  752. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  753. memcpy(path->address.bits,pi->address().rawIpData(),16);
  754. // TODO: zoneIndex not supported yet, but should be once echo-location works w/V6
  755. } else {
  756. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  757. memcpy(path->address.bits,pi->address().rawIpData(),4);
  758. }
  759. path->address.port = pi->address().port();
  760. Utils::scopy(path->address.ascii,sizeof(path->address.ascii),pi->address().toIpString().c_str());
  761. path->lastSend = (pi->lastSend() > 0) ? ((long)(now - pi->lastSend())) : (long)-1;
  762. path->lastReceive = (pi->lastReceived() > 0) ? ((long)(now - pi->lastReceived())) : (long)-1;
  763. path->lastPing = (pi->lastPing() > 0) ? ((long)(now - pi->lastPing())) : (long)-1;
  764. path->active = pi->active(now);
  765. path->fixed = pi->fixed();
  766. }
  767. }
  768. return pl;
  769. }
  770. // Fills out everything but ips[] and numIps, which must be done more manually
  771. static void _fillNetworkQueryResultBuffer(const SharedPtr<Network> &network,const SharedPtr<NetworkConfig> &nconf,ZT1_Node_Network *nbuf)
  772. {
  773. nbuf->nwid = network->id();
  774. Utils::snprintf(nbuf->nwidHex,sizeof(nbuf->nwidHex),"%.16llx",(unsigned long long)network->id());
  775. if (nconf) {
  776. Utils::scopy(nbuf->name,sizeof(nbuf->name),nconf->name().c_str());
  777. Utils::scopy(nbuf->description,sizeof(nbuf->description),nconf->description().c_str());
  778. }
  779. Utils::scopy(nbuf->device,sizeof(nbuf->device),network->tapDeviceName().c_str());
  780. Utils::scopy(nbuf->statusStr,sizeof(nbuf->statusStr),Network::statusString(network->status()));
  781. network->mac().toString(nbuf->macStr,sizeof(nbuf->macStr));
  782. network->mac().copyTo(nbuf->mac,sizeof(nbuf->mac));
  783. uint64_t lcu = network->lastConfigUpdate();
  784. if (lcu > 0)
  785. nbuf->configAge = (long)(Utils::now() - lcu);
  786. else nbuf->configAge = -1;
  787. nbuf->status = static_cast<typeof(nbuf->status)>(network->status());
  788. nbuf->enabled = network->enabled();
  789. nbuf->isPrivate = (nconf) ? nconf->isPrivate() : true;
  790. }
  791. ZT1_Node_Network *Node::getNetworkStatus(uint64_t nwid)
  792. throw()
  793. {
  794. _NodeImpl *impl = (_NodeImpl *)_impl;
  795. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  796. SharedPtr<Network> network(_r->nc->network(nwid));
  797. if (!network)
  798. return (ZT1_Node_Network *)0;
  799. SharedPtr<NetworkConfig> nconf(network->config2());
  800. std::set<InetAddress> ips(network->ips());
  801. char *buf = (char *)::malloc(sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  802. if (!buf)
  803. return (ZT1_Node_Network *)0;
  804. memset(buf,0,sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  805. ZT1_Node_Network *nbuf = (ZT1_Node_Network *)buf;
  806. buf += sizeof(ZT1_Node_Network);
  807. _fillNetworkQueryResultBuffer(network,nconf,nbuf);
  808. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  809. nbuf->numIps = 0;
  810. for(std::set<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  811. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  812. if (ip->isV6()) {
  813. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  814. memcpy(ipb->bits,ip->rawIpData(),16);
  815. } else {
  816. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  817. memcpy(ipb->bits,ip->rawIpData(),4);
  818. }
  819. ipb->port = ip->port();
  820. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  821. }
  822. return nbuf;
  823. }
  824. ZT1_Node_NetworkList *Node::listNetworks()
  825. throw()
  826. {
  827. _NodeImpl *impl = (_NodeImpl *)_impl;
  828. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  829. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  830. std::vector< SharedPtr<NetworkConfig> > nconfs(networks.size());
  831. std::vector< std::set<InetAddress> > ipsv(networks.size());
  832. unsigned long returnBufSize = sizeof(ZT1_Node_NetworkList);
  833. for(unsigned long i=0;i<networks.size();++i) {
  834. nconfs[i] = networks[i]->config2();
  835. ipsv[i] = networks[i]->ips();
  836. returnBufSize += sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ipsv[i].size());
  837. }
  838. char *buf = (char *)::malloc(returnBufSize);
  839. if (!buf)
  840. return (ZT1_Node_NetworkList *)0;
  841. memset(buf,0,returnBufSize);
  842. ZT1_Node_NetworkList *nl = (ZT1_Node_NetworkList *)buf;
  843. buf += sizeof(ZT1_Node_NetworkList);
  844. nl->networks = (ZT1_Node_Network *)buf;
  845. buf += sizeof(ZT1_Node_Network) * networks.size();
  846. for(unsigned long i=0;i<networks.size();++i) {
  847. ZT1_Node_Network *nbuf = &(nl->networks[nl->numNetworks++]);
  848. _fillNetworkQueryResultBuffer(networks[i],nconfs[i],nbuf);
  849. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  850. buf += sizeof(ZT1_Node_PhysicalAddress);
  851. nbuf->numIps = 0;
  852. for(std::set<InetAddress>::iterator ip(ipsv[i].begin());ip!=ipsv[i].end();++ip) {
  853. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  854. if (ip->isV6()) {
  855. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  856. memcpy(ipb->bits,ip->rawIpData(),16);
  857. } else {
  858. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  859. memcpy(ipb->bits,ip->rawIpData(),4);
  860. }
  861. ipb->port = ip->port();
  862. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  863. }
  864. }
  865. return nl;
  866. }
  867. void Node::freeQueryResult(void *qr)
  868. throw()
  869. {
  870. if (qr)
  871. ::free(qr);
  872. }
  873. bool Node::updateCheck()
  874. throw()
  875. {
  876. _NodeImpl *impl = (_NodeImpl *)_impl;
  877. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  878. if (_r->updater) {
  879. _r->updater->checkNow();
  880. return true;
  881. }
  882. return false;
  883. }
  884. class _VersionStringMaker
  885. {
  886. public:
  887. char vs[32];
  888. _VersionStringMaker()
  889. {
  890. Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  891. }
  892. ~_VersionStringMaker() {}
  893. };
  894. static const _VersionStringMaker __versionString;
  895. const char *Node::versionString() throw() { return __versionString.vs; }
  896. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  897. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  898. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  899. } // namespace ZeroTier