Node.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. #include <ShlObj.h>
  44. #endif
  45. #ifdef __UNIX_LIKE__
  46. #include <fcntl.h>
  47. #include <unistd.h>
  48. #include <signal.h>
  49. #include <sys/file.h>
  50. #endif
  51. #include "Condition.hpp"
  52. #include "Node.hpp"
  53. #include "Topology.hpp"
  54. #include "Demarc.hpp"
  55. #include "Packet.hpp"
  56. #include "Switch.hpp"
  57. #include "Utils.hpp"
  58. #include "EthernetTap.hpp"
  59. #include "Logger.hpp"
  60. #include "InetAddress.hpp"
  61. #include "Salsa20.hpp"
  62. #include "RuntimeEnvironment.hpp"
  63. #include "NodeConfig.hpp"
  64. #include "Defaults.hpp"
  65. #include "SysEnv.hpp"
  66. #include "Network.hpp"
  67. #include "MulticastGroup.hpp"
  68. #include "Mutex.hpp"
  69. #include "Multicaster.hpp"
  70. #include "CMWC4096.hpp"
  71. #include "SHA512.hpp"
  72. #include "Service.hpp"
  73. #include "SoftwareUpdater.hpp"
  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,(unsigned int)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. std::vector<std::string> Node::LocalClient::splitLine(const char *line)
  164. {
  165. return Utils::split(line," ","\\","\"");
  166. }
  167. std::string Node::LocalClient::authTokenDefaultUserPath()
  168. {
  169. #ifdef __WINDOWS__
  170. char buf[16384];
  171. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_APPDATA,NULL,0,buf)))
  172. return (std::string(buf) + "\\ZeroTier\\One\\authtoken.secret");
  173. else return std::string();
  174. #else // not __WINDOWS__
  175. const char *home = getenv("HOME");
  176. if (home) {
  177. #ifdef __APPLE__
  178. return (std::string(home) + "/Library/Application Support/ZeroTier/One/authtoken.secret");
  179. #else
  180. return (std::string(home) + "/.zeroTierOneAuthToken");
  181. #endif
  182. } else return std::string();
  183. #endif // __WINDOWS__ or not __WINDOWS__
  184. }
  185. std::string Node::LocalClient::authTokenDefaultSystemPath()
  186. {
  187. return (ZT_DEFAULTS.defaultHomePath + ZT_PATH_SEPARATOR_S"authtoken.secret");
  188. }
  189. struct _NodeImpl
  190. {
  191. RuntimeEnvironment renv;
  192. unsigned int port;
  193. unsigned int controlPort;
  194. std::string reasonForTerminationStr;
  195. volatile Node::ReasonForTermination reasonForTermination;
  196. volatile bool started;
  197. volatile bool running;
  198. volatile bool resynchronize;
  199. inline Node::ReasonForTermination terminate()
  200. {
  201. RuntimeEnvironment *_r = &renv;
  202. LOG("terminating: %s",reasonForTerminationStr.c_str());
  203. renv.shutdownInProgress = true;
  204. Thread::sleep(500);
  205. running = false;
  206. #ifndef __WINDOWS__
  207. delete renv.netconfService;
  208. #endif
  209. delete renv.updater;
  210. delete renv.nc;
  211. delete renv.sysEnv;
  212. delete renv.topology;
  213. delete renv.demarc;
  214. delete renv.sw;
  215. delete renv.mc;
  216. delete renv.prng;
  217. delete renv.log;
  218. return reasonForTermination;
  219. }
  220. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  221. {
  222. reasonForTerminationStr = rstr;
  223. reasonForTermination = r;
  224. return terminate();
  225. }
  226. };
  227. #ifndef __WINDOWS__
  228. static void _netconfServiceMessageHandler(void *renv,Service &svc,const Dictionary &msg)
  229. {
  230. if (!renv)
  231. return; // sanity check
  232. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)renv;
  233. try {
  234. //TRACE("from netconf:\n%s",msg.toString().c_str());
  235. const std::string &type = msg.get("type");
  236. if (type == "ready") {
  237. LOG("received 'ready' from netconf.service, sending netconf-init with identity information...");
  238. Dictionary initMessage;
  239. initMessage["type"] = "netconf-init";
  240. initMessage["netconfId"] = _r->identity.toString(true);
  241. _r->netconfService->send(initMessage);
  242. } else if (type == "netconf-response") {
  243. uint64_t inRePacketId = strtoull(msg.get("requestId").c_str(),(char **)0,16);
  244. uint64_t nwid = strtoull(msg.get("nwid").c_str(),(char **)0,16);
  245. Address peerAddress(msg.get("peer").c_str());
  246. if (peerAddress) {
  247. if (msg.contains("error")) {
  248. Packet::ErrorCode errCode = Packet::ERROR_INVALID_REQUEST;
  249. const std::string &err = msg.get("error");
  250. if (err == "OBJ_NOT_FOUND")
  251. errCode = Packet::ERROR_OBJ_NOT_FOUND;
  252. else if (err == "ACCESS_DENIED")
  253. errCode = Packet::ERROR_NETWORK_ACCESS_DENIED_;
  254. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_ERROR);
  255. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  256. outp.append(inRePacketId);
  257. outp.append((unsigned char)errCode);
  258. outp.append(nwid);
  259. _r->sw->send(outp,true);
  260. } else if (msg.contains("netconf")) {
  261. const std::string &netconf = msg.get("netconf");
  262. if (netconf.length() < 2048) { // sanity check
  263. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_OK);
  264. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  265. outp.append(inRePacketId);
  266. outp.append(nwid);
  267. outp.append((uint16_t)netconf.length());
  268. outp.append(netconf.data(),netconf.length());
  269. outp.compress();
  270. _r->sw->send(outp,true);
  271. }
  272. }
  273. }
  274. } else if (type == "netconf-push") {
  275. if (msg.contains("to")) {
  276. Dictionary to(msg.get("to")); // key: peer address, value: comma-delimited network list
  277. for(Dictionary::iterator t(to.begin());t!=to.end();++t) {
  278. Address ztaddr(t->first);
  279. if (ztaddr) {
  280. Packet outp(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  281. char *saveptr = (char *)0;
  282. // Note: this loop trashes t->second, which is quasi-legal C++ but
  283. // shouldn't break anything as long as we don't try to use 'to'
  284. // for anything interesting after doing this.
  285. for(char *p=Utils::stok(const_cast<char *>(t->second.c_str()),",",&saveptr);(p);p=Utils::stok((char *)0,",",&saveptr)) {
  286. uint64_t nwid = Utils::hexStrToU64(p);
  287. if (nwid) {
  288. if ((outp.size() + sizeof(uint64_t)) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  289. _r->sw->send(outp,true);
  290. outp.reset(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  291. }
  292. outp.append(nwid);
  293. }
  294. }
  295. if (outp.payloadLength())
  296. _r->sw->send(outp,true);
  297. }
  298. }
  299. }
  300. }
  301. } catch (std::exception &exc) {
  302. LOG("unexpected exception parsing response from netconf service: %s",exc.what());
  303. } catch ( ... ) {
  304. LOG("unexpected exception parsing response from netconf service: unknown exception");
  305. }
  306. }
  307. #endif // !__WINDOWS__
  308. Node::Node(const char *hp,unsigned int port,unsigned int controlPort)
  309. throw() :
  310. _impl(new _NodeImpl)
  311. {
  312. _NodeImpl *impl = (_NodeImpl *)_impl;
  313. if ((hp)&&(strlen(hp) > 0))
  314. impl->renv.homePath = hp;
  315. else impl->renv.homePath = ZT_DEFAULTS.defaultHomePath;
  316. impl->port = (port) ? port : (unsigned int)ZT_DEFAULT_UDP_PORT;
  317. impl->controlPort = (controlPort) ? controlPort : (unsigned int)ZT_DEFAULT_CONTROL_UDP_PORT;
  318. impl->reasonForTermination = Node::NODE_RUNNING;
  319. impl->started = false;
  320. impl->running = false;
  321. impl->resynchronize = false;
  322. }
  323. Node::~Node()
  324. {
  325. delete (_NodeImpl *)_impl;
  326. }
  327. Node::ReasonForTermination Node::run()
  328. throw()
  329. {
  330. _NodeImpl *impl = (_NodeImpl *)_impl;
  331. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  332. impl->started = true;
  333. impl->running = true;
  334. try {
  335. #ifdef ZT_LOG_STDOUT
  336. _r->log = new Logger((const char *)0,(const char *)0,0);
  337. #else
  338. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  339. #endif
  340. LOG("starting version %s",versionString());
  341. // Create non-crypto PRNG right away in case other code in init wants to use it
  342. _r->prng = new CMWC4096();
  343. bool gotId = false;
  344. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  345. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  346. std::string idser;
  347. if (Utils::readFile(identitySecretPath.c_str(),idser))
  348. gotId = _r->identity.fromString(idser);
  349. if ((gotId)&&(!_r->identity.locallyValidate()))
  350. gotId = false;
  351. if (gotId) {
  352. // Make sure identity.public matches identity.secret
  353. idser = std::string();
  354. Utils::readFile(identityPublicPath.c_str(),idser);
  355. std::string pubid(_r->identity.toString(false));
  356. if (idser != pubid) {
  357. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  358. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  359. }
  360. } else {
  361. LOG("no identity found or identity invalid, generating one... this might take a few seconds...");
  362. _r->identity.generate();
  363. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  364. idser = _r->identity.toString(true);
  365. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  366. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  367. idser = _r->identity.toString(false);
  368. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  369. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  370. }
  371. Utils::lockDownFile(identitySecretPath.c_str(),false);
  372. // Make sure networks.d exists
  373. {
  374. std::string networksDotD(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  375. #ifdef __WINDOWS__
  376. CreateDirectoryA(networksDotD.c_str(),NULL);
  377. #else
  378. mkdir(networksDotD.c_str(),0700);
  379. #endif
  380. }
  381. // Load or generate config authentication secret
  382. std::string configAuthTokenPath(_r->homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  383. std::string configAuthToken;
  384. if (!Utils::readFile(configAuthTokenPath.c_str(),configAuthToken)) {
  385. configAuthToken = "";
  386. unsigned int sr = 0;
  387. for(unsigned int i=0;i<24;++i) {
  388. Utils::getSecureRandom(&sr,sizeof(sr));
  389. configAuthToken.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[sr % 62]);
  390. }
  391. if (!Utils::writeFile(configAuthTokenPath.c_str(),configAuthToken))
  392. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write authtoken.secret (home path not writable?)");
  393. }
  394. Utils::lockDownFile(configAuthTokenPath.c_str(),false);
  395. // Create the objects that make up runtime state.
  396. _r->mc = new Multicaster();
  397. _r->sw = new Switch(_r);
  398. _r->demarc = new Demarc(_r);
  399. _r->topology = new Topology(_r,Utils::fileExists((_r->homePath + ZT_PATH_SEPARATOR_S + "iddb.d").c_str()));
  400. _r->sysEnv = new SysEnv();
  401. try {
  402. _r->nc = new NodeConfig(_r,configAuthToken.c_str(),impl->controlPort);
  403. } catch (std::exception &exc) {
  404. char foo[1024];
  405. Utils::snprintf(foo,sizeof(foo),"unable to bind to local control port %u: is another instance of ZeroTier One already running?",impl->controlPort);
  406. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,foo);
  407. }
  408. _r->node = this;
  409. #ifdef ZT_AUTO_UPDATE
  410. if (ZT_DEFAULTS.updateLatestNfoURL.length()) {
  411. _r->updater = new SoftwareUpdater(_r);
  412. _r->updater->cleanOldUpdates(); // clean out updates.d on startup
  413. } else {
  414. LOG("WARNING: unable to enable software updates: latest .nfo URL from ZT_DEFAULTS is empty (does this platform actually support software updates?)");
  415. }
  416. #endif
  417. // Bind local port for core I/O
  418. if (!_r->demarc->bindLocalUdp(impl->port)) {
  419. char foo[1024];
  420. Utils::snprintf(foo,sizeof(foo),"unable to bind to global I/O port %u: is another instance of ZeroTier One already running?",impl->controlPort);
  421. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,foo);
  422. }
  423. // Set initial supernode list
  424. _r->topology->setSupernodes(ZT_DEFAULTS.supernodes);
  425. } catch (std::bad_alloc &exc) {
  426. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  427. } catch (std::runtime_error &exc) {
  428. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  429. } catch ( ... ) {
  430. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  431. }
  432. // Start external service subprocesses, which is only used by special nodes
  433. // right now and isn't available on Windows.
  434. #ifndef __WINDOWS__
  435. try {
  436. std::string netconfServicePath(_r->homePath + ZT_PATH_SEPARATOR_S + "services.d" + ZT_PATH_SEPARATOR_S + "netconf.service");
  437. if (Utils::fileExists(netconfServicePath.c_str())) {
  438. LOG("netconf.d/netconf.service appears to exist, starting...");
  439. _r->netconfService = new Service(_r,"netconf",netconfServicePath.c_str(),&_netconfServiceMessageHandler,_r);
  440. Dictionary initMessage;
  441. initMessage["type"] = "netconf-init";
  442. initMessage["netconfId"] = _r->identity.toString(true);
  443. _r->netconfService->send(initMessage);
  444. }
  445. } catch ( ... ) {
  446. LOG("unexpected exception attempting to start services");
  447. }
  448. #endif
  449. // Core I/O loop
  450. try {
  451. /* Shut down if this file exists but fails to open. This is used on Mac to
  452. * shut down automatically on .app deletion by symlinking this to the
  453. * Info.plist file inside the ZeroTier One application. This causes the
  454. * service to die when the user throws away the app, allowing uninstallation
  455. * in the natural Mac way. */
  456. std::string shutdownIfUnreadablePath(_r->homePath + ZT_PATH_SEPARATOR_S + "shutdownIfUnreadable");
  457. uint64_t lastNetworkAutoconfCheck = Utils::now() - 5000ULL; // check autoconf again after 5s for startup
  458. uint64_t lastPingCheck = 0;
  459. uint64_t lastSupernodePing = 0;
  460. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  461. uint64_t lastNetworkFingerprintCheck = 0;
  462. uint64_t lastMulticastCheck = 0;
  463. uint64_t networkConfigurationFingerprint = _r->sysEnv->getNetworkConfigurationFingerprint(_r->nc->networkTapDeviceNames());
  464. _r->timeOfLastNetworkEnvironmentChange = Utils::now();
  465. long lastDelayDelta = 0;
  466. while (impl->reasonForTermination == NODE_RUNNING) {
  467. if (Utils::fileExists(shutdownIfUnreadablePath.c_str(),false)) {
  468. FILE *tmpf = fopen(shutdownIfUnreadablePath.c_str(),"r");
  469. if (!tmpf)
  470. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"shutdownIfUnreadable exists but is not readable");
  471. fclose(tmpf);
  472. }
  473. uint64_t now = Utils::now();
  474. bool resynchronize = impl->resynchronize;
  475. if (resynchronize) {
  476. LOG("manual resynchronize ordered, resyncing with network");
  477. }
  478. impl->resynchronize = false;
  479. // If it looks like the computer slept and woke, resynchronize.
  480. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  481. resynchronize = true;
  482. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  483. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  484. }
  485. // If our network environment looks like it changed, resynchronize.
  486. if ((resynchronize)||((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY)) {
  487. lastNetworkFingerprintCheck = now;
  488. uint64_t fp = _r->sysEnv->getNetworkConfigurationFingerprint(_r->nc->networkTapDeviceNames());
  489. if (fp != networkConfigurationFingerprint) {
  490. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  491. networkConfigurationFingerprint = fp;
  492. _r->timeOfLastNetworkEnvironmentChange = now;
  493. resynchronize = true;
  494. }
  495. }
  496. // Ping supernodes separately for two reasons: (1) supernodes only ping each
  497. // other, and (2) we still want to ping them first on resynchronize.
  498. if ((resynchronize)||((now - lastSupernodePing) >= ZT_PEER_DIRECT_PING_DELAY)) {
  499. lastSupernodePing = now;
  500. std::vector< SharedPtr<Peer> > sns(_r->topology->supernodePeers());
  501. TRACE("pinging %d supernodes",(int)sns.size());
  502. for(std::vector< SharedPtr<Peer> >::const_iterator p(sns.begin());p!=sns.end();++p)
  503. (*p)->sendPing(_r,now);
  504. }
  505. if (resynchronize) {
  506. /* If resynchronizing, forget P2P links to all peers and then send
  507. * something to formerly active ones. This will relay via a supernode
  508. * which will trigger a new RENDEZVOUS and a new hole punch. This
  509. * functor excludes supernodes, which are pinged separately above. */
  510. _r->topology->eachPeer(Topology::ResetActivePeers(_r,now));
  511. } else {
  512. // Periodically check for changes in our local multicast subscriptions
  513. // and broadcast those changes to directly connected peers.
  514. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  515. lastMulticastCheck = now;
  516. try {
  517. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  518. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  519. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  520. if ((*nw)->updateMulticastGroups())
  521. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  522. }
  523. if (toAnnounce.size())
  524. _r->sw->announceMulticastGroups(toAnnounce);
  525. } catch (std::exception &exc) {
  526. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  527. } catch ( ... ) {
  528. LOG("unexpected exception announcing multicast groups: (unknown)");
  529. }
  530. }
  531. // Periodically ping all our non-stale direct peers unless we're a supernode.
  532. // Supernodes only ping each other (which is done above).
  533. if (!_r->topology->amSupernode()) {
  534. if ((now - lastPingCheck) >= ZT_PING_CHECK_DELAY) {
  535. lastPingCheck = now;
  536. try {
  537. _r->topology->eachPeer(Topology::PingPeersThatNeedPing(_r,now));
  538. _r->topology->eachPeer(Topology::OpenPeersThatNeedFirewallOpener(_r,now));
  539. } catch (std::exception &exc) {
  540. LOG("unexpected exception running ping check cycle: %s",exc.what());
  541. } catch ( ... ) {
  542. LOG("unexpected exception running ping check cycle: (unkonwn)");
  543. }
  544. }
  545. }
  546. }
  547. // Periodically or on resynchronize update network configurations.
  548. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  549. lastNetworkAutoconfCheck = now;
  550. std::vector< SharedPtr<Network> > nets(_r->nc->networks());
  551. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  552. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  553. (*n)->requestConfiguration();
  554. }
  555. }
  556. // Do periodic cleanup, flushes of stuff to disk, software update
  557. // checks, etc.
  558. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  559. lastClean = now;
  560. _r->mc->clean();
  561. _r->topology->clean();
  562. _r->nc->clean();
  563. if (_r->updater)
  564. _r->updater->checkIfMaxIntervalExceeded(now);
  565. }
  566. // Sleep for loop interval or until something interesting happens.
  567. try {
  568. unsigned long delay = std::min((unsigned long)ZT_MIN_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  569. uint64_t start = Utils::now();
  570. _r->mainLoopWaitCondition.wait(delay);
  571. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  572. } catch (std::exception &exc) {
  573. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  574. } catch ( ... ) {
  575. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  576. }
  577. }
  578. } catch ( ... ) {
  579. LOG("FATAL: unexpected exception in core loop: unknown exception");
  580. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  581. }
  582. return impl->terminate();
  583. }
  584. const char *Node::reasonForTermination() const
  585. throw()
  586. {
  587. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  588. return (const char *)0;
  589. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  590. }
  591. void Node::terminate(ReasonForTermination reason,const char *reasonText)
  592. throw()
  593. {
  594. ((_NodeImpl *)_impl)->reasonForTermination = reason;
  595. ((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
  596. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  597. }
  598. void Node::resync()
  599. throw()
  600. {
  601. ((_NodeImpl *)_impl)->resynchronize = true;
  602. ((_NodeImpl *)_impl)->renv.mainLoopWaitCondition.signal();
  603. }
  604. class _VersionStringMaker
  605. {
  606. public:
  607. char vs[32];
  608. _VersionStringMaker()
  609. {
  610. Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  611. }
  612. ~_VersionStringMaker() {}
  613. };
  614. static const _VersionStringMaker __versionString;
  615. const char *Node::versionString() throw() { return __versionString.vs; }
  616. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  617. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  618. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  619. } // namespace ZeroTier
  620. extern "C" {
  621. ZeroTier::Node *zeroTierCreateNode(const char *hp,unsigned int port,unsigned int controlPort)
  622. {
  623. return new ZeroTier::Node(hp,port,controlPort);
  624. }
  625. void zeroTierDeleteNode(ZeroTier::Node *n)
  626. {
  627. delete n;
  628. }
  629. ZeroTier::Node::LocalClient *zeroTierCreateLocalClient(const char *authToken,unsigned int controlPort,void (*resultHandler)(void *,unsigned long,const char *),void *arg)
  630. {
  631. return new ZeroTier::Node::LocalClient(authToken,controlPort,resultHandler,arg);
  632. }
  633. void zeroTierDeleteLocalClient(ZeroTier::Node::LocalClient *lc)
  634. {
  635. delete lc;
  636. }
  637. } // extern "C"