Node.cpp 23 KB

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