Node.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 <stdarg.h>
  30. #include <string.h>
  31. #include <stdint.h>
  32. #include "../version.h"
  33. #include "Constants.hpp"
  34. #include "Node.hpp"
  35. #include "RuntimeEnvironment.hpp"
  36. #include "NetworkController.hpp"
  37. #include "Switch.hpp"
  38. #include "Multicaster.hpp"
  39. #include "Topology.hpp"
  40. #include "Buffer.hpp"
  41. #include "Packet.hpp"
  42. #include "Address.hpp"
  43. #include "Identity.hpp"
  44. #include "SelfAwareness.hpp"
  45. #include "Cluster.hpp"
  46. #include "DeferredPackets.hpp"
  47. const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
  48. namespace ZeroTier {
  49. /****************************************************************************/
  50. /* Public Node interface (C++, exposed via CAPI bindings) */
  51. /****************************************************************************/
  52. Node::Node(
  53. uint64_t now,
  54. void *uptr,
  55. ZT_DataStoreGetFunction dataStoreGetFunction,
  56. ZT_DataStorePutFunction dataStorePutFunction,
  57. ZT_WirePacketSendFunction wirePacketSendFunction,
  58. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  59. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  60. ZT_EventCallback eventCallback) :
  61. _RR(this),
  62. RR(&_RR),
  63. _uPtr(uptr),
  64. _dataStoreGetFunction(dataStoreGetFunction),
  65. _dataStorePutFunction(dataStorePutFunction),
  66. _wirePacketSendFunction(wirePacketSendFunction),
  67. _virtualNetworkFrameFunction(virtualNetworkFrameFunction),
  68. _virtualNetworkConfigFunction(virtualNetworkConfigFunction),
  69. _eventCallback(eventCallback),
  70. _networks(),
  71. _networks_m(),
  72. _prngStreamPtr(0),
  73. _now(now),
  74. _lastPingCheck(0),
  75. _lastHousekeepingRun(0)
  76. {
  77. _online = false;
  78. // Use Salsa20 alone as a high-quality non-crypto PRNG
  79. {
  80. char foo[32];
  81. Utils::getSecureRandom(foo,32);
  82. _prng.init(foo,256,foo);
  83. memset(_prngStream,0,sizeof(_prngStream));
  84. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  85. }
  86. {
  87. std::string idtmp(dataStoreGet("identity.secret"));
  88. if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
  89. TRACE("identity.secret not found, generating...");
  90. RR->identity.generate();
  91. idtmp = RR->identity.toString(true);
  92. if (!dataStorePut("identity.secret",idtmp,true))
  93. throw std::runtime_error("unable to write identity.secret");
  94. }
  95. RR->publicIdentityStr = RR->identity.toString(false);
  96. RR->secretIdentityStr = RR->identity.toString(true);
  97. idtmp = dataStoreGet("identity.public");
  98. if (idtmp != RR->publicIdentityStr) {
  99. if (!dataStorePut("identity.public",RR->publicIdentityStr,false))
  100. throw std::runtime_error("unable to write identity.public");
  101. }
  102. }
  103. try {
  104. RR->sw = new Switch(RR);
  105. RR->mc = new Multicaster(RR);
  106. RR->topology = new Topology(RR);
  107. RR->sa = new SelfAwareness(RR);
  108. RR->dp = new DeferredPackets(RR);
  109. } catch ( ... ) {
  110. delete RR->dp;
  111. delete RR->sa;
  112. delete RR->topology;
  113. delete RR->mc;
  114. delete RR->sw;
  115. throw;
  116. }
  117. postEvent(ZT_EVENT_UP);
  118. }
  119. Node::~Node()
  120. {
  121. Mutex::Lock _l(_networks_m);
  122. _networks.clear(); // ensure that networks are destroyed before shutdow
  123. RR->dpEnabled = 0;
  124. delete RR->dp;
  125. delete RR->sa;
  126. delete RR->topology;
  127. delete RR->mc;
  128. delete RR->sw;
  129. #ifdef ZT_ENABLE_CLUSTER
  130. delete RR->cluster;
  131. #endif
  132. }
  133. ZT_ResultCode Node::processWirePacket(
  134. uint64_t now,
  135. const struct sockaddr_storage *localAddress,
  136. const struct sockaddr_storage *remoteAddress,
  137. const void *packetData,
  138. unsigned int packetLength,
  139. volatile uint64_t *nextBackgroundTaskDeadline)
  140. {
  141. _now = now;
  142. RR->sw->onRemotePacket(*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  143. return ZT_RESULT_OK;
  144. }
  145. ZT_ResultCode Node::processVirtualNetworkFrame(
  146. uint64_t now,
  147. uint64_t nwid,
  148. uint64_t sourceMac,
  149. uint64_t destMac,
  150. unsigned int etherType,
  151. unsigned int vlanId,
  152. const void *frameData,
  153. unsigned int frameLength,
  154. volatile uint64_t *nextBackgroundTaskDeadline)
  155. {
  156. _now = now;
  157. SharedPtr<Network> nw(this->network(nwid));
  158. if (nw) {
  159. RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  160. return ZT_RESULT_OK;
  161. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  162. }
  163. class _PingPeersThatNeedPing
  164. {
  165. public:
  166. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now,const std::vector< std::pair<Address,InetAddress> > &relays) :
  167. lastReceiveFromUpstream(0),
  168. RR(renv),
  169. _now(now),
  170. _relays(relays),
  171. _world(RR->topology->world())
  172. {
  173. }
  174. uint64_t lastReceiveFromUpstream; // tracks last time we got a packet from an 'upstream' peer like a root or a relay
  175. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  176. {
  177. bool upstream = false;
  178. InetAddress stableEndpoint4,stableEndpoint6;
  179. // If this is a world root, pick (if possible) both an IPv4 and an IPv6 stable endpoint to use if link isn't currently alive.
  180. for(std::vector<World::Root>::const_iterator r(_world.roots().begin());r!=_world.roots().end();++r) {
  181. if (r->identity.address() == p->address()) {
  182. upstream = true;
  183. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)r->stableEndpoints.size();++k) {
  184. const InetAddress &addr = r->stableEndpoints[ptr++ % r->stableEndpoints.size()];
  185. if (!stableEndpoint4) {
  186. if (addr.ss_family == AF_INET)
  187. stableEndpoint4 = addr;
  188. }
  189. if (!stableEndpoint6) {
  190. if (addr.ss_family == AF_INET6)
  191. stableEndpoint6 = addr;
  192. }
  193. }
  194. break;
  195. }
  196. }
  197. if (!upstream) {
  198. // If I am a root server, only ping other root servers -- roots don't ping "down"
  199. // since that would just be a waste of bandwidth and could potentially cause route
  200. // flapping in Cluster mode.
  201. if (RR->topology->amRoot())
  202. return;
  203. // Check for network preferred relays, also considered 'upstream' and thus always
  204. // pinged to keep links up. If they have stable addresses we will try them there.
  205. for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(_relays.begin());r!=_relays.end();++r) {
  206. if (r->first == p->address()) {
  207. if (r->second.ss_family == AF_INET)
  208. stableEndpoint4 = r->second;
  209. else if (r->second.ss_family == AF_INET6)
  210. stableEndpoint6 = r->second;
  211. upstream = true;
  212. break;
  213. }
  214. }
  215. }
  216. if (upstream) {
  217. // "Upstream" devices are roots and relays and get special treatment -- they stay alive
  218. // forever and we try to keep (if available) both IPv4 and IPv6 channels open to them.
  219. bool needToContactIndirect = true;
  220. if (p->doPingAndKeepalive(_now,AF_INET)) {
  221. needToContactIndirect = false;
  222. } else {
  223. if (stableEndpoint4) {
  224. needToContactIndirect = false;
  225. p->sendHELLO(InetAddress(),stableEndpoint4,_now);
  226. }
  227. }
  228. if (p->doPingAndKeepalive(_now,AF_INET6)) {
  229. needToContactIndirect = false;
  230. } else {
  231. if (stableEndpoint6) {
  232. needToContactIndirect = false;
  233. p->sendHELLO(InetAddress(),stableEndpoint6,_now);
  234. }
  235. }
  236. if (needToContactIndirect) {
  237. // If this is an upstream and we have no stable endpoint for either IPv4 or IPv6,
  238. // send a NOP indirectly if possible to see if we can get to this peer in any
  239. // way whatsoever. This will e.g. find network preferred relays that lack
  240. // stable endpoints by using root servers.
  241. Packet outp(p->address(),RR->identity.address(),Packet::VERB_NOP);
  242. RR->sw->send(outp,true,0);
  243. }
  244. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  245. } else if (p->activelyTransferringFrames(_now)) {
  246. // Normal nodes get their preferred link kept alive if the node has generated frame traffic recently
  247. p->doPingAndKeepalive(_now,0);
  248. }
  249. }
  250. private:
  251. const RuntimeEnvironment *RR;
  252. uint64_t _now;
  253. const std::vector< std::pair<Address,InetAddress> > &_relays;
  254. World _world;
  255. };
  256. ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  257. {
  258. _now = now;
  259. Mutex::Lock bl(_backgroundTasksLock);
  260. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  261. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  262. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  263. try {
  264. _lastPingCheck = now;
  265. // Get relays and networks that need config without leaving the mutex locked
  266. std::vector< std::pair<Address,InetAddress> > networkRelays;
  267. std::vector< SharedPtr<Network> > needConfig;
  268. {
  269. Mutex::Lock _l(_networks_m);
  270. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  271. SharedPtr<NetworkConfig> nc(n->second->config2());
  272. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!nc))
  273. needConfig.push_back(n->second);
  274. if (nc)
  275. networkRelays.insert(networkRelays.end(),nc->relays().begin(),nc->relays().end());
  276. }
  277. }
  278. // Request updated configuration for networks that need it
  279. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  280. (*n)->requestConfiguration();
  281. // Do pings and keepalives
  282. _PingPeersThatNeedPing pfunc(RR,now,networkRelays);
  283. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  284. // Update online status, post status change as event
  285. const bool oldOnline = _online;
  286. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  287. if (oldOnline != _online)
  288. postEvent(_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  289. } catch ( ... ) {
  290. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  291. }
  292. } else {
  293. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  294. }
  295. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  296. try {
  297. _lastHousekeepingRun = now;
  298. RR->topology->clean(now);
  299. RR->sa->clean(now);
  300. RR->mc->clean(now);
  301. } catch ( ... ) {
  302. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  303. }
  304. }
  305. try {
  306. #ifdef ZT_ENABLE_CLUSTER
  307. // If clustering is enabled we have to call cluster->doPeriodicTasks() very often, so we override normal timer deadline behavior
  308. if (RR->cluster) {
  309. RR->sw->doTimerTasks(now);
  310. RR->cluster->doPeriodicTasks();
  311. *nextBackgroundTaskDeadline = now + ZT_CLUSTER_PERIODIC_TASK_PERIOD; // this is really short so just tick at this rate
  312. } else {
  313. #endif
  314. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  315. #ifdef ZT_ENABLE_CLUSTER
  316. }
  317. #endif
  318. } catch ( ... ) {
  319. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  320. }
  321. return ZT_RESULT_OK;
  322. }
  323. ZT_ResultCode Node::join(uint64_t nwid)
  324. {
  325. Mutex::Lock _l(_networks_m);
  326. SharedPtr<Network> nw = _network(nwid);
  327. if(!nw)
  328. _networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid))));
  329. std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
  330. return ZT_RESULT_OK;
  331. }
  332. ZT_ResultCode Node::leave(uint64_t nwid)
  333. {
  334. std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
  335. Mutex::Lock _l(_networks_m);
  336. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  337. if (n->first != nwid)
  338. newn.push_back(*n);
  339. else n->second->destroy();
  340. }
  341. _networks.swap(newn);
  342. return ZT_RESULT_OK;
  343. }
  344. ZT_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  345. {
  346. SharedPtr<Network> nw(this->network(nwid));
  347. if (nw) {
  348. nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  349. return ZT_RESULT_OK;
  350. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  351. }
  352. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  353. {
  354. SharedPtr<Network> nw(this->network(nwid));
  355. if (nw) {
  356. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  357. return ZT_RESULT_OK;
  358. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  359. }
  360. uint64_t Node::address() const
  361. {
  362. return RR->identity.address().toInt();
  363. }
  364. void Node::status(ZT_NodeStatus *status) const
  365. {
  366. status->address = RR->identity.address().toInt();
  367. status->worldId = RR->topology->worldId();
  368. status->worldTimestamp = RR->topology->worldTimestamp();
  369. status->publicIdentity = RR->publicIdentityStr.c_str();
  370. status->secretIdentity = RR->secretIdentityStr.c_str();
  371. status->online = _online ? 1 : 0;
  372. }
  373. ZT_PeerList *Node::peers() const
  374. {
  375. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  376. std::sort(peers.begin(),peers.end());
  377. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  378. if (!buf)
  379. return (ZT_PeerList *)0;
  380. ZT_PeerList *pl = (ZT_PeerList *)buf;
  381. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  382. pl->peerCount = 0;
  383. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  384. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  385. p->address = pi->second->address().toInt();
  386. p->lastUnicastFrame = pi->second->lastUnicastFrame();
  387. p->lastMulticastFrame = pi->second->lastMulticastFrame();
  388. if (pi->second->remoteVersionKnown()) {
  389. p->versionMajor = pi->second->remoteVersionMajor();
  390. p->versionMinor = pi->second->remoteVersionMinor();
  391. p->versionRev = pi->second->remoteVersionRevision();
  392. } else {
  393. p->versionMajor = -1;
  394. p->versionMinor = -1;
  395. p->versionRev = -1;
  396. }
  397. p->latency = pi->second->latency();
  398. p->role = RR->topology->isRoot(pi->second->identity()) ? ZT_PEER_ROLE_ROOT : ZT_PEER_ROLE_LEAF;
  399. std::vector<Path> paths(pi->second->paths());
  400. Path *bestPath = pi->second->getBestPath(_now);
  401. p->pathCount = 0;
  402. for(std::vector<Path>::iterator path(paths.begin());path!=paths.end();++path) {
  403. memcpy(&(p->paths[p->pathCount].address),&(path->address()),sizeof(struct sockaddr_storage));
  404. p->paths[p->pathCount].lastSend = path->lastSend();
  405. p->paths[p->pathCount].lastReceive = path->lastReceived();
  406. p->paths[p->pathCount].active = path->active(_now) ? 1 : 0;
  407. p->paths[p->pathCount].preferred = ((bestPath)&&(*path == *bestPath)) ? 1 : 0;
  408. ++p->pathCount;
  409. }
  410. }
  411. return pl;
  412. }
  413. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  414. {
  415. Mutex::Lock _l(_networks_m);
  416. SharedPtr<Network> nw = _network(nwid);
  417. if(nw) {
  418. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  419. nw->externalConfig(nc);
  420. return nc;
  421. }
  422. return (ZT_VirtualNetworkConfig *)0;
  423. }
  424. ZT_VirtualNetworkList *Node::networks() const
  425. {
  426. Mutex::Lock _l(_networks_m);
  427. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  428. if (!buf)
  429. return (ZT_VirtualNetworkList *)0;
  430. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  431. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  432. nl->networkCount = 0;
  433. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  434. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  435. return nl;
  436. }
  437. void Node::freeQueryResult(void *qr)
  438. {
  439. if (qr)
  440. ::free(qr);
  441. }
  442. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  443. {
  444. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  445. Mutex::Lock _l(_directPaths_m);
  446. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  447. std::sort(_directPaths.begin(),_directPaths.end());
  448. _directPaths.erase(std::unique(_directPaths.begin(),_directPaths.end()),_directPaths.end());
  449. return 1;
  450. }
  451. return 0;
  452. }
  453. void Node::clearLocalInterfaceAddresses()
  454. {
  455. Mutex::Lock _l(_directPaths_m);
  456. _directPaths.clear();
  457. }
  458. void Node::setNetconfMaster(void *networkControllerInstance)
  459. {
  460. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  461. }
  462. ZT_ResultCode Node::circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  463. {
  464. if (test->hopCount > 0) {
  465. try {
  466. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  467. RR->identity.address().appendTo(outp);
  468. outp.append((uint16_t)((test->reportAtEveryHop != 0) ? 0x03 : 0x02));
  469. outp.append((uint64_t)test->timestamp);
  470. outp.append((uint64_t)test->testId);
  471. outp.append((uint16_t)0); // originator credential length, updated later
  472. if (test->credentialNetworkId) {
  473. outp.append((uint8_t)0x01);
  474. outp.append((uint64_t)test->credentialNetworkId);
  475. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23,(uint16_t)9);
  476. }
  477. outp.append((uint16_t)0);
  478. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const char *>(outp.data()) + ZT_PACKET_IDX_PAYLOAD,outp.size() - ZT_PACKET_IDX_PAYLOAD));
  479. outp.append((uint16_t)sig.size());
  480. outp.append(sig.data,(unsigned int)sig.size());
  481. outp.append((uint16_t)0); // originator doesn't need an extra credential, since it's the originator
  482. for(unsigned int h=1;h<test->hopCount;++h) {
  483. outp.append((uint8_t)0);
  484. outp.append((uint8_t)(test->hops[h].breadth & 0xff));
  485. for(unsigned int a=0;a<test->hops[h].breadth;++a)
  486. Address(test->hops[h].addresses[a]).appendTo(outp);
  487. }
  488. for(unsigned int a=0;a<test->hops[0].breadth;++a) {
  489. outp.newInitializationVector();
  490. outp.setDestination(Address(test->hops[0].addresses[a]));
  491. RR->sw->send(outp,true,0);
  492. }
  493. } catch ( ... ) {
  494. return ZT_RESULT_FATAL_ERROR_INTERNAL; // probably indicates FIFO too big for packet
  495. }
  496. }
  497. {
  498. test->_internalPtr = reinterpret_cast<void *>(reportCallback);
  499. Mutex::Lock _l(_circuitTests_m);
  500. if (std::find(_circuitTests.begin(),_circuitTests.end(),test) == _circuitTests.end())
  501. _circuitTests.push_back(test);
  502. }
  503. return ZT_RESULT_OK;
  504. }
  505. void Node::circuitTestEnd(ZT_CircuitTest *test)
  506. {
  507. Mutex::Lock _l(_circuitTests_m);
  508. for(;;) {
  509. std::vector< ZT_CircuitTest * >::iterator ct(std::find(_circuitTests.begin(),_circuitTests.end(),test));
  510. if (ct == _circuitTests.end())
  511. break;
  512. else _circuitTests.erase(ct);
  513. }
  514. }
  515. ZT_ResultCode Node::clusterInit(
  516. unsigned int myId,
  517. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  518. unsigned int numZeroTierPhysicalEndpoints,
  519. int x,
  520. int y,
  521. int z,
  522. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  523. void *sendFunctionArg,
  524. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  525. void *addressToLocationFunctionArg)
  526. {
  527. #ifdef ZT_ENABLE_CLUSTER
  528. if (RR->cluster)
  529. return ZT_RESULT_ERROR_BAD_PARAMETER;
  530. std::vector<InetAddress> eps;
  531. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  532. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  533. std::sort(eps.begin(),eps.end());
  534. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  535. return ZT_RESULT_OK;
  536. #else
  537. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  538. #endif
  539. }
  540. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  541. {
  542. #ifdef ZT_ENABLE_CLUSTER
  543. if (!RR->cluster)
  544. return ZT_RESULT_ERROR_BAD_PARAMETER;
  545. RR->cluster->addMember((uint16_t)memberId);
  546. return ZT_RESULT_OK;
  547. #else
  548. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  549. #endif
  550. }
  551. void Node::clusterRemoveMember(unsigned int memberId)
  552. {
  553. #ifdef ZT_ENABLE_CLUSTER
  554. if (RR->cluster)
  555. RR->cluster->removeMember((uint16_t)memberId);
  556. #endif
  557. }
  558. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  559. {
  560. #ifdef ZT_ENABLE_CLUSTER
  561. if (RR->cluster)
  562. RR->cluster->handleIncomingStateMessage(msg,len);
  563. #endif
  564. }
  565. void Node::clusterStatus(ZT_ClusterStatus *cs)
  566. {
  567. if (!cs)
  568. return;
  569. #ifdef ZT_ENABLE_CLUSTER
  570. if (RR->cluster)
  571. RR->cluster->status(*cs);
  572. else
  573. #endif
  574. memset(cs,0,sizeof(ZT_ClusterStatus));
  575. }
  576. void Node::backgroundThreadMain()
  577. {
  578. ++RR->dpEnabled;
  579. for(;;) {
  580. try {
  581. if (RR->dp->process() < 0)
  582. break;
  583. } catch ( ... ) {} // sanity check -- should not throw
  584. }
  585. --RR->dpEnabled;
  586. }
  587. /****************************************************************************/
  588. /* Node methods used only within node/ */
  589. /****************************************************************************/
  590. std::string Node::dataStoreGet(const char *name)
  591. {
  592. char buf[1024];
  593. std::string r;
  594. unsigned long olen = 0;
  595. do {
  596. long n = _dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  597. if (n <= 0)
  598. return std::string();
  599. r.append(buf,n);
  600. } while (r.length() < olen);
  601. return r;
  602. }
  603. #ifdef ZT_TRACE
  604. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  605. {
  606. static Mutex traceLock;
  607. va_list ap;
  608. char tmp1[1024],tmp2[1024],tmp3[256];
  609. Mutex::Lock _l(traceLock);
  610. time_t now = (time_t)(_now / 1000ULL);
  611. #ifdef __WINDOWS__
  612. ctime_s(tmp3,sizeof(tmp3),&now);
  613. char *nowstr = tmp3;
  614. #else
  615. char *nowstr = ctime_r(&now,tmp3);
  616. #endif
  617. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  618. if (nowstr[nowstrlen-1] == '\n')
  619. nowstr[--nowstrlen] = (char)0;
  620. if (nowstr[nowstrlen-1] == '\r')
  621. nowstr[--nowstrlen] = (char)0;
  622. va_start(ap,fmt);
  623. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  624. va_end(ap);
  625. tmp2[sizeof(tmp2)-1] = (char)0;
  626. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  627. postEvent(ZT_EVENT_TRACE,tmp1);
  628. }
  629. #endif // ZT_TRACE
  630. uint64_t Node::prng()
  631. {
  632. unsigned int p = (++_prngStreamPtr % (sizeof(_prngStream) / sizeof(uint64_t)));
  633. if (!p)
  634. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  635. return _prngStream[p];
  636. }
  637. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  638. {
  639. std::vector< ZT_CircuitTest * > toNotify;
  640. {
  641. Mutex::Lock _l(_circuitTests_m);
  642. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  643. if ((*i)->testId == report->testId)
  644. toNotify.push_back(*i);
  645. }
  646. }
  647. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  648. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  649. }
  650. } // namespace ZeroTier
  651. /****************************************************************************/
  652. /* CAPI bindings */
  653. /****************************************************************************/
  654. extern "C" {
  655. enum ZT_ResultCode ZT_Node_new(
  656. ZT_Node **node,
  657. void *uptr,
  658. uint64_t now,
  659. ZT_DataStoreGetFunction dataStoreGetFunction,
  660. ZT_DataStorePutFunction dataStorePutFunction,
  661. ZT_WirePacketSendFunction wirePacketSendFunction,
  662. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  663. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  664. ZT_EventCallback eventCallback)
  665. {
  666. *node = (ZT_Node *)0;
  667. try {
  668. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,eventCallback));
  669. return ZT_RESULT_OK;
  670. } catch (std::bad_alloc &exc) {
  671. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  672. } catch (std::runtime_error &exc) {
  673. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  674. } catch ( ... ) {
  675. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  676. }
  677. }
  678. void ZT_Node_delete(ZT_Node *node)
  679. {
  680. try {
  681. delete (reinterpret_cast<ZeroTier::Node *>(node));
  682. } catch ( ... ) {}
  683. }
  684. enum ZT_ResultCode ZT_Node_processWirePacket(
  685. ZT_Node *node,
  686. uint64_t now,
  687. const struct sockaddr_storage *localAddress,
  688. const struct sockaddr_storage *remoteAddress,
  689. const void *packetData,
  690. unsigned int packetLength,
  691. volatile uint64_t *nextBackgroundTaskDeadline)
  692. {
  693. try {
  694. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  695. } catch (std::bad_alloc &exc) {
  696. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  697. } catch ( ... ) {
  698. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  699. }
  700. }
  701. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  702. ZT_Node *node,
  703. uint64_t now,
  704. uint64_t nwid,
  705. uint64_t sourceMac,
  706. uint64_t destMac,
  707. unsigned int etherType,
  708. unsigned int vlanId,
  709. const void *frameData,
  710. unsigned int frameLength,
  711. volatile uint64_t *nextBackgroundTaskDeadline)
  712. {
  713. try {
  714. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  715. } catch (std::bad_alloc &exc) {
  716. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  717. } catch ( ... ) {
  718. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  719. }
  720. }
  721. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  722. {
  723. try {
  724. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  725. } catch (std::bad_alloc &exc) {
  726. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  727. } catch ( ... ) {
  728. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  729. }
  730. }
  731. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid)
  732. {
  733. try {
  734. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid);
  735. } catch (std::bad_alloc &exc) {
  736. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  737. } catch ( ... ) {
  738. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  739. }
  740. }
  741. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid)
  742. {
  743. try {
  744. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid);
  745. } catch (std::bad_alloc &exc) {
  746. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  747. } catch ( ... ) {
  748. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  749. }
  750. }
  751. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  752. {
  753. try {
  754. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  755. } catch (std::bad_alloc &exc) {
  756. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  757. } catch ( ... ) {
  758. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  759. }
  760. }
  761. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  762. {
  763. try {
  764. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  765. } catch (std::bad_alloc &exc) {
  766. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  767. } catch ( ... ) {
  768. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  769. }
  770. }
  771. uint64_t ZT_Node_address(ZT_Node *node)
  772. {
  773. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  774. }
  775. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  776. {
  777. try {
  778. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  779. } catch ( ... ) {}
  780. }
  781. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  782. {
  783. try {
  784. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  785. } catch ( ... ) {
  786. return (ZT_PeerList *)0;
  787. }
  788. }
  789. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  790. {
  791. try {
  792. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  793. } catch ( ... ) {
  794. return (ZT_VirtualNetworkConfig *)0;
  795. }
  796. }
  797. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  798. {
  799. try {
  800. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  801. } catch ( ... ) {
  802. return (ZT_VirtualNetworkList *)0;
  803. }
  804. }
  805. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  806. {
  807. try {
  808. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  809. } catch ( ... ) {}
  810. }
  811. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  812. {
  813. try {
  814. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  815. } catch ( ... ) {
  816. return 0;
  817. }
  818. }
  819. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  820. {
  821. try {
  822. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  823. } catch ( ... ) {}
  824. }
  825. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  826. {
  827. try {
  828. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  829. } catch ( ... ) {}
  830. }
  831. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  832. {
  833. try {
  834. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(test,reportCallback);
  835. } catch ( ... ) {
  836. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  837. }
  838. }
  839. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  840. {
  841. try {
  842. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  843. } catch ( ... ) {}
  844. }
  845. enum ZT_ResultCode ZT_Node_clusterInit(
  846. ZT_Node *node,
  847. unsigned int myId,
  848. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  849. unsigned int numZeroTierPhysicalEndpoints,
  850. int x,
  851. int y,
  852. int z,
  853. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  854. void *sendFunctionArg,
  855. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  856. void *addressToLocationFunctionArg)
  857. {
  858. try {
  859. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  860. } catch ( ... ) {
  861. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  862. }
  863. }
  864. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  865. {
  866. try {
  867. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  868. } catch ( ... ) {
  869. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  870. }
  871. }
  872. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  873. {
  874. try {
  875. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  876. } catch ( ... ) {}
  877. }
  878. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  879. {
  880. try {
  881. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  882. } catch ( ... ) {}
  883. }
  884. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  885. {
  886. try {
  887. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  888. } catch ( ... ) {}
  889. }
  890. void ZT_Node_backgroundThreadMain(ZT_Node *node)
  891. {
  892. try {
  893. reinterpret_cast<ZeroTier::Node *>(node)->backgroundThreadMain();
  894. } catch ( ... ) {}
  895. }
  896. void ZT_version(int *major,int *minor,int *revision,unsigned long *featureFlags)
  897. {
  898. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  899. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  900. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  901. if (featureFlags) {
  902. *featureFlags = (
  903. ZT_FEATURE_FLAG_THREAD_SAFE
  904. );
  905. }
  906. }
  907. } // extern "C"