2
0

Node.cpp 37 KB

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