Node.cpp 33 KB

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