Node.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <errno.h>
  31. #include <map>
  32. #include <set>
  33. #include <utility>
  34. #include <algorithm>
  35. #include <list>
  36. #include <vector>
  37. #include <string>
  38. #include "Condition.hpp"
  39. #include "Node.hpp"
  40. #include "Topology.hpp"
  41. #include "Demarc.hpp"
  42. #include "Packet.hpp"
  43. #include "Switch.hpp"
  44. #include "Utils.hpp"
  45. #include "EthernetTap.hpp"
  46. #include "Logger.hpp"
  47. #include "Constants.hpp"
  48. #include "InetAddress.hpp"
  49. #include "Salsa20.hpp"
  50. #include "HMAC.hpp"
  51. #include "RuntimeEnvironment.hpp"
  52. #include "NodeConfig.hpp"
  53. #include "Defaults.hpp"
  54. #include "SysEnv.hpp"
  55. #include "Network.hpp"
  56. #include "MulticastGroup.hpp"
  57. #include "Mutex.hpp"
  58. #include "Multicaster.hpp"
  59. #include "CMWC4096.hpp"
  60. #include "Service.hpp"
  61. #ifdef __WINDOWS__
  62. #include <Windows.h>
  63. #else
  64. #include <fcntl.h>
  65. #include <unistd.h>
  66. #include <signal.h>
  67. #include <sys/file.h>
  68. #include <sys/stat.h>
  69. #endif
  70. #include "../version.h"
  71. namespace ZeroTier {
  72. struct _LocalClientImpl
  73. {
  74. unsigned char key[32];
  75. UdpSocket *sock;
  76. void (*resultHandler)(void *,unsigned long,const char *);
  77. void *arg;
  78. InetAddress localDestAddr;
  79. Mutex inUseLock;
  80. };
  81. static void _CBlocalClientHandler(UdpSocket *sock,void *arg,const InetAddress &remoteAddr,const void *data,unsigned int len)
  82. {
  83. _LocalClientImpl *impl = (_LocalClientImpl *)arg;
  84. if (!impl)
  85. return;
  86. if (!impl->resultHandler)
  87. return; // sanity check
  88. Mutex::Lock _l(impl->inUseLock);
  89. try {
  90. unsigned long convId = 0;
  91. std::vector<std::string> results;
  92. if (!NodeConfig::decodeControlMessagePacket(impl->key,data,len,convId,results))
  93. return;
  94. for(std::vector<std::string>::iterator r(results.begin());r!=results.end();++r)
  95. impl->resultHandler(impl->arg,convId,r->c_str());
  96. } catch ( ... ) {}
  97. }
  98. Node::LocalClient::LocalClient(const char *authToken,void (*resultHandler)(void *,unsigned long,const char *),void *arg)
  99. throw() :
  100. _impl((void *)0)
  101. {
  102. _LocalClientImpl *impl = new _LocalClientImpl;
  103. UdpSocket *sock = (UdpSocket *)0;
  104. for(unsigned int i=0;i<5000;++i) {
  105. try {
  106. sock = new UdpSocket(true,32768 + (rand() % 20000),false,&_CBlocalClientHandler,impl);
  107. break;
  108. } catch ( ... ) {
  109. sock = (UdpSocket *)0;
  110. }
  111. }
  112. // If socket fails to bind, there's a big problem like missing IPv4 stack
  113. if (sock) {
  114. SHA256_CTX sha;
  115. SHA256_Init(&sha);
  116. SHA256_Update(&sha,authToken,strlen(authToken));
  117. SHA256_Final(impl->key,&sha);
  118. impl->sock = sock;
  119. impl->resultHandler = resultHandler;
  120. impl->arg = arg;
  121. impl->localDestAddr = InetAddress::LO4;
  122. impl->localDestAddr.setPort(ZT_CONTROL_UDP_PORT);
  123. _impl = impl;
  124. } else delete impl;
  125. }
  126. Node::LocalClient::~LocalClient()
  127. {
  128. if (_impl) {
  129. ((_LocalClientImpl *)_impl)->inUseLock.lock();
  130. delete ((_LocalClientImpl *)_impl)->sock;
  131. ((_LocalClientImpl *)_impl)->inUseLock.unlock();
  132. delete ((_LocalClientImpl *)_impl);
  133. }
  134. }
  135. unsigned long Node::LocalClient::send(const char *command)
  136. throw()
  137. {
  138. if (!_impl)
  139. return 0;
  140. _LocalClientImpl *impl = (_LocalClientImpl *)_impl;
  141. Mutex::Lock _l(impl->inUseLock);
  142. try {
  143. uint32_t convId = (uint32_t)rand();
  144. if (!convId)
  145. convId = 1;
  146. std::vector<std::string> tmp;
  147. tmp.push_back(std::string(command));
  148. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > packets(NodeConfig::encodeControlMessage(impl->key,convId,tmp));
  149. for(std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> >::iterator p(packets.begin());p!=packets.end();++p)
  150. impl->sock->send(impl->localDestAddr,p->data(),p->size(),-1);
  151. return convId;
  152. } catch ( ... ) {
  153. return 0;
  154. }
  155. }
  156. struct _NodeImpl
  157. {
  158. RuntimeEnvironment renv;
  159. std::string reasonForTerminationStr;
  160. Node::ReasonForTermination reasonForTermination;
  161. volatile bool started;
  162. volatile bool running;
  163. volatile bool terminateNow;
  164. // Helper used to rapidly terminate from run()
  165. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  166. {
  167. RuntimeEnvironment *_r = &renv;
  168. LOG("terminating: %s",rstr);
  169. reasonForTerminationStr = rstr;
  170. reasonForTermination = r;
  171. running = false;
  172. return r;
  173. }
  174. };
  175. #ifndef __WINDOWS__
  176. static void _netconfServiceMessageHandler(void *renv,Service &svc,const Dictionary &msg)
  177. {
  178. if (!renv)
  179. return; // sanity check
  180. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)renv;
  181. try {
  182. //TRACE("from netconf:\n%s",msg.toString().c_str());
  183. const std::string &type = msg.get("type");
  184. if (type == "netconf-response") {
  185. uint64_t inRePacketId = strtoull(msg.get("requestId").c_str(),(char **)0,16);
  186. uint64_t nwid = strtoull(msg.get("nwid").c_str(),(char **)0,16);
  187. Address peerAddress(msg.get("peer").c_str());
  188. if (peerAddress) {
  189. if (msg.contains("error")) {
  190. Packet::ErrorCode errCode = Packet::ERROR_INVALID_REQUEST;
  191. const std::string &err = msg.get("error");
  192. if (err == "NOT_FOUND")
  193. errCode = Packet::ERROR_NOT_FOUND;
  194. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_ERROR);
  195. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  196. outp.append(inRePacketId);
  197. outp.append((unsigned char)errCode);
  198. outp.append(nwid);
  199. _r->sw->send(outp,true);
  200. } else if (msg.contains("netconf")) {
  201. const std::string &netconf = msg.get("netconf");
  202. if (netconf.length() < 2048) { // sanity check
  203. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_OK);
  204. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  205. outp.append(inRePacketId);
  206. outp.append(nwid);
  207. outp.append((uint16_t)netconf.length());
  208. outp.append(netconf.data(),netconf.length());
  209. outp.compress();
  210. _r->sw->send(outp,true);
  211. }
  212. }
  213. }
  214. }
  215. } catch (std::exception &exc) {
  216. LOG("unexpected exception parsing response from netconf service: %s",exc.what());
  217. } catch ( ... ) {
  218. LOG("unexpected exception parsing response from netconf service: unknown exception");
  219. }
  220. }
  221. #endif // !__WINDOWS__
  222. Node::Node(const char *hp)
  223. throw() :
  224. _impl(new _NodeImpl)
  225. {
  226. _NodeImpl *impl = (_NodeImpl *)_impl;
  227. impl->renv.homePath = hp;
  228. impl->reasonForTermination = Node::NODE_RUNNING;
  229. impl->started = false;
  230. impl->running = false;
  231. impl->terminateNow = false;
  232. }
  233. Node::~Node()
  234. {
  235. _NodeImpl *impl = (_NodeImpl *)_impl;
  236. #ifndef __WINDOWS__
  237. delete impl->renv.netconfService;
  238. #endif
  239. delete impl->renv.nc;
  240. delete impl->renv.sysEnv;
  241. delete impl->renv.topology;
  242. delete impl->renv.sw;
  243. delete impl->renv.multicaster;
  244. delete impl->renv.demarc;
  245. delete impl->renv.prng;
  246. delete impl->renv.log;
  247. delete impl;
  248. }
  249. /**
  250. * Execute node in current thread
  251. *
  252. * This does not return until the node shuts down. Shutdown may be caused
  253. * by an internally detected condition such as a new upgrade being
  254. * available or a fatal error, or it may be signaled externally using
  255. * the terminate() method.
  256. *
  257. * @return Reason for termination
  258. */
  259. Node::ReasonForTermination Node::run()
  260. throw()
  261. {
  262. _NodeImpl *impl = (_NodeImpl *)_impl;
  263. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  264. impl->started = true;
  265. impl->running = true;
  266. try {
  267. #ifdef ZT_LOG_STDOUT
  268. _r->log = new Logger((const char *)0,(const char *)0,0);
  269. #else
  270. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  271. #endif
  272. TRACE("initializing...");
  273. // Create non-crypto PRNG right away in case other code in init wants to use it
  274. _r->prng = new CMWC4096();
  275. bool gotId = false;
  276. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  277. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  278. std::string idser;
  279. if (Utils::readFile(identitySecretPath.c_str(),idser))
  280. gotId = _r->identity.fromString(idser);
  281. if (gotId) {
  282. // Make sure identity.public matches identity.secret
  283. idser = std::string();
  284. Utils::readFile(identityPublicPath.c_str(),idser);
  285. std::string pubid(_r->identity.toString(false));
  286. if (idser != pubid) {
  287. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  288. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  289. }
  290. } else {
  291. LOG("no identity found, generating one... this might take a few seconds...");
  292. _r->identity.generate();
  293. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  294. idser = _r->identity.toString(true);
  295. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  296. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  297. idser = _r->identity.toString(false);
  298. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  299. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  300. }
  301. Utils::lockDownFile(identitySecretPath.c_str(),false);
  302. // Clean up some obsolete files if present -- this will be removed later
  303. Utils::rm((_r->homePath + ZT_PATH_SEPARATOR_S + "status"));
  304. Utils::rm((_r->homePath + ZT_PATH_SEPARATOR_S + "thisdeviceismine"));
  305. // Make sure networks.d exists
  306. #ifdef __WINDOWS__
  307. CreateDirectory((_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str(),NULL);
  308. #else
  309. mkdir((_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d").c_str(),0700);
  310. #endif
  311. // Load or generate config authentication secret
  312. std::string configAuthTokenPath(_r->homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  313. std::string configAuthToken;
  314. if (!Utils::readFile(configAuthTokenPath.c_str(),configAuthToken)) {
  315. configAuthToken = "";
  316. unsigned int sr = 0;
  317. for(unsigned int i=0;i<24;++i) {
  318. Utils::getSecureRandom(&sr,sizeof(sr));
  319. configAuthToken.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[sr % 62]);
  320. }
  321. if (!Utils::writeFile(configAuthTokenPath.c_str(),configAuthToken))
  322. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write authtoken.secret (home path not writable?)");
  323. }
  324. Utils::lockDownFile(configAuthTokenPath.c_str(),false);
  325. // Create the core objects in RuntimeEnvironment: node config, demarcation
  326. // point, switch, network topology database, and system environment
  327. // watcher.
  328. _r->demarc = new Demarc(_r);
  329. _r->multicaster = new Multicaster();
  330. _r->sw = new Switch(_r);
  331. _r->topology = new Topology(_r,(_r->homePath + ZT_PATH_SEPARATOR_S + "peer.db").c_str());
  332. _r->sysEnv = new SysEnv(_r);
  333. try {
  334. _r->nc = new NodeConfig(_r,configAuthToken.c_str());
  335. } catch ( ... ) {
  336. // An exception here currently means that another instance of ZeroTier
  337. // One is running.
  338. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"another instance of ZeroTier One appears to be running, or local control UDP port cannot be bound");
  339. }
  340. // TODO: make configurable
  341. bool boundPort = false;
  342. for(unsigned int p=ZT_DEFAULT_UDP_PORT;p<(ZT_DEFAULT_UDP_PORT + 128);++p) {
  343. if (_r->demarc->bindLocalUdp(p)) {
  344. boundPort = true;
  345. break;
  346. }
  347. }
  348. if (!boundPort)
  349. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not bind any local UDP ports");
  350. // TODO: bootstrap off network so we don't have to update code for
  351. // changes in supernodes.
  352. _r->topology->setSupernodes(ZT_DEFAULTS.supernodes);
  353. } catch (std::bad_alloc &exc) {
  354. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  355. } catch (std::runtime_error &exc) {
  356. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  357. } catch ( ... ) {
  358. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  359. }
  360. #ifndef __WINDOWS__
  361. try {
  362. std::string netconfServicePath(_r->homePath + ZT_PATH_SEPARATOR_S + "services.d" + ZT_PATH_SEPARATOR_S + "netconf.service");
  363. if (Utils::fileExists(netconfServicePath.c_str())) {
  364. LOG("netconf.d/netconfi.service appears to exist, starting...");
  365. _r->netconfService = new Service(_r,"netconf",netconfServicePath.c_str(),&_netconfServiceMessageHandler,_r);
  366. }
  367. } catch ( ... ) {
  368. LOG("unexpected exception attempting to start services");
  369. }
  370. #endif
  371. try {
  372. uint64_t lastNetworkAutoconfCheck = 0;
  373. uint64_t lastPingCheck = 0;
  374. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  375. uint64_t lastNetworkFingerprintCheck = 0;
  376. uint64_t networkConfigurationFingerprint = _r->sysEnv->getNetworkConfigurationFingerprint();
  377. uint64_t lastMulticastCheck = 0;
  378. uint64_t lastMulticastAnnounceAll = 0;
  379. long lastDelayDelta = 0;
  380. LOG("%s starting version %s",_r->identity.address().toString().c_str(),versionString());
  381. while (!impl->terminateNow) {
  382. uint64_t now = Utils::now();
  383. bool resynchronize = false;
  384. // Detect sleep/wake by looking for delay loop pauses that are longer
  385. // than we intended to pause.
  386. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  387. resynchronize = true;
  388. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  389. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  390. }
  391. // Periodically check our network environment, sending pings out to all
  392. // our direct links if things look like we got a different address.
  393. if ((resynchronize)||((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY)) {
  394. lastNetworkFingerprintCheck = now;
  395. uint64_t fp = _r->sysEnv->getNetworkConfigurationFingerprint();
  396. if (fp != networkConfigurationFingerprint) {
  397. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  398. networkConfigurationFingerprint = fp;
  399. resynchronize = true;
  400. _r->nc->whackAllTaps(); // call whack() on all tap devices -- hack, might go away
  401. }
  402. }
  403. // Request configuration for unconfigured nets, or nets with out of date
  404. // configuration information.
  405. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  406. lastNetworkAutoconfCheck = now;
  407. std::vector< SharedPtr<Network> > nets(_r->nc->networks());
  408. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  409. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  410. (*n)->requestConfiguration();
  411. }
  412. }
  413. // Periodically check for changes in our local multicast subscriptions and broadcast
  414. // those changes to peers.
  415. if ((resynchronize)||((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD)) {
  416. lastMulticastCheck = now;
  417. bool announceAll = ((resynchronize)||((now - lastMulticastAnnounceAll) >= ZT_MULTICAST_LIKE_ANNOUNCE_ALL_PERIOD));
  418. try {
  419. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  420. {
  421. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  422. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  423. if (((*nw)->updateMulticastGroups())||(announceAll))
  424. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  425. }
  426. }
  427. if (toAnnounce.size()) {
  428. _r->sw->announceMulticastGroups(toAnnounce);
  429. // Only update lastMulticastAnnounceAll if we've announced something. This keeps
  430. // the announceAll condition true during startup when there are no multicast
  431. // groups until there is at least one. Technically this shouldn't be required as
  432. // updateMulticastGroups() should return true on any change, but why not?
  433. if (announceAll)
  434. lastMulticastAnnounceAll = now;
  435. }
  436. } catch (std::exception &exc) {
  437. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  438. } catch ( ... ) {
  439. LOG("unexpected exception announcing multicast groups: (unknown)");
  440. }
  441. }
  442. if ((resynchronize)||((now - lastPingCheck) >= ZT_PING_CHECK_DELAY)) {
  443. lastPingCheck = now;
  444. try {
  445. if (_r->topology->amSupernode()) {
  446. // Supernodes are so super they don't even have to ping out, since
  447. // all nodes ping them. They're also never firewalled so they
  448. // don't need firewall openers. They just ping each other.
  449. std::vector< SharedPtr<Peer> > sns(_r->topology->supernodePeers());
  450. for(std::vector< SharedPtr<Peer> >::const_iterator p(sns.begin());p!=sns.end();++p) {
  451. if ((now - (*p)->lastDirectSend()) > ZT_PEER_DIRECT_PING_DELAY)
  452. _r->sw->sendHELLO((*p)->address());
  453. }
  454. } else {
  455. std::vector< SharedPtr<Peer> > needPing,needFirewallOpener;
  456. if (resynchronize) {
  457. _r->topology->eachPeer(Topology::CollectPeersWithDirectPath(needPing));
  458. } else {
  459. _r->topology->eachPeer(Topology::CollectPeersThatNeedPing(needPing));
  460. }
  461. for(std::vector< SharedPtr<Peer> >::iterator p(needPing.begin());p!=needPing.end();++p) {
  462. try {
  463. _r->sw->sendHELLO((*p)->address());
  464. } catch (std::exception &exc) {
  465. LOG("unexpected exception sending HELLO to %s: %s",(*p)->address().toString().c_str());
  466. } catch ( ... ) {
  467. LOG("unexpected exception sending HELLO to %s: (unknown)",(*p)->address().toString().c_str());
  468. }
  469. }
  470. _r->topology->eachPeer(Topology::CollectPeersThatNeedFirewallOpener(needFirewallOpener));
  471. for(std::vector< SharedPtr<Peer> >::iterator p(needFirewallOpener.begin());p!=needFirewallOpener.end();++p) {
  472. try {
  473. (*p)->sendFirewallOpener(_r,now);
  474. } catch (std::exception &exc) {
  475. LOG("unexpected exception sending firewall opener to %s: %s",(*p)->address().toString().c_str(),exc.what());
  476. } catch ( ... ) {
  477. LOG("unexpected exception sending firewall opener to %s: (unknown)",(*p)->address().toString().c_str());
  478. }
  479. }
  480. }
  481. } catch (std::exception &exc) {
  482. LOG("unexpected exception running ping check cycle: %s",exc.what());
  483. } catch ( ... ) {
  484. LOG("unexpected exception running ping check cycle: (unkonwn)");
  485. }
  486. }
  487. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  488. lastClean = now;
  489. _r->topology->clean();
  490. _r->nc->clean();
  491. }
  492. try {
  493. unsigned long delay = std::min((unsigned long)ZT_MIN_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  494. uint64_t start = Utils::now();
  495. _r->mainLoopWaitCondition.wait(delay);
  496. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  497. } catch (std::exception &exc) {
  498. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  499. } catch ( ... ) {
  500. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  501. }
  502. }
  503. } catch ( ... ) {
  504. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  505. }
  506. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"normal termination");
  507. }
  508. const char *Node::reasonForTermination() const
  509. throw()
  510. {
  511. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  512. return (const char *)0;
  513. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  514. }
  515. void Node::terminate()
  516. throw()
  517. {
  518. ((_NodeImpl *)_impl)->terminateNow = true;
  519. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  520. }
  521. class _VersionStringMaker
  522. {
  523. public:
  524. char vs[32];
  525. _VersionStringMaker()
  526. {
  527. sprintf(vs,"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  528. }
  529. ~_VersionStringMaker() {}
  530. };
  531. static const _VersionStringMaker __versionString;
  532. const char *Node::versionString() throw() { return __versionString.vs; }
  533. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  534. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  535. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  536. // Scanned for by loader and/or updater to determine a binary's version
  537. const unsigned char EMBEDDED_VERSION_STAMP[20] = {
  538. 0x6d,0xfe,0xff,0x01,0x90,0xfa,0x89,0x57,0x88,0xa1,0xaa,0xdc,0xdd,0xde,0xb0,0x33,
  539. ZEROTIER_ONE_VERSION_MAJOR,
  540. ZEROTIER_ONE_VERSION_MINOR,
  541. (unsigned char)(((unsigned int)ZEROTIER_ONE_VERSION_REVISION) & 0xff), /* little-endian */
  542. (unsigned char)((((unsigned int)ZEROTIER_ONE_VERSION_REVISION) >> 8) & 0xff)
  543. };
  544. } // namespace ZeroTier