Node.cpp 20 KB

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