Node.cpp 32 KB

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