Node.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. #else
  45. #include <fcntl.h>
  46. #include <unistd.h>
  47. #include <signal.h>
  48. #include <sys/file.h>
  49. #endif
  50. #include "../version.h"
  51. #include "Node.hpp"
  52. #include "RuntimeEnvironment.hpp"
  53. #include "Logger.hpp"
  54. #include "Utils.hpp"
  55. #include "Defaults.hpp"
  56. #include "Identity.hpp"
  57. #include "Topology.hpp"
  58. #include "SocketManager.hpp"
  59. #include "Packet.hpp"
  60. #include "Switch.hpp"
  61. #include "EthernetTap.hpp"
  62. #include "CMWC4096.hpp"
  63. #include "NodeConfig.hpp"
  64. #include "Network.hpp"
  65. #include "MulticastGroup.hpp"
  66. #include "Mutex.hpp"
  67. #include "Multicaster.hpp"
  68. #include "Service.hpp"
  69. #include "SoftwareUpdater.hpp"
  70. #include "Buffer.hpp"
  71. #include "IpcConnection.hpp"
  72. #include "AntiRecursion.hpp"
  73. #include "RoutingTable.hpp"
  74. #include "HttpClient.hpp"
  75. namespace ZeroTier {
  76. // ---------------------------------------------------------------------------
  77. struct _NodeControlClientImpl
  78. {
  79. void (*resultHandler)(void *,const char *);
  80. void *arg;
  81. IpcConnection *ipcc;
  82. std::string err;
  83. };
  84. static void _CBipcResultHandler(void *arg,IpcConnection *ipcc,IpcConnection::EventType event,const char *result)
  85. {
  86. if ((event == IpcConnection::IPC_EVENT_COMMAND)&&(result)) {
  87. if (strcmp(result,"200 auth OK"))
  88. ((_NodeControlClientImpl *)arg)->resultHandler(((_NodeControlClientImpl *)arg)->arg,result);
  89. }
  90. }
  91. Node::NodeControlClient::NodeControlClient(const char *hp,void (*resultHandler)(void *,const char *),void *arg,const char *authToken)
  92. throw() :
  93. _impl((void *)new _NodeControlClientImpl)
  94. {
  95. _NodeControlClientImpl *impl = (_NodeControlClientImpl *)_impl;
  96. impl->ipcc = (IpcConnection *)0;
  97. if (!hp)
  98. hp = ZT_DEFAULTS.defaultHomePath.c_str();
  99. std::string at;
  100. if (authToken)
  101. at = authToken;
  102. else if (!Utils::readFile(authTokenDefaultSystemPath(),at)) {
  103. if (!Utils::readFile(authTokenDefaultUserPath(),at)) {
  104. impl->err = "no authentication token specified and authtoken.secret not readable";
  105. return;
  106. }
  107. }
  108. std::string myid;
  109. if (Utils::readFile((std::string(hp) + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),myid)) {
  110. std::string myaddr(myid.substr(0,myid.find(':')));
  111. if (myaddr.length() != 10)
  112. impl->err = "invalid address extracted from identity.public";
  113. else {
  114. try {
  115. impl->resultHandler = resultHandler;
  116. impl->arg = arg;
  117. impl->ipcc = new IpcConnection((std::string(ZT_IPC_ENDPOINT_BASE) + myaddr).c_str(),&_CBipcResultHandler,_impl);
  118. impl->ipcc->printf("auth %s"ZT_EOL_S,at.c_str());
  119. } catch ( ... ) {
  120. impl->ipcc = (IpcConnection *)0;
  121. impl->err = "failure connecting to running ZeroTier One service";
  122. }
  123. }
  124. } else impl->err = "unable to read identity.public";
  125. }
  126. Node::NodeControlClient::~NodeControlClient()
  127. {
  128. if (_impl) {
  129. delete ((_NodeControlClientImpl *)_impl)->ipcc;
  130. delete (_NodeControlClientImpl *)_impl;
  131. }
  132. }
  133. const char *Node::NodeControlClient::error() const
  134. throw()
  135. {
  136. if (((_NodeControlClientImpl *)_impl)->err.length())
  137. return ((_NodeControlClientImpl *)_impl)->err.c_str();
  138. return (const char *)0;
  139. }
  140. void Node::NodeControlClient::send(const char *command)
  141. throw()
  142. {
  143. try {
  144. if (((_NodeControlClientImpl *)_impl)->ipcc)
  145. ((_NodeControlClientImpl *)_impl)->ipcc->printf("%s"ZT_EOL_S,command);
  146. } catch ( ... ) {}
  147. }
  148. std::vector<std::string> Node::NodeControlClient::splitLine(const char *line)
  149. {
  150. return Utils::split(line," ","\\","\"");
  151. }
  152. const char *Node::NodeControlClient::authTokenDefaultUserPath()
  153. {
  154. static std::string dlp;
  155. static Mutex dlp_m;
  156. Mutex::Lock _l(dlp_m);
  157. #ifdef __WINDOWS__
  158. if (!dlp.length()) {
  159. char buf[16384];
  160. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_APPDATA,NULL,0,buf)))
  161. dlp = (std::string(buf) + "\\ZeroTier\\One\\authtoken.secret");
  162. }
  163. #else // not __WINDOWS__
  164. if (!dlp.length()) {
  165. const char *home = getenv("HOME");
  166. if (home) {
  167. #ifdef __APPLE__
  168. dlp = (std::string(home) + "/Library/Application Support/ZeroTier/One/authtoken.secret");
  169. #else
  170. dlp = (std::string(home) + "/.zeroTierOneAuthToken");
  171. #endif
  172. }
  173. }
  174. #endif // __WINDOWS__ or not __WINDOWS__
  175. return dlp.c_str();
  176. }
  177. const char *Node::NodeControlClient::authTokenDefaultSystemPath()
  178. {
  179. static std::string dsp;
  180. static Mutex dsp_m;
  181. Mutex::Lock _l(dsp_m);
  182. if (!dsp.length())
  183. dsp = (ZT_DEFAULTS.defaultHomePath + ZT_PATH_SEPARATOR_S"authtoken.secret");
  184. return dsp.c_str();
  185. }
  186. // ---------------------------------------------------------------------------
  187. struct _NodeImpl
  188. {
  189. RuntimeEnvironment renv;
  190. unsigned int udpPort,tcpPort;
  191. std::string reasonForTerminationStr;
  192. volatile Node::ReasonForTermination reasonForTermination;
  193. volatile bool started;
  194. volatile bool running;
  195. volatile bool resynchronize;
  196. // This function performs final node tear-down
  197. inline Node::ReasonForTermination terminate()
  198. {
  199. RuntimeEnvironment *_r = &renv;
  200. LOG("terminating: %s",reasonForTerminationStr.c_str());
  201. renv.shutdownInProgress = true;
  202. Thread::sleep(500);
  203. running = false;
  204. #ifndef __WINDOWS__
  205. delete renv.netconfService;
  206. #endif
  207. delete renv.updater; renv.updater = (SoftwareUpdater *)0;
  208. delete renv.nc; renv.nc = (NodeConfig *)0; // shut down all networks, close taps, etc.
  209. delete renv.topology; renv.topology = (Topology *)0; // now we no longer need routing info
  210. delete renv.sm; renv.sm = (SocketManager *)0; // close all sockets
  211. delete renv.sw; renv.sw = (Switch *)0; // order matters less from here down
  212. delete renv.mc; renv.mc = (Multicaster *)0;
  213. delete renv.antiRec; renv.antiRec = (AntiRecursion *)0;
  214. delete renv.http; renv.http = (HttpClient *)0;
  215. delete renv.prng; renv.prng = (CMWC4096 *)0;
  216. delete renv.log; renv.log = (Logger *)0; // but stop logging last of all
  217. return reasonForTermination;
  218. }
  219. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  220. {
  221. reasonForTerminationStr = rstr;
  222. reasonForTermination = r;
  223. return terminate();
  224. }
  225. };
  226. #ifndef __WINDOWS__ // "services" are not supported on Windows
  227. static void _netconfServiceMessageHandler(void *renv,Service &svc,const Dictionary &msg)
  228. {
  229. if (!renv)
  230. return; // sanity check
  231. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)renv;
  232. try {
  233. //TRACE("from netconf:\n%s",msg.toString().c_str());
  234. const std::string &type = msg.get("type");
  235. if (type == "ready") {
  236. LOG("received 'ready' from netconf.service, sending netconf-init with identity information...");
  237. Dictionary initMessage;
  238. initMessage["type"] = "netconf-init";
  239. initMessage["netconfId"] = _r->identity.toString(true);
  240. _r->netconfService->send(initMessage);
  241. } else if (type == "netconf-response") {
  242. uint64_t inRePacketId = strtoull(msg.get("requestId").c_str(),(char **)0,16);
  243. uint64_t nwid = strtoull(msg.get("nwid").c_str(),(char **)0,16);
  244. Address peerAddress(msg.get("peer").c_str());
  245. if (peerAddress) {
  246. if (msg.contains("error")) {
  247. Packet::ErrorCode errCode = Packet::ERROR_INVALID_REQUEST;
  248. const std::string &err = msg.get("error");
  249. if (err == "OBJ_NOT_FOUND")
  250. errCode = Packet::ERROR_OBJ_NOT_FOUND;
  251. else if (err == "ACCESS_DENIED")
  252. errCode = Packet::ERROR_NETWORK_ACCESS_DENIED_;
  253. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_ERROR);
  254. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  255. outp.append(inRePacketId);
  256. outp.append((unsigned char)errCode);
  257. outp.append(nwid);
  258. _r->sw->send(outp,true);
  259. } else if (msg.contains("netconf")) {
  260. const std::string &netconf = msg.get("netconf");
  261. if (netconf.length() < 2048) { // sanity check
  262. Packet outp(peerAddress,_r->identity.address(),Packet::VERB_OK);
  263. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  264. outp.append(inRePacketId);
  265. outp.append(nwid);
  266. outp.append((uint16_t)netconf.length());
  267. outp.append(netconf.data(),netconf.length());
  268. outp.compress();
  269. _r->sw->send(outp,true);
  270. }
  271. }
  272. }
  273. } else if (type == "netconf-push") {
  274. if (msg.contains("to")) {
  275. Dictionary to(msg.get("to")); // key: peer address, value: comma-delimited network list
  276. for(Dictionary::iterator t(to.begin());t!=to.end();++t) {
  277. Address ztaddr(t->first);
  278. if (ztaddr) {
  279. Packet outp(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  280. char *saveptr = (char *)0;
  281. // Note: this loop trashes t->second, which is quasi-legal C++ but
  282. // shouldn't break anything as long as we don't try to use 'to'
  283. // for anything interesting after doing this.
  284. for(char *p=Utils::stok(const_cast<char *>(t->second.c_str()),",",&saveptr);(p);p=Utils::stok((char *)0,",",&saveptr)) {
  285. uint64_t nwid = Utils::hexStrToU64(p);
  286. if (nwid) {
  287. if ((outp.size() + sizeof(uint64_t)) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  288. _r->sw->send(outp,true);
  289. outp.reset(ztaddr,_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  290. }
  291. outp.append(nwid);
  292. }
  293. }
  294. if (outp.payloadLength())
  295. _r->sw->send(outp,true);
  296. }
  297. }
  298. }
  299. }
  300. } catch (std::exception &exc) {
  301. LOG("unexpected exception parsing response from netconf service: %s",exc.what());
  302. } catch ( ... ) {
  303. LOG("unexpected exception parsing response from netconf service: unknown exception");
  304. }
  305. }
  306. #endif // !__WINDOWS__
  307. Node::Node(
  308. const char *hp,
  309. EthernetTapFactory *tf,
  310. RoutingTable *rt,
  311. unsigned int udpPort,
  312. unsigned int tcpPort,
  313. bool resetIdentity)
  314. throw() :
  315. _impl(new _NodeImpl)
  316. {
  317. _NodeImpl *impl = (_NodeImpl *)_impl;
  318. if ((hp)&&(hp[0]))
  319. impl->renv.homePath = hp;
  320. else impl->renv.homePath = ZT_DEFAULTS.defaultHomePath;
  321. impl->renv.tapFactory = tf;
  322. impl->renv.routingTable = rt;
  323. if (resetIdentity) {
  324. // Forget identity and peer database, peer keys, etc.
  325. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  326. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  327. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "peers.persist").c_str());
  328. // Truncate network config information in networks.d but leave the files since we
  329. // still want to remember any networks we have joined. This will force those networks
  330. // to be reconfigured with our newly regenerated identity after startup.
  331. std::string networksDotD(impl->renv.homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  332. std::map< std::string,bool > nwfiles(Utils::listDirectory(networksDotD.c_str()));
  333. for(std::map<std::string,bool>::iterator nwf(nwfiles.begin());nwf!=nwfiles.end();++nwf) {
  334. FILE *trun = fopen((networksDotD + ZT_PATH_SEPARATOR_S + nwf->first).c_str(),"w");
  335. if (trun)
  336. fclose(trun);
  337. }
  338. }
  339. impl->udpPort = udpPort & 0xffff;
  340. impl->tcpPort = tcpPort & 0xffff;
  341. impl->reasonForTermination = Node::NODE_RUNNING;
  342. impl->started = false;
  343. impl->running = false;
  344. impl->resynchronize = false;
  345. }
  346. Node::~Node()
  347. {
  348. delete (_NodeImpl *)_impl;
  349. }
  350. static void _CBztTraffic(const SharedPtr<Socket> &fromSock,void *arg,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  351. {
  352. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)arg;
  353. if ((_r->sw)&&(!_r->shutdownInProgress))
  354. _r->sw->onRemotePacket(fromSock,from,data);
  355. }
  356. static void _cbHandleGetRootTopology(void *arg,int code,const std::string &url,const std::string &body)
  357. {
  358. RuntimeEnvironment *_r = (RuntimeEnvironment *)arg;
  359. if (_r->shutdownInProgress)
  360. return;
  361. if ((code != 200)||(body.length() == 0)) {
  362. TRACE("failed to retrieve %s",url.c_str());
  363. return;
  364. }
  365. try {
  366. Dictionary rt(body);
  367. if (!Topology::authenticateRootTopology(rt)) {
  368. LOG("discarded invalid root topology update from %s (signature check failed)",url.c_str());
  369. return;
  370. }
  371. {
  372. std::string rootTopologyPath(_r->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
  373. std::string rootTopology;
  374. if (Utils::readFile(rootTopologyPath.c_str(),rootTopology)) {
  375. Dictionary alreadyHave(rootTopology);
  376. if (alreadyHave == rt) {
  377. TRACE("retrieved root topology from %s but no change (same as on disk)",url.c_str());
  378. return;
  379. } else if (alreadyHave.signatureTimestamp() > rt.signatureTimestamp()) {
  380. TRACE("retrieved root topology from %s but no change (ours is newer)",url.c_str());
  381. return;
  382. }
  383. }
  384. Utils::writeFile(rootTopologyPath.c_str(),body);
  385. }
  386. _r->topology->setSupernodes(Dictionary(rt.get("supernodes")));
  387. } catch ( ... ) {
  388. LOG("discarded invalid root topology update from %s (format invalid)",url.c_str());
  389. return;
  390. }
  391. }
  392. Node::ReasonForTermination Node::run()
  393. throw()
  394. {
  395. _NodeImpl *impl = (_NodeImpl *)_impl;
  396. RuntimeEnvironment *_r = (RuntimeEnvironment *)&(impl->renv);
  397. impl->started = true;
  398. impl->running = true;
  399. try {
  400. #ifdef ZT_LOG_STDOUT
  401. _r->log = new Logger((const char *)0,(const char *)0,0);
  402. #else
  403. _r->log = new Logger((_r->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  404. #endif
  405. LOG("starting version %s",versionString());
  406. // Create non-crypto PRNG right away in case other code in init wants to use it
  407. _r->prng = new CMWC4096();
  408. bool gotId = false;
  409. std::string identitySecretPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  410. std::string identityPublicPath(_r->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  411. std::string idser;
  412. if (Utils::readFile(identitySecretPath.c_str(),idser))
  413. gotId = _r->identity.fromString(idser);
  414. if ((gotId)&&(!_r->identity.locallyValidate()))
  415. gotId = false;
  416. if (gotId) {
  417. // Make sure identity.public matches identity.secret
  418. idser = std::string();
  419. Utils::readFile(identityPublicPath.c_str(),idser);
  420. std::string pubid(_r->identity.toString(false));
  421. if (idser != pubid) {
  422. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  423. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  424. }
  425. } else {
  426. LOG("no identity found or identity invalid, generating one... this might take a few seconds...");
  427. _r->identity.generate();
  428. LOG("generated new identity: %s",_r->identity.address().toString().c_str());
  429. idser = _r->identity.toString(true);
  430. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  431. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  432. idser = _r->identity.toString(false);
  433. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  434. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  435. }
  436. Utils::lockDownFile(identitySecretPath.c_str(),false);
  437. // Make sure networks.d exists
  438. {
  439. std::string networksDotD(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  440. #ifdef __WINDOWS__
  441. CreateDirectoryA(networksDotD.c_str(),NULL);
  442. #else
  443. mkdir(networksDotD.c_str(),0700);
  444. #endif
  445. }
  446. std::string configAuthTokenPath(_r->homePath + ZT_PATH_SEPARATOR_S + "authtoken.secret");
  447. std::string configAuthToken;
  448. if (!Utils::readFile(configAuthTokenPath.c_str(),configAuthToken)) {
  449. configAuthToken = "";
  450. unsigned int sr = 0;
  451. for(unsigned int i=0;i<24;++i) {
  452. Utils::getSecureRandom(&sr,sizeof(sr));
  453. configAuthToken.push_back("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[sr % 62]);
  454. }
  455. if (!Utils::writeFile(configAuthTokenPath.c_str(),configAuthToken))
  456. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write authtoken.secret (home path not writable?)");
  457. }
  458. Utils::lockDownFile(configAuthTokenPath.c_str(),false);
  459. _r->http = new HttpClient();
  460. _r->antiRec = new AntiRecursion();
  461. _r->mc = new Multicaster();
  462. _r->sw = new Switch(_r);
  463. _r->sm = new SocketManager(impl->udpPort,impl->tcpPort,&_CBztTraffic,_r);
  464. _r->topology = new Topology(_r,Utils::fileExists((_r->homePath + ZT_PATH_SEPARATOR_S + "iddb.d").c_str()));
  465. try {
  466. _r->nc = new NodeConfig(_r,configAuthToken.c_str());
  467. } catch (std::exception &exc) {
  468. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unable to initialize IPC socket: is ZeroTier One already running?");
  469. }
  470. _r->node = this;
  471. #ifdef ZT_AUTO_UPDATE
  472. if (ZT_DEFAULTS.updateLatestNfoURL.length()) {
  473. _r->updater = new SoftwareUpdater(_r);
  474. _r->updater->cleanOldUpdates(); // clean out updates.d on startup
  475. } else {
  476. LOG("WARNING: unable to enable software updates: latest .nfo URL from ZT_DEFAULTS is empty (does this platform actually support software updates?)");
  477. }
  478. #endif
  479. std::string rootTopologyPath(_r->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
  480. std::string rootTopology;
  481. if (!Utils::readFile(rootTopologyPath.c_str(),rootTopology))
  482. rootTopology = ZT_DEFAULTS.defaultRootTopology;
  483. try {
  484. Dictionary rt(rootTopology);
  485. if (Topology::authenticateRootTopology(rt)) {
  486. _r->topology->setSupernodes(Dictionary(rt.get("supernodes")));
  487. } else {
  488. LOG("%s failed signature check, using built-in defaults instead",rootTopologyPath.c_str());
  489. Utils::rm(rootTopologyPath.c_str());
  490. _r->topology->setSupernodes(Dictionary(Dictionary(ZT_DEFAULTS.defaultRootTopology).get("supernodes")));
  491. }
  492. } catch ( ... ) {
  493. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"invalid root-topology format");
  494. }
  495. } catch (std::bad_alloc &exc) {
  496. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  497. } catch (std::runtime_error &exc) {
  498. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  499. } catch ( ... ) {
  500. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  501. }
  502. // Start external service subprocesses, which is only used by special nodes
  503. // right now and isn't available on Windows.
  504. #ifndef __WINDOWS__
  505. try {
  506. std::string netconfServicePath(_r->homePath + ZT_PATH_SEPARATOR_S + "services.d" + ZT_PATH_SEPARATOR_S + "netconf.service");
  507. if (Utils::fileExists(netconfServicePath.c_str())) {
  508. LOG("netconf.d/netconf.service appears to exist, starting...");
  509. _r->netconfService = new Service(_r,"netconf",netconfServicePath.c_str(),&_netconfServiceMessageHandler,_r);
  510. Dictionary initMessage;
  511. initMessage["type"] = "netconf-init";
  512. initMessage["netconfId"] = _r->identity.toString(true);
  513. _r->netconfService->send(initMessage);
  514. }
  515. } catch ( ... ) {
  516. LOG("unexpected exception attempting to start services");
  517. }
  518. #endif
  519. // Core I/O loop
  520. try {
  521. /* Shut down if this file exists but fails to open. This is used on Mac to
  522. * shut down automatically on .app deletion by symlinking this to the
  523. * Info.plist file inside the ZeroTier One application. This causes the
  524. * service to die when the user throws away the app, allowing uninstallation
  525. * in the natural Mac way. */
  526. std::string shutdownIfUnreadablePath(_r->homePath + ZT_PATH_SEPARATOR_S + "shutdownIfUnreadable");
  527. uint64_t lastNetworkAutoconfCheck = Utils::now() - 5000ULL; // check autoconf again after 5s for startup
  528. uint64_t lastPingCheck = 0;
  529. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  530. uint64_t lastNetworkFingerprintCheck = 0;
  531. uint64_t lastMulticastCheck = 0;
  532. uint64_t lastSupernodePingCheck = 0;
  533. uint64_t lastBeacon = 0;
  534. uint64_t lastRootTopologyFetch = 0;
  535. long lastDelayDelta = 0;
  536. uint64_t networkConfigurationFingerprint = 0;
  537. _r->timeOfLastResynchronize = Utils::now();
  538. while (impl->reasonForTermination == NODE_RUNNING) {
  539. /* This is how the service automatically shuts down when the OSX .app is
  540. * thrown in the trash. It's not used on any other platform for now but
  541. * could do similar things. It's disabled on Windows since it doesn't really
  542. * work there. */
  543. #ifdef __UNIX_LIKE__
  544. if (Utils::fileExists(shutdownIfUnreadablePath.c_str(),false)) {
  545. FILE *tmpf = fopen(shutdownIfUnreadablePath.c_str(),"r");
  546. if (!tmpf)
  547. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"shutdownIfUnreadable exists but is not readable");
  548. fclose(tmpf);
  549. }
  550. #endif
  551. uint64_t now = Utils::now();
  552. bool resynchronize = false;
  553. // If it looks like the computer slept and woke, resynchronize.
  554. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  555. resynchronize = true;
  556. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  557. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  558. }
  559. // If our network environment looks like it changed, resynchronize.
  560. if ((resynchronize)||((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY)) {
  561. lastNetworkFingerprintCheck = now;
  562. uint64_t fp = _r->routingTable->networkEnvironmentFingerprint(_r->nc->networkTapDeviceNames());
  563. if (fp != networkConfigurationFingerprint) {
  564. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  565. networkConfigurationFingerprint = fp;
  566. resynchronize = true;
  567. }
  568. }
  569. // Supernodes do not resynchronize unless explicitly ordered via SIGHUP.
  570. if ((resynchronize)&&(_r->topology->amSupernode()))
  571. resynchronize = false;
  572. // Check for SIGHUP / force resync.
  573. if (impl->resynchronize) {
  574. impl->resynchronize = false;
  575. resynchronize = true;
  576. LOG("resynchronize forced by user, syncing with network");
  577. }
  578. if (resynchronize) {
  579. _r->tcpTunnelingEnabled = false; // turn off TCP tunneling master switch at first, will be reenabled on persistent UDP failure
  580. _r->timeOfLastResynchronize = now;
  581. }
  582. /* Supernodes are pinged separately and more aggressively. The
  583. * ZT_STARTUP_AGGRO parameter sets a limit on how rapidly they are
  584. * tried, while PingSupernodesThatNeedPing contains the logic for
  585. * determining if they need PING. */
  586. if ((now - lastSupernodePingCheck) >= ZT_STARTUP_AGGRO) {
  587. lastSupernodePingCheck = now;
  588. uint64_t lastReceiveFromAnySupernode = 0; // function object result paramter
  589. _r->topology->eachSupernodePeer(Topology::FindMostRecentDirectReceiveTimestamp(lastReceiveFromAnySupernode));
  590. // Turn on TCP tunneling master switch if we haven't heard anything since before
  591. // the last resynchronize and we've been trying long enough.
  592. uint64_t tlr = _r->timeOfLastResynchronize;
  593. if ((lastReceiveFromAnySupernode < tlr)&&((now - tlr) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT)) {
  594. TRACE("network still unreachable after %u ms, TCP TUNNELING ENABLED",(unsigned int)ZT_TCP_TUNNEL_FAILOVER_TIMEOUT);
  595. _r->tcpTunnelingEnabled = true;
  596. }
  597. _r->topology->eachSupernodePeer(Topology::PingSupernodesThatNeedPing(_r,now));
  598. }
  599. if (resynchronize) {
  600. /* Send NOP to all peers on resynchronize, directly to supernodes and
  601. * indirectly to regular nodes (to trigger RENDEZVOUS). Also clear
  602. * learned paths since they're likely no longer valid, and close
  603. * TCP sockets since they're also likely invalid. */
  604. _r->sm->closeTcpSockets();
  605. _r->topology->eachPeer(Topology::ResetActivePeers(_r,now));
  606. } else {
  607. /* Periodically check for changes in our local multicast subscriptions
  608. * and broadcast those changes to directly connected peers. */
  609. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  610. lastMulticastCheck = now;
  611. try {
  612. std::map< SharedPtr<Network>,std::set<MulticastGroup> > toAnnounce;
  613. std::vector< SharedPtr<Network> > networks(_r->nc->networks());
  614. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw) {
  615. if ((*nw)->updateMulticastGroups())
  616. toAnnounce.insert(std::pair< SharedPtr<Network>,std::set<MulticastGroup> >(*nw,(*nw)->multicastGroups()));
  617. }
  618. if (toAnnounce.size())
  619. _r->sw->announceMulticastGroups(toAnnounce);
  620. } catch (std::exception &exc) {
  621. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  622. } catch ( ... ) {
  623. LOG("unexpected exception announcing multicast groups: (unknown)");
  624. }
  625. }
  626. /* Periodically ping all our non-stale direct peers unless we're a supernode.
  627. * Supernodes only ping each other (which is done above). */
  628. if ((!_r->topology->amSupernode())&&((now - lastPingCheck) >= ZT_PING_CHECK_DELAY)) {
  629. lastPingCheck = now;
  630. try {
  631. _r->topology->eachPeer(Topology::PingPeersThatNeedPing(_r,now));
  632. #ifdef ZT_FIREWALL_OPENER_DELAY
  633. _r->topology->eachPeer(Topology::OpenPeersThatNeedFirewallOpener(_r,now));
  634. #endif
  635. } catch (std::exception &exc) {
  636. LOG("unexpected exception running ping check cycle: %s",exc.what());
  637. } catch ( ... ) {
  638. LOG("unexpected exception running ping check cycle: (unkonwn)");
  639. }
  640. }
  641. }
  642. // Update network configurations when needed.
  643. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  644. lastNetworkAutoconfCheck = now;
  645. std::vector< SharedPtr<Network> > nets(_r->nc->networks());
  646. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  647. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  648. (*n)->requestConfiguration();
  649. }
  650. }
  651. // Do periodic tasks in submodules.
  652. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  653. lastClean = now;
  654. _r->mc->clean();
  655. _r->topology->clean();
  656. _r->nc->clean();
  657. if (_r->updater)
  658. _r->updater->checkIfMaxIntervalExceeded(now);
  659. }
  660. // Send beacons to physical local LANs
  661. if ((resynchronize)||((now - lastBeacon) >= ZT_BEACON_INTERVAL)) {
  662. lastBeacon = now;
  663. char bcn[ZT_PROTO_BEACON_LENGTH];
  664. void *bcnptr = bcn;
  665. *((uint32_t *)(bcnptr)) = _r->prng->next32();
  666. bcnptr = bcn + 4;
  667. *((uint32_t *)(bcnptr)) = _r->prng->next32();
  668. _r->identity.address().copyTo(bcn + ZT_PROTO_BEACON_IDX_ADDRESS,ZT_ADDRESS_LENGTH);
  669. TRACE("sending LAN beacon to %s",ZT_DEFAULTS.v4Broadcast.toString().c_str());
  670. _r->antiRec->logOutgoingZT(bcn,ZT_PROTO_BEACON_LENGTH);
  671. _r->sm->send(ZT_DEFAULTS.v4Broadcast,false,false,bcn,ZT_PROTO_BEACON_LENGTH);
  672. }
  673. if ((now - lastRootTopologyFetch) >= ZT_UPDATE_ROOT_TOPOLOGY_CHECK_INTERVAL) {
  674. lastRootTopologyFetch = now;
  675. TRACE("fetching root topology from %s",ZT_DEFAULTS.rootTopologyUpdateURL.c_str());
  676. _r->http->GET(ZT_DEFAULTS.rootTopologyUpdateURL,HttpClient::NO_HEADERS,60,&_cbHandleGetRootTopology,_r);
  677. }
  678. // Sleep for loop interval or until something interesting happens.
  679. try {
  680. unsigned long delay = std::min((unsigned long)ZT_MAX_SERVICE_LOOP_INTERVAL,_r->sw->doTimerTasks());
  681. uint64_t start = Utils::now();
  682. _r->sm->poll(delay);
  683. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  684. } catch (std::exception &exc) {
  685. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  686. } catch ( ... ) {
  687. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  688. }
  689. }
  690. } catch ( ... ) {
  691. LOG("FATAL: unexpected exception in core loop: unknown exception");
  692. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  693. }
  694. return impl->terminate();
  695. }
  696. const char *Node::reasonForTermination() const
  697. throw()
  698. {
  699. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  700. return (const char *)0;
  701. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  702. }
  703. void Node::terminate(ReasonForTermination reason,const char *reasonText)
  704. throw()
  705. {
  706. ((_NodeImpl *)_impl)->reasonForTermination = reason;
  707. ((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
  708. ((_NodeImpl *)_impl)->renv.sm->whack();
  709. }
  710. void Node::resync()
  711. throw()
  712. {
  713. ((_NodeImpl *)_impl)->resynchronize = true;
  714. ((_NodeImpl *)_impl)->renv.sm->whack();
  715. }
  716. class _VersionStringMaker
  717. {
  718. public:
  719. char vs[32];
  720. _VersionStringMaker()
  721. {
  722. Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  723. }
  724. ~_VersionStringMaker() {}
  725. };
  726. static const _VersionStringMaker __versionString;
  727. const char *Node::versionString() throw() { return __versionString.vs; }
  728. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  729. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  730. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  731. } // namespace ZeroTier