Node.cpp 34 KB

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