Node.cpp 21 KB

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