Node.cpp 22 KB

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