Node.cpp 33 KB

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