Node.cpp 34 KB

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