Node.cpp 33 KB

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