Node.cpp 24 KB

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