Node.cpp 38 KB

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