Node.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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 "Multicaster.hpp"
  67. #include "Mutex.hpp"
  68. #include "Service.hpp"
  69. #include "SoftwareUpdater.hpp"
  70. #include "Buffer.hpp"
  71. #include "AntiRecursion.hpp"
  72. #include "RoutingTable.hpp"
  73. #include "HttpClient.hpp"
  74. namespace ZeroTier {
  75. struct _NodeImpl
  76. {
  77. RuntimeEnvironment renv;
  78. unsigned int udpPort,tcpPort;
  79. std::string reasonForTerminationStr;
  80. volatile Node::ReasonForTermination reasonForTermination;
  81. volatile bool started;
  82. volatile bool running;
  83. volatile bool resynchronize;
  84. volatile bool disableRootTopologyUpdates;
  85. std::string overrideRootTopology;
  86. // This function performs final node tear-down
  87. inline Node::ReasonForTermination terminate()
  88. {
  89. RuntimeEnvironment *RR = &renv;
  90. LOG("terminating: %s",reasonForTerminationStr.c_str());
  91. renv.shutdownInProgress = true;
  92. Thread::sleep(500);
  93. running = false;
  94. #ifndef __WINDOWS__
  95. delete renv.netconfService;
  96. #endif
  97. delete renv.updater; renv.updater = (SoftwareUpdater *)0;
  98. delete renv.nc; renv.nc = (NodeConfig *)0; // shut down all networks, close taps, etc.
  99. delete renv.topology; renv.topology = (Topology *)0; // now we no longer need routing info
  100. delete renv.sm; renv.sm = (SocketManager *)0; // close all sockets
  101. delete renv.sw; renv.sw = (Switch *)0; // order matters less from here down
  102. delete renv.mc; renv.mc = (Multicaster *)0;
  103. delete renv.antiRec; renv.antiRec = (AntiRecursion *)0;
  104. delete renv.http; renv.http = (HttpClient *)0;
  105. delete renv.prng; renv.prng = (CMWC4096 *)0;
  106. delete renv.log; renv.log = (Logger *)0; // but stop logging last of all
  107. return reasonForTermination;
  108. }
  109. inline Node::ReasonForTermination terminateBecause(Node::ReasonForTermination r,const char *rstr)
  110. {
  111. reasonForTerminationStr = rstr;
  112. reasonForTermination = r;
  113. return terminate();
  114. }
  115. };
  116. #ifndef __WINDOWS__ // "services" are not supported on Windows
  117. static void _netconfServiceMessageHandler(void *renv,Service &svc,const Dictionary &msg)
  118. {
  119. if (!renv)
  120. return; // sanity check
  121. const RuntimeEnvironment *RR = (const RuntimeEnvironment *)renv;
  122. try {
  123. //TRACE("from netconf:\n%s",msg.toString().c_str());
  124. const std::string &type = msg.get("type");
  125. if (type == "ready") {
  126. LOG("received 'ready' from netconf.service, sending netconf-init with identity information...");
  127. Dictionary initMessage;
  128. initMessage["type"] = "netconf-init";
  129. initMessage["netconfId"] = RR->identity.toString(true);
  130. RR->netconfService->send(initMessage);
  131. } else if (type == "netconf-response") {
  132. uint64_t inRePacketId = strtoull(msg.get("requestId").c_str(),(char **)0,16);
  133. uint64_t nwid = strtoull(msg.get("nwid").c_str(),(char **)0,16);
  134. Address peerAddress(msg.get("peer").c_str());
  135. if (peerAddress) {
  136. if (msg.contains("error")) {
  137. Packet::ErrorCode errCode = Packet::ERROR_INVALID_REQUEST;
  138. const std::string &err = msg.get("error");
  139. if (err == "OBJ_NOT_FOUND")
  140. errCode = Packet::ERROR_OBJ_NOT_FOUND;
  141. else if (err == "ACCESS_DENIED")
  142. errCode = Packet::ERROR_NETWORK_ACCESS_DENIED_;
  143. Packet outp(peerAddress,RR->identity.address(),Packet::VERB_ERROR);
  144. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  145. outp.append(inRePacketId);
  146. outp.append((unsigned char)errCode);
  147. outp.append(nwid);
  148. RR->sw->send(outp,true);
  149. } else if (msg.contains("netconf")) {
  150. const std::string &netconf = msg.get("netconf");
  151. if (netconf.length() < 2048) { // sanity check
  152. Packet outp(peerAddress,RR->identity.address(),Packet::VERB_OK);
  153. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  154. outp.append(inRePacketId);
  155. outp.append(nwid);
  156. outp.append((uint16_t)netconf.length());
  157. outp.append(netconf.data(),netconf.length());
  158. outp.compress();
  159. RR->sw->send(outp,true);
  160. }
  161. }
  162. }
  163. } else if (type == "netconf-push") {
  164. if (msg.contains("to")) {
  165. Dictionary to(msg.get("to")); // key: peer address, value: comma-delimited network list
  166. for(Dictionary::iterator t(to.begin());t!=to.end();++t) {
  167. Address ztaddr(t->first);
  168. if (ztaddr) {
  169. Packet outp(ztaddr,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  170. char *saveptr = (char *)0;
  171. // Note: this loop trashes t->second, which is quasi-legal C++ but
  172. // shouldn't break anything as long as we don't try to use 'to'
  173. // for anything interesting after doing this.
  174. for(char *p=Utils::stok(const_cast<char *>(t->second.c_str()),",",&saveptr);(p);p=Utils::stok((char *)0,",",&saveptr)) {
  175. uint64_t nwid = Utils::hexStrToU64(p);
  176. if (nwid) {
  177. if ((outp.size() + sizeof(uint64_t)) >= ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  178. RR->sw->send(outp,true);
  179. outp.reset(ztaddr,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  180. }
  181. outp.append(nwid);
  182. }
  183. }
  184. if (outp.payloadLength())
  185. RR->sw->send(outp,true);
  186. }
  187. }
  188. }
  189. }
  190. } catch (std::exception &exc) {
  191. LOG("unexpected exception parsing response from netconf service: %s",exc.what());
  192. } catch ( ... ) {
  193. LOG("unexpected exception parsing response from netconf service: unknown exception");
  194. }
  195. }
  196. #endif // !__WINDOWS__
  197. Node::Node(
  198. const char *hp,
  199. EthernetTapFactory *tf,
  200. RoutingTable *rt,
  201. unsigned int udpPort,
  202. unsigned int tcpPort,
  203. bool resetIdentity,
  204. const char *overrideRootTopology) throw() :
  205. _impl(new _NodeImpl)
  206. {
  207. _NodeImpl *impl = (_NodeImpl *)_impl;
  208. if ((hp)&&(hp[0]))
  209. impl->renv.homePath = hp;
  210. else impl->renv.homePath = ZT_DEFAULTS.defaultHomePath;
  211. impl->renv.tapFactory = tf;
  212. impl->renv.routingTable = rt;
  213. if (resetIdentity) {
  214. // Forget identity and peer database, peer keys, etc.
  215. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  216. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  217. Utils::rm((impl->renv.homePath + ZT_PATH_SEPARATOR_S + "peers.persist").c_str());
  218. // Truncate network config information in networks.d but leave the files since we
  219. // still want to remember any networks we have joined. This will force those networks
  220. // to be reconfigured with our newly regenerated identity after startup.
  221. std::string networksDotD(impl->renv.homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  222. std::map< std::string,bool > nwfiles(Utils::listDirectory(networksDotD.c_str()));
  223. for(std::map<std::string,bool>::iterator nwf(nwfiles.begin());nwf!=nwfiles.end();++nwf) {
  224. FILE *trun = fopen((networksDotD + ZT_PATH_SEPARATOR_S + nwf->first).c_str(),"w");
  225. if (trun)
  226. fclose(trun);
  227. }
  228. }
  229. impl->udpPort = udpPort & 0xffff;
  230. impl->tcpPort = tcpPort & 0xffff;
  231. impl->reasonForTermination = Node::NODE_RUNNING;
  232. impl->started = false;
  233. impl->running = false;
  234. impl->resynchronize = false;
  235. if (overrideRootTopology) {
  236. impl->disableRootTopologyUpdates = true;
  237. impl->overrideRootTopology = overrideRootTopology;
  238. } else {
  239. impl->disableRootTopologyUpdates = false;
  240. }
  241. }
  242. Node::~Node()
  243. {
  244. delete (_NodeImpl *)_impl;
  245. }
  246. static void _CBztTraffic(const SharedPtr<Socket> &fromSock,void *arg,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  247. {
  248. const RuntimeEnvironment *RR = (const RuntimeEnvironment *)arg;
  249. if ((RR->sw)&&(!RR->shutdownInProgress))
  250. RR->sw->onRemotePacket(fromSock,from,data);
  251. }
  252. static void _cbHandleGetRootTopology(void *arg,int code,const std::string &url,const std::string &body)
  253. {
  254. RuntimeEnvironment *RR = (RuntimeEnvironment *)arg;
  255. if (RR->shutdownInProgress)
  256. return;
  257. if ((code != 200)||(body.length() == 0)) {
  258. TRACE("failed to retrieve %s",url.c_str());
  259. return;
  260. }
  261. try {
  262. Dictionary rt(body);
  263. if (!Topology::authenticateRootTopology(rt)) {
  264. LOG("discarded invalid root topology update from %s (signature check failed)",url.c_str());
  265. return;
  266. }
  267. {
  268. std::string rootTopologyPath(RR->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
  269. std::string rootTopology;
  270. if (Utils::readFile(rootTopologyPath.c_str(),rootTopology)) {
  271. Dictionary alreadyHave(rootTopology);
  272. if (alreadyHave == rt) {
  273. TRACE("retrieved root topology from %s but no change (same as on disk)",url.c_str());
  274. return;
  275. } else if (alreadyHave.signatureTimestamp() > rt.signatureTimestamp()) {
  276. TRACE("retrieved root topology from %s but no change (ours is newer)",url.c_str());
  277. return;
  278. }
  279. }
  280. Utils::writeFile(rootTopologyPath.c_str(),body);
  281. }
  282. RR->topology->setSupernodes(Dictionary(rt.get("supernodes")));
  283. } catch ( ... ) {
  284. LOG("discarded invalid root topology update from %s (format invalid)",url.c_str());
  285. return;
  286. }
  287. }
  288. Node::ReasonForTermination Node::run()
  289. throw()
  290. {
  291. _NodeImpl *impl = (_NodeImpl *)_impl;
  292. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  293. impl->started = true;
  294. impl->running = true;
  295. try {
  296. #ifdef ZT_LOG_STDOUT
  297. RR->log = new Logger((const char *)0,(const char *)0,0);
  298. #else
  299. RR->log = new Logger((RR->homePath + ZT_PATH_SEPARATOR_S + "node.log").c_str(),(const char *)0,131072);
  300. #endif
  301. LOG("starting version %s",versionString());
  302. // Create non-crypto PRNG right away in case other code in init wants to use it
  303. RR->prng = new CMWC4096();
  304. // Read identity public and secret, generating if not present
  305. {
  306. bool gotId = false;
  307. std::string identitySecretPath(RR->homePath + ZT_PATH_SEPARATOR_S + "identity.secret");
  308. std::string identityPublicPath(RR->homePath + ZT_PATH_SEPARATOR_S + "identity.public");
  309. std::string idser;
  310. if (Utils::readFile(identitySecretPath.c_str(),idser))
  311. gotId = RR->identity.fromString(idser);
  312. if ((gotId)&&(!RR->identity.locallyValidate()))
  313. gotId = false;
  314. if (gotId) {
  315. // Make sure identity.public matches identity.secret
  316. idser = std::string();
  317. Utils::readFile(identityPublicPath.c_str(),idser);
  318. std::string pubid(RR->identity.toString(false));
  319. if (idser != pubid) {
  320. if (!Utils::writeFile(identityPublicPath.c_str(),pubid))
  321. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  322. }
  323. } else {
  324. LOG("no identity found or identity invalid, generating one... this might take a few seconds...");
  325. RR->identity.generate();
  326. LOG("generated new identity: %s",RR->identity.address().toString().c_str());
  327. idser = RR->identity.toString(true);
  328. if (!Utils::writeFile(identitySecretPath.c_str(),idser))
  329. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.secret (home path not writable?)");
  330. idser = RR->identity.toString(false);
  331. if (!Utils::writeFile(identityPublicPath.c_str(),idser))
  332. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"could not write identity.public (home path not writable?)");
  333. }
  334. Utils::lockDownFile(identitySecretPath.c_str(),false);
  335. }
  336. // Make sure networks.d exists (used by NodeConfig to remember networks)
  337. {
  338. std::string networksDotD(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  339. #ifdef __WINDOWS__
  340. CreateDirectoryA(networksDotD.c_str(),NULL);
  341. #else
  342. mkdir(networksDotD.c_str(),0700);
  343. #endif
  344. }
  345. // Make sure iddb.d exists (used by Topology to remember identities)
  346. {
  347. std::string iddbDotD(RR->homePath + ZT_PATH_SEPARATOR_S + "iddb.d");
  348. #ifdef __WINDOWS__
  349. CreateDirectoryA(iddbDotD.c_str(),NULL);
  350. #else
  351. mkdir(iddbDotD.c_str(),0700);
  352. #endif
  353. }
  354. RR->http = new HttpClient();
  355. RR->antiRec = new AntiRecursion();
  356. RR->mc = new Multicaster(RR);
  357. RR->sw = new Switch(RR);
  358. RR->sm = new SocketManager(impl->udpPort,impl->tcpPort,&_CBztTraffic,RR);
  359. RR->topology = new Topology(RR);
  360. try {
  361. RR->nc = new NodeConfig(RR);
  362. } catch (std::exception &exc) {
  363. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unable to initialize IPC socket: is ZeroTier One already running?");
  364. }
  365. RR->node = this;
  366. #ifdef ZT_AUTO_UPDATE
  367. if (ZT_DEFAULTS.updateLatestNfoURL.length()) {
  368. RR->updater = new SoftwareUpdater(RR);
  369. RR->updater->cleanOldUpdates(); // clean out updates.d on startup
  370. } else {
  371. LOG("WARNING: unable to enable software updates: latest .nfo URL from ZT_DEFAULTS is empty (does this platform actually support software updates?)");
  372. }
  373. #endif
  374. // Initialize root topology from defaults or root-toplogy file in home path on disk
  375. if (impl->overrideRootTopology.length() == 0) {
  376. std::string rootTopologyPath(RR->homePath + ZT_PATH_SEPARATOR_S + "root-topology");
  377. std::string rootTopology;
  378. if (!Utils::readFile(rootTopologyPath.c_str(),rootTopology))
  379. rootTopology = ZT_DEFAULTS.defaultRootTopology;
  380. try {
  381. Dictionary rt(rootTopology);
  382. if (Topology::authenticateRootTopology(rt)) {
  383. // Set supernodes if root topology signature is valid
  384. RR->topology->setSupernodes(Dictionary(rt.get("supernodes",""))); // set supernodes from root-topology
  385. // If root-topology contains noupdate=1, disable further updates and only use what was on disk
  386. impl->disableRootTopologyUpdates = (Utils::strToInt(rt.get("noupdate","0").c_str()) > 0);
  387. } else {
  388. // Revert to built-in defaults if root topology fails signature check
  389. LOG("%s failed signature check, using built-in defaults instead",rootTopologyPath.c_str());
  390. Utils::rm(rootTopologyPath.c_str());
  391. RR->topology->setSupernodes(Dictionary(Dictionary(ZT_DEFAULTS.defaultRootTopology).get("supernodes","")));
  392. impl->disableRootTopologyUpdates = false;
  393. }
  394. } catch ( ... ) {
  395. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"invalid root-topology format");
  396. }
  397. } else {
  398. try {
  399. Dictionary rt(impl->overrideRootTopology);
  400. RR->topology->setSupernodes(Dictionary(rt.get("supernodes","")));
  401. impl->disableRootTopologyUpdates = true;
  402. } catch ( ... ) {
  403. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"invalid root-topology format");
  404. }
  405. }
  406. // Delete peers.persist if it exists -- legacy file, just takes up space
  407. Utils::rm(std::string(RR->homePath + ZT_PATH_SEPARATOR_S + "peers.persist").c_str());
  408. } catch (std::bad_alloc &exc) {
  409. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"memory allocation failure");
  410. } catch (std::runtime_error &exc) {
  411. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,exc.what());
  412. } catch ( ... ) {
  413. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unknown exception during initialization");
  414. }
  415. // Start external service subprocesses, which is only used by special nodes
  416. // right now and isn't available on Windows.
  417. #ifndef __WINDOWS__
  418. try {
  419. std::string netconfServicePath(RR->homePath + ZT_PATH_SEPARATOR_S + "services.d" + ZT_PATH_SEPARATOR_S + "netconf.service");
  420. if (Utils::fileExists(netconfServicePath.c_str())) {
  421. LOG("netconf.d/netconf.service appears to exist, starting...");
  422. RR->netconfService = new Service(RR,"netconf",netconfServicePath.c_str(),&_netconfServiceMessageHandler,RR);
  423. Dictionary initMessage;
  424. initMessage["type"] = "netconf-init";
  425. initMessage["netconfId"] = RR->identity.toString(true);
  426. RR->netconfService->send(initMessage);
  427. }
  428. } catch ( ... ) {
  429. LOG("unexpected exception attempting to start services");
  430. }
  431. #endif
  432. // Core I/O loop
  433. try {
  434. /* Shut down if this file exists but fails to open. This is used on Mac to
  435. * shut down automatically on .app deletion by symlinking this to the
  436. * Info.plist file inside the ZeroTier One application. This causes the
  437. * service to die when the user throws away the app, allowing uninstallation
  438. * in the natural Mac way. */
  439. std::string shutdownIfUnreadablePath(RR->homePath + ZT_PATH_SEPARATOR_S + "shutdownIfUnreadable");
  440. uint64_t lastNetworkAutoconfCheck = Utils::now() - 5000ULL; // check autoconf again after 5s for startup
  441. uint64_t lastPingCheck = 0;
  442. uint64_t lastClean = Utils::now(); // don't need to do this immediately
  443. uint64_t lastNetworkFingerprintCheck = 0;
  444. uint64_t lastMulticastCheck = 0;
  445. uint64_t lastSupernodePingCheck = 0;
  446. uint64_t lastBeacon = 0;
  447. uint64_t lastRootTopologyFetch = 0;
  448. uint64_t lastShutdownIfUnreadableCheck = 0;
  449. long lastDelayDelta = 0;
  450. uint64_t networkConfigurationFingerprint = 0;
  451. RR->timeOfLastResynchronize = Utils::now();
  452. // We are up and running
  453. RR->initialized = true;
  454. while (impl->reasonForTermination == NODE_RUNNING) {
  455. uint64_t now = Utils::now();
  456. bool resynchronize = false;
  457. /* This is how the service automatically shuts down when the OSX .app is
  458. * thrown in the trash. It's not used on any other platform for now but
  459. * could do similar things. It's disabled on Windows since it doesn't really
  460. * work there. */
  461. #ifdef __UNIX_LIKE__
  462. if ((now - lastShutdownIfUnreadableCheck) > 10000) {
  463. lastShutdownIfUnreadableCheck = now;
  464. if (Utils::fileExists(shutdownIfUnreadablePath.c_str(),false)) {
  465. int tmpfd = ::open(shutdownIfUnreadablePath.c_str(),O_RDONLY,0);
  466. if (tmpfd < 0) {
  467. return impl->terminateBecause(Node::NODE_NORMAL_TERMINATION,"shutdownIfUnreadable exists but is not readable");
  468. } else ::close(tmpfd);
  469. }
  470. }
  471. #endif
  472. // If it looks like the computer slept and woke, resynchronize.
  473. if (lastDelayDelta >= ZT_SLEEP_WAKE_DETECTION_THRESHOLD) {
  474. resynchronize = true;
  475. LOG("probable suspend/resume detected, pausing a moment for things to settle...");
  476. Thread::sleep(ZT_SLEEP_WAKE_SETTLE_TIME);
  477. }
  478. // If our network environment looks like it changed, resynchronize.
  479. if ((resynchronize)||((now - lastNetworkFingerprintCheck) >= ZT_NETWORK_FINGERPRINT_CHECK_DELAY)) {
  480. lastNetworkFingerprintCheck = now;
  481. uint64_t fp = RR->routingTable->networkEnvironmentFingerprint(RR->nc->networkTapDeviceNames());
  482. if (fp != networkConfigurationFingerprint) {
  483. LOG("netconf fingerprint change: %.16llx != %.16llx, resyncing with network",networkConfigurationFingerprint,fp);
  484. networkConfigurationFingerprint = fp;
  485. resynchronize = true;
  486. }
  487. }
  488. // Supernodes do not resynchronize unless explicitly ordered via SIGHUP.
  489. if ((resynchronize)&&(RR->topology->amSupernode()))
  490. resynchronize = false;
  491. // Check for SIGHUP / force resync.
  492. if (impl->resynchronize) {
  493. impl->resynchronize = false;
  494. resynchronize = true;
  495. LOG("resynchronize forced by user, syncing with network");
  496. }
  497. if (resynchronize) {
  498. RR->tcpTunnelingEnabled = false; // turn off TCP tunneling master switch at first, will be reenabled on persistent UDP failure
  499. RR->timeOfLastResynchronize = now;
  500. }
  501. /* Supernodes are pinged separately and more aggressively. The
  502. * ZT_STARTUP_AGGRO parameter sets a limit on how rapidly they are
  503. * tried, while PingSupernodesThatNeedPing contains the logic for
  504. * determining if they need PING. */
  505. if ((now - lastSupernodePingCheck) >= ZT_STARTUP_AGGRO) {
  506. lastSupernodePingCheck = now;
  507. uint64_t lastReceiveFromAnySupernode = 0; // function object result paramter
  508. RR->topology->eachSupernodePeer(Topology::FindMostRecentDirectReceiveTimestamp(lastReceiveFromAnySupernode));
  509. // Turn on TCP tunneling master switch if we haven't heard anything since before
  510. // the last resynchronize and we've been trying long enough.
  511. uint64_t tlr = RR->timeOfLastResynchronize;
  512. if ((lastReceiveFromAnySupernode < tlr)&&((now - tlr) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT)) {
  513. TRACE("network still unreachable after %u ms, TCP TUNNELING ENABLED",(unsigned int)ZT_TCP_TUNNEL_FAILOVER_TIMEOUT);
  514. RR->tcpTunnelingEnabled = true;
  515. }
  516. RR->topology->eachSupernodePeer(Topology::PingSupernodesThatNeedPing(RR,now));
  517. }
  518. if (resynchronize) {
  519. /* Send NOP to all peers on resynchronize, directly to supernodes and
  520. * indirectly to regular nodes (to trigger RENDEZVOUS). Also clear
  521. * learned paths since they're likely no longer valid, and close
  522. * TCP sockets since they're also likely invalid. */
  523. RR->sm->closeTcpSockets();
  524. RR->topology->eachPeer(Topology::ResetActivePeers(RR,now));
  525. } else {
  526. /* Periodically check for changes in our local multicast subscriptions
  527. * and broadcast those changes to directly connected peers. */
  528. if ((now - lastMulticastCheck) >= ZT_MULTICAST_LOCAL_POLL_PERIOD) {
  529. lastMulticastCheck = now;
  530. try {
  531. std::vector< SharedPtr<Network> > networks(RR->nc->networks());
  532. for(std::vector< SharedPtr<Network> >::const_iterator nw(networks.begin());nw!=networks.end();++nw)
  533. (*nw)->rescanMulticastGroups();
  534. } catch (std::exception &exc) {
  535. LOG("unexpected exception announcing multicast groups: %s",exc.what());
  536. } catch ( ... ) {
  537. LOG("unexpected exception announcing multicast groups: (unknown)");
  538. }
  539. }
  540. /* Periodically ping all our non-stale direct peers unless we're a supernode.
  541. * Supernodes only ping each other (which is done above). */
  542. if ((!RR->topology->amSupernode())&&((now - lastPingCheck) >= ZT_PING_CHECK_DELAY)) {
  543. lastPingCheck = now;
  544. try {
  545. RR->topology->eachPeer(Topology::PingPeersThatNeedPing(RR,now));
  546. } catch (std::exception &exc) {
  547. LOG("unexpected exception running ping check cycle: %s",exc.what());
  548. } catch ( ... ) {
  549. LOG("unexpected exception running ping check cycle: (unkonwn)");
  550. }
  551. }
  552. }
  553. // Update network configurations when needed.
  554. if ((resynchronize)||((now - lastNetworkAutoconfCheck) >= ZT_NETWORK_AUTOCONF_CHECK_DELAY)) {
  555. lastNetworkAutoconfCheck = now;
  556. std::vector< SharedPtr<Network> > nets(RR->nc->networks());
  557. for(std::vector< SharedPtr<Network> >::iterator n(nets.begin());n!=nets.end();++n) {
  558. if ((now - (*n)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)
  559. (*n)->requestConfiguration();
  560. }
  561. }
  562. // Do periodic tasks in submodules.
  563. if ((now - lastClean) >= ZT_DB_CLEAN_PERIOD) {
  564. lastClean = now;
  565. RR->topology->clean(now);
  566. RR->mc->clean(now);
  567. RR->nc->clean();
  568. if (RR->updater)
  569. RR->updater->checkIfMaxIntervalExceeded(now);
  570. }
  571. // Send beacons to physical local LANs
  572. if ((resynchronize)||((now - lastBeacon) >= ZT_BEACON_INTERVAL)) {
  573. lastBeacon = now;
  574. char bcn[ZT_PROTO_BEACON_LENGTH];
  575. void *bcnptr = bcn;
  576. *((uint32_t *)(bcnptr)) = RR->prng->next32();
  577. bcnptr = bcn + 4;
  578. *((uint32_t *)(bcnptr)) = RR->prng->next32();
  579. RR->identity.address().copyTo(bcn + ZT_PROTO_BEACON_IDX_ADDRESS,ZT_ADDRESS_LENGTH);
  580. TRACE("sending LAN beacon to %s",ZT_DEFAULTS.v4Broadcast.toString().c_str());
  581. RR->antiRec->logOutgoingZT(bcn,ZT_PROTO_BEACON_LENGTH);
  582. RR->sm->send(ZT_DEFAULTS.v4Broadcast,false,false,bcn,ZT_PROTO_BEACON_LENGTH);
  583. }
  584. // Check for updates to root topology (supernodes) periodically
  585. if ((now - lastRootTopologyFetch) >= ZT_UPDATE_ROOT_TOPOLOGY_CHECK_INTERVAL) {
  586. lastRootTopologyFetch = now;
  587. if (!impl->disableRootTopologyUpdates) {
  588. TRACE("fetching root topology from %s",ZT_DEFAULTS.rootTopologyUpdateURL.c_str());
  589. RR->http->GET(ZT_DEFAULTS.rootTopologyUpdateURL,HttpClient::NO_HEADERS,60,&_cbHandleGetRootTopology,RR);
  590. }
  591. }
  592. // Sleep for loop interval or until something interesting happens.
  593. try {
  594. unsigned long delay = std::min((unsigned long)ZT_MAX_SERVICE_LOOP_INTERVAL,RR->sw->doTimerTasks());
  595. uint64_t start = Utils::now();
  596. RR->sm->poll(delay);
  597. lastDelayDelta = (long)(Utils::now() - start) - (long)delay; // used to detect sleep/wake
  598. } catch (std::exception &exc) {
  599. LOG("unexpected exception running Switch doTimerTasks: %s",exc.what());
  600. } catch ( ... ) {
  601. LOG("unexpected exception running Switch doTimerTasks: (unknown)");
  602. }
  603. }
  604. } catch ( ... ) {
  605. LOG("FATAL: unexpected exception in core loop: unknown exception");
  606. return impl->terminateBecause(Node::NODE_UNRECOVERABLE_ERROR,"unexpected exception during outer main I/O loop");
  607. }
  608. return impl->terminate();
  609. }
  610. const char *Node::terminationMessage() const
  611. throw()
  612. {
  613. if ((!((_NodeImpl *)_impl)->started)||(((_NodeImpl *)_impl)->running))
  614. return (const char *)0;
  615. return ((_NodeImpl *)_impl)->reasonForTerminationStr.c_str();
  616. }
  617. void Node::terminate(ReasonForTermination reason,const char *reasonText)
  618. throw()
  619. {
  620. ((_NodeImpl *)_impl)->reasonForTermination = reason;
  621. ((_NodeImpl *)_impl)->reasonForTerminationStr = ((reasonText) ? reasonText : "");
  622. ((_NodeImpl *)_impl)->renv.sm->whack();
  623. }
  624. void Node::resync()
  625. throw()
  626. {
  627. ((_NodeImpl *)_impl)->resynchronize = true;
  628. ((_NodeImpl *)_impl)->renv.sm->whack();
  629. }
  630. bool Node::online()
  631. throw()
  632. {
  633. _NodeImpl *impl = (_NodeImpl *)_impl;
  634. if (!impl->running)
  635. return false;
  636. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  637. uint64_t now = Utils::now();
  638. uint64_t since = RR->timeOfLastResynchronize;
  639. std::vector< SharedPtr<Peer> > snp(RR->topology->supernodePeers());
  640. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  641. uint64_t lastRec = (*sn)->lastDirectReceive();
  642. if ((lastRec)&&(lastRec > since)&&((now - lastRec) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
  643. return true;
  644. }
  645. return false;
  646. }
  647. bool Node::started()
  648. throw()
  649. {
  650. _NodeImpl *impl = (_NodeImpl *)_impl;
  651. return impl->started;
  652. }
  653. bool Node::running()
  654. throw()
  655. {
  656. _NodeImpl *impl = (_NodeImpl *)_impl;
  657. return impl->running;
  658. }
  659. bool Node::initialized()
  660. throw()
  661. {
  662. _NodeImpl *impl = (_NodeImpl *)_impl;
  663. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  664. return ((RR)&&(RR->initialized));
  665. }
  666. uint64_t Node::address()
  667. throw()
  668. {
  669. _NodeImpl *impl = (_NodeImpl *)_impl;
  670. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  671. if ((!RR)||(!RR->initialized))
  672. return 0;
  673. return RR->identity.address().toInt();
  674. }
  675. void Node::join(uint64_t nwid)
  676. throw()
  677. {
  678. _NodeImpl *impl = (_NodeImpl *)_impl;
  679. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  680. RR->nc->join(nwid);
  681. }
  682. void Node::leave(uint64_t nwid)
  683. throw()
  684. {
  685. _NodeImpl *impl = (_NodeImpl *)_impl;
  686. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  687. RR->nc->leave(nwid);
  688. }
  689. struct GatherPeerStatistics
  690. {
  691. uint64_t now;
  692. ZT1_Node_Status *status;
  693. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  694. {
  695. ++status->knownPeers;
  696. if (p->hasActiveDirectPath(now))
  697. ++status->directlyConnectedPeers;
  698. if (p->alive(now))
  699. ++status->alivePeers;
  700. }
  701. };
  702. void Node::status(ZT1_Node_Status *status)
  703. throw()
  704. {
  705. _NodeImpl *impl = (_NodeImpl *)_impl;
  706. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  707. memset(status,0,sizeof(ZT1_Node_Status));
  708. Utils::scopy(status->publicIdentity,sizeof(status->publicIdentity),RR->identity.toString(false).c_str());
  709. RR->identity.address().toString(status->address,sizeof(status->address));
  710. status->rawAddress = RR->identity.address().toInt();
  711. status->knownPeers = 0;
  712. status->supernodes = RR->topology->numSupernodes();
  713. status->directlyConnectedPeers = 0;
  714. status->alivePeers = 0;
  715. GatherPeerStatistics gps;
  716. gps.now = Utils::now();
  717. gps.status = status;
  718. RR->topology->eachPeer<GatherPeerStatistics &>(gps);
  719. if (status->alivePeers > 0) {
  720. double dlsr = (double)status->directlyConnectedPeers / (double)status->alivePeers;
  721. if (dlsr > 1.0) dlsr = 1.0;
  722. if (dlsr < 0.0) dlsr = 0.0;
  723. status->directLinkSuccessRate = (float)dlsr;
  724. } else status->directLinkSuccessRate = 1.0f; // no connections to no active peers == 100% success at nothing
  725. status->online = online();
  726. status->running = impl->running;
  727. }
  728. struct CollectPeersAndPaths
  729. {
  730. std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > > data;
  731. inline void operator()(Topology &t,const SharedPtr<Peer> &p) { this->data.push_back(std::pair< SharedPtr<Peer>,std::vector<Path> >(p,p->paths())); }
  732. };
  733. struct SortPeersAndPathsInAscendingAddressOrder
  734. {
  735. inline bool operator()(const std::pair< SharedPtr<Peer>,std::vector<Path> > &a,const std::pair< SharedPtr<Peer>,std::vector<Path> > &b) const { return (a.first->address() < b.first->address()); }
  736. };
  737. ZT1_Node_PeerList *Node::listPeers()
  738. throw()
  739. {
  740. _NodeImpl *impl = (_NodeImpl *)_impl;
  741. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  742. CollectPeersAndPaths pp;
  743. RR->topology->eachPeer<CollectPeersAndPaths &>(pp);
  744. std::sort(pp.data.begin(),pp.data.end(),SortPeersAndPathsInAscendingAddressOrder());
  745. unsigned int returnBufSize = sizeof(ZT1_Node_PeerList);
  746. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p)
  747. returnBufSize += sizeof(ZT1_Node_Peer) + (sizeof(ZT1_Node_PhysicalPath) * p->second.size());
  748. char *buf = (char *)::malloc(returnBufSize);
  749. if (!buf)
  750. return (ZT1_Node_PeerList *)0;
  751. memset(buf,0,returnBufSize);
  752. ZT1_Node_PeerList *pl = (ZT1_Node_PeerList *)buf;
  753. buf += sizeof(ZT1_Node_PeerList);
  754. pl->peers = (ZT1_Node_Peer *)buf;
  755. buf += (sizeof(ZT1_Node_Peer) * pp.data.size());
  756. pl->numPeers = 0;
  757. uint64_t now = Utils::now();
  758. for(std::vector< std::pair< SharedPtr<Peer>,std::vector<Path> > >::iterator p(pp.data.begin());p!=pp.data.end();++p) {
  759. ZT1_Node_Peer *prec = &(pl->peers[pl->numPeers++]);
  760. if (p->first->remoteVersionKnown())
  761. Utils::snprintf(prec->remoteVersion,sizeof(prec->remoteVersion),"%u.%u.%u",p->first->remoteVersionMajor(),p->first->remoteVersionMinor(),p->first->remoteVersionRevision());
  762. p->first->address().toString(prec->address,sizeof(prec->address));
  763. prec->rawAddress = p->first->address().toInt();
  764. prec->latency = p->first->latency();
  765. prec->role = RR->topology->isSupernode(p->first->address()) ? ZT1_Node_Peer::ZT1_Node_Peer_SUPERNODE : ZT1_Node_Peer::ZT1_Node_Peer_NODE;
  766. prec->paths = (ZT1_Node_PhysicalPath *)buf;
  767. buf += sizeof(ZT1_Node_PhysicalPath) * p->second.size();
  768. prec->numPaths = 0;
  769. for(std::vector<Path>::iterator pi(p->second.begin());pi!=p->second.end();++pi) {
  770. ZT1_Node_PhysicalPath *path = &(prec->paths[prec->numPaths++]);
  771. path->type = static_cast<typeof(path->type)>(pi->type());
  772. if (pi->address().isV6()) {
  773. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  774. memcpy(path->address.bits,pi->address().rawIpData(),16);
  775. // TODO: zoneIndex not supported yet, but should be once echo-location works w/V6
  776. } else {
  777. path->address.type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  778. memcpy(path->address.bits,pi->address().rawIpData(),4);
  779. }
  780. path->address.port = pi->address().port();
  781. Utils::scopy(path->address.ascii,sizeof(path->address.ascii),pi->address().toIpString().c_str());
  782. path->lastSend = (pi->lastSend() > 0) ? ((long)(now - pi->lastSend())) : (long)-1;
  783. path->lastReceive = (pi->lastReceived() > 0) ? ((long)(now - pi->lastReceived())) : (long)-1;
  784. path->lastPing = (pi->lastPing() > 0) ? ((long)(now - pi->lastPing())) : (long)-1;
  785. path->active = pi->active(now);
  786. path->fixed = pi->fixed();
  787. }
  788. }
  789. return pl;
  790. }
  791. // Fills out everything but ips[] and numIps, which must be done more manually
  792. static void _fillNetworkQueryResultBuffer(const SharedPtr<Network> &network,const SharedPtr<NetworkConfig> &nconf,ZT1_Node_Network *nbuf)
  793. {
  794. nbuf->nwid = network->id();
  795. Utils::snprintf(nbuf->nwidHex,sizeof(nbuf->nwidHex),"%.16llx",(unsigned long long)network->id());
  796. if (nconf) {
  797. Utils::scopy(nbuf->name,sizeof(nbuf->name),nconf->name().c_str());
  798. Utils::scopy(nbuf->description,sizeof(nbuf->description),nconf->description().c_str());
  799. }
  800. Utils::scopy(nbuf->device,sizeof(nbuf->device),network->tapDeviceName().c_str());
  801. Utils::scopy(nbuf->statusStr,sizeof(nbuf->statusStr),Network::statusString(network->status()));
  802. network->mac().toString(nbuf->macStr,sizeof(nbuf->macStr));
  803. network->mac().copyTo(nbuf->mac,sizeof(nbuf->mac));
  804. uint64_t lcu = network->lastConfigUpdate();
  805. if (lcu > 0)
  806. nbuf->configAge = (long)(Utils::now() - lcu);
  807. else nbuf->configAge = -1;
  808. nbuf->status = static_cast<typeof(nbuf->status)>(network->status());
  809. nbuf->enabled = network->enabled();
  810. nbuf->isPrivate = (nconf) ? nconf->isPrivate() : true;
  811. }
  812. ZT1_Node_Network *Node::getNetworkStatus(uint64_t nwid)
  813. throw()
  814. {
  815. _NodeImpl *impl = (_NodeImpl *)_impl;
  816. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  817. SharedPtr<Network> network(RR->nc->network(nwid));
  818. if (!network)
  819. return (ZT1_Node_Network *)0;
  820. SharedPtr<NetworkConfig> nconf(network->config2());
  821. std::set<InetAddress> ips(network->ips());
  822. char *buf = (char *)::malloc(sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  823. if (!buf)
  824. return (ZT1_Node_Network *)0;
  825. memset(buf,0,sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ips.size()));
  826. ZT1_Node_Network *nbuf = (ZT1_Node_Network *)buf;
  827. buf += sizeof(ZT1_Node_Network);
  828. _fillNetworkQueryResultBuffer(network,nconf,nbuf);
  829. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  830. nbuf->numIps = 0;
  831. for(std::set<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  832. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  833. if (ip->isV6()) {
  834. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  835. memcpy(ipb->bits,ip->rawIpData(),16);
  836. } else {
  837. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  838. memcpy(ipb->bits,ip->rawIpData(),4);
  839. }
  840. ipb->port = ip->port();
  841. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  842. }
  843. return nbuf;
  844. }
  845. ZT1_Node_NetworkList *Node::listNetworks()
  846. throw()
  847. {
  848. _NodeImpl *impl = (_NodeImpl *)_impl;
  849. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  850. std::vector< SharedPtr<Network> > networks(RR->nc->networks());
  851. std::vector< SharedPtr<NetworkConfig> > nconfs(networks.size());
  852. std::vector< std::set<InetAddress> > ipsv(networks.size());
  853. unsigned long returnBufSize = sizeof(ZT1_Node_NetworkList);
  854. for(unsigned long i=0;i<networks.size();++i) {
  855. nconfs[i] = networks[i]->config2();
  856. ipsv[i] = networks[i]->ips();
  857. returnBufSize += sizeof(ZT1_Node_Network) + (sizeof(ZT1_Node_PhysicalAddress) * ipsv[i].size());
  858. }
  859. char *buf = (char *)::malloc(returnBufSize);
  860. if (!buf)
  861. return (ZT1_Node_NetworkList *)0;
  862. memset(buf,0,returnBufSize);
  863. ZT1_Node_NetworkList *nl = (ZT1_Node_NetworkList *)buf;
  864. buf += sizeof(ZT1_Node_NetworkList);
  865. nl->networks = (ZT1_Node_Network *)buf;
  866. buf += sizeof(ZT1_Node_Network) * networks.size();
  867. for(unsigned long i=0;i<networks.size();++i) {
  868. ZT1_Node_Network *nbuf = &(nl->networks[nl->numNetworks++]);
  869. _fillNetworkQueryResultBuffer(networks[i],nconfs[i],nbuf);
  870. nbuf->ips = (ZT1_Node_PhysicalAddress *)buf;
  871. buf += sizeof(ZT1_Node_PhysicalAddress);
  872. nbuf->numIps = 0;
  873. for(std::set<InetAddress>::iterator ip(ipsv[i].begin());ip!=ipsv[i].end();++ip) {
  874. ZT1_Node_PhysicalAddress *ipb = &(nbuf->ips[nbuf->numIps++]);
  875. if (ip->isV6()) {
  876. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV6;
  877. memcpy(ipb->bits,ip->rawIpData(),16);
  878. } else {
  879. ipb->type = ZT1_Node_PhysicalAddress::ZT1_Node_PhysicalAddress_TYPE_IPV4;
  880. memcpy(ipb->bits,ip->rawIpData(),4);
  881. }
  882. ipb->port = ip->port();
  883. Utils::scopy(ipb->ascii,sizeof(ipb->ascii),ip->toIpString().c_str());
  884. }
  885. }
  886. return nl;
  887. }
  888. void Node::freeQueryResult(void *qr)
  889. throw()
  890. {
  891. if (qr)
  892. ::free(qr);
  893. }
  894. bool Node::updateCheck()
  895. throw()
  896. {
  897. _NodeImpl *impl = (_NodeImpl *)_impl;
  898. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  899. if (RR->updater) {
  900. RR->updater->checkNow();
  901. return true;
  902. }
  903. return false;
  904. }
  905. bool Node::injectPacketFromHost(uint64_t nwid,const unsigned char *from,const unsigned char *to,unsigned int etherType,const void *data,unsigned int len)
  906. {
  907. if (!running())
  908. return false;
  909. if ((!from)||(!to))
  910. return false;
  911. _NodeImpl *impl = (_NodeImpl *)_impl;
  912. RuntimeEnvironment *RR = (RuntimeEnvironment *)&(impl->renv);
  913. SharedPtr<Network> network(RR->nc->network(nwid));
  914. if (network)
  915. return network->tapInjectPacketFromHost(MAC(from,6),MAC(to,6),etherType,data,len);
  916. return false;
  917. }
  918. class _VersionStringMaker
  919. {
  920. public:
  921. char vs[32];
  922. _VersionStringMaker()
  923. {
  924. Utils::snprintf(vs,sizeof(vs),"%d.%d.%d",(int)ZEROTIER_ONE_VERSION_MAJOR,(int)ZEROTIER_ONE_VERSION_MINOR,(int)ZEROTIER_ONE_VERSION_REVISION);
  925. }
  926. ~_VersionStringMaker() {}
  927. };
  928. static const _VersionStringMaker __versionString;
  929. const char *Node::versionString() throw() { return __versionString.vs; }
  930. unsigned int Node::versionMajor() throw() { return ZEROTIER_ONE_VERSION_MAJOR; }
  931. unsigned int Node::versionMinor() throw() { return ZEROTIER_ONE_VERSION_MINOR; }
  932. unsigned int Node::versionRevision() throw() { return ZEROTIER_ONE_VERSION_REVISION; }
  933. } // namespace ZeroTier