Node.cpp 31 KB

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