Node.cpp 31 KB

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