Node.cpp 34 KB

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