Node.cpp 37 KB

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