Node.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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,-1);
  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< SharedPtr<Path> > paths(pi->second->paths());
  375. SharedPtr<Path> bestp(pi->second->getBestPath(_now));
  376. p->pathCount = 0;
  377. for(std::vector< SharedPtr<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)->lastOut();
  380. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  381. p->paths[p->pathCount].preferred = (*path == bestp) ? 1 : 0;
  382. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  383. ++p->pathCount;
  384. }
  385. }
  386. return pl;
  387. }
  388. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  389. {
  390. Mutex::Lock _l(_networks_m);
  391. SharedPtr<Network> nw = _network(nwid);
  392. if(nw) {
  393. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  394. nw->externalConfig(nc);
  395. return nc;
  396. }
  397. return (ZT_VirtualNetworkConfig *)0;
  398. }
  399. ZT_VirtualNetworkList *Node::networks() const
  400. {
  401. Mutex::Lock _l(_networks_m);
  402. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  403. if (!buf)
  404. return (ZT_VirtualNetworkList *)0;
  405. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  406. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  407. nl->networkCount = 0;
  408. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  409. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  410. return nl;
  411. }
  412. void Node::freeQueryResult(void *qr)
  413. {
  414. if (qr)
  415. ::free(qr);
  416. }
  417. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  418. {
  419. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  420. Mutex::Lock _l(_directPaths_m);
  421. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  422. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  423. return 1;
  424. }
  425. }
  426. return 0;
  427. }
  428. void Node::clearLocalInterfaceAddresses()
  429. {
  430. Mutex::Lock _l(_directPaths_m);
  431. _directPaths.clear();
  432. }
  433. void Node::setNetconfMaster(void *networkControllerInstance)
  434. {
  435. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  436. }
  437. ZT_ResultCode Node::circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  438. {
  439. if (test->hopCount > 0) {
  440. try {
  441. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  442. RR->identity.address().appendTo(outp);
  443. outp.append((uint16_t)((test->reportAtEveryHop != 0) ? 0x03 : 0x02));
  444. outp.append((uint64_t)test->timestamp);
  445. outp.append((uint64_t)test->testId);
  446. outp.append((uint16_t)0); // originator credential length, updated later
  447. if (test->credentialNetworkId) {
  448. outp.append((uint8_t)0x01);
  449. outp.append((uint64_t)test->credentialNetworkId);
  450. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23,(uint16_t)9);
  451. }
  452. outp.append((uint16_t)0);
  453. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const char *>(outp.data()) + ZT_PACKET_IDX_PAYLOAD,outp.size() - ZT_PACKET_IDX_PAYLOAD));
  454. outp.append((uint16_t)sig.size());
  455. outp.append(sig.data,(unsigned int)sig.size());
  456. outp.append((uint16_t)0); // originator doesn't need an extra credential, since it's the originator
  457. for(unsigned int h=1;h<test->hopCount;++h) {
  458. outp.append((uint8_t)0);
  459. outp.append((uint8_t)(test->hops[h].breadth & 0xff));
  460. for(unsigned int a=0;a<test->hops[h].breadth;++a)
  461. Address(test->hops[h].addresses[a]).appendTo(outp);
  462. }
  463. for(unsigned int a=0;a<test->hops[0].breadth;++a) {
  464. outp.newInitializationVector();
  465. outp.setDestination(Address(test->hops[0].addresses[a]));
  466. RR->sw->send(outp,true);
  467. }
  468. } catch ( ... ) {
  469. return ZT_RESULT_FATAL_ERROR_INTERNAL; // probably indicates FIFO too big for packet
  470. }
  471. }
  472. {
  473. test->_internalPtr = reinterpret_cast<void *>(reportCallback);
  474. Mutex::Lock _l(_circuitTests_m);
  475. if (std::find(_circuitTests.begin(),_circuitTests.end(),test) == _circuitTests.end())
  476. _circuitTests.push_back(test);
  477. }
  478. return ZT_RESULT_OK;
  479. }
  480. void Node::circuitTestEnd(ZT_CircuitTest *test)
  481. {
  482. Mutex::Lock _l(_circuitTests_m);
  483. for(;;) {
  484. std::vector< ZT_CircuitTest * >::iterator ct(std::find(_circuitTests.begin(),_circuitTests.end(),test));
  485. if (ct == _circuitTests.end())
  486. break;
  487. else _circuitTests.erase(ct);
  488. }
  489. }
  490. void Node::pushNetworkRefresh(uint64_t dest,uint64_t nwid,const uint64_t *blacklistAddresses,const uint64_t *blacklistBeforeTimestamps,unsigned int blacklistCount)
  491. {
  492. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  493. outp.append(nwid);
  494. outp.addSize(2);
  495. unsigned int c = 0;
  496. for(unsigned int i=0;i<blacklistCount;++i) {
  497. if ((outp.size() + 13) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  498. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 8,(uint16_t)c);
  499. RR->sw->send(outp,true);
  500. outp = Packet(Address(dest),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REFRESH);
  501. outp.append(nwid);
  502. outp.addSize(2);
  503. c = 0;
  504. }
  505. Address(blacklistAddresses[i]).appendTo(outp);
  506. outp.append(blacklistBeforeTimestamps[i]);
  507. ++c;
  508. }
  509. if (c > 0) {
  510. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 8,(uint16_t)c);
  511. RR->sw->send(outp,true);
  512. }
  513. }
  514. ZT_ResultCode Node::clusterInit(
  515. unsigned int myId,
  516. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  517. unsigned int numZeroTierPhysicalEndpoints,
  518. int x,
  519. int y,
  520. int z,
  521. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  522. void *sendFunctionArg,
  523. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  524. void *addressToLocationFunctionArg)
  525. {
  526. #ifdef ZT_ENABLE_CLUSTER
  527. if (RR->cluster)
  528. return ZT_RESULT_ERROR_BAD_PARAMETER;
  529. std::vector<InetAddress> eps;
  530. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  531. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  532. std::sort(eps.begin(),eps.end());
  533. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  534. return ZT_RESULT_OK;
  535. #else
  536. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  537. #endif
  538. }
  539. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  540. {
  541. #ifdef ZT_ENABLE_CLUSTER
  542. if (!RR->cluster)
  543. return ZT_RESULT_ERROR_BAD_PARAMETER;
  544. RR->cluster->addMember((uint16_t)memberId);
  545. return ZT_RESULT_OK;
  546. #else
  547. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  548. #endif
  549. }
  550. void Node::clusterRemoveMember(unsigned int memberId)
  551. {
  552. #ifdef ZT_ENABLE_CLUSTER
  553. if (RR->cluster)
  554. RR->cluster->removeMember((uint16_t)memberId);
  555. #endif
  556. }
  557. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  558. {
  559. #ifdef ZT_ENABLE_CLUSTER
  560. if (RR->cluster)
  561. RR->cluster->handleIncomingStateMessage(msg,len);
  562. #endif
  563. }
  564. void Node::clusterStatus(ZT_ClusterStatus *cs)
  565. {
  566. if (!cs)
  567. return;
  568. #ifdef ZT_ENABLE_CLUSTER
  569. if (RR->cluster)
  570. RR->cluster->status(*cs);
  571. else
  572. #endif
  573. memset(cs,0,sizeof(ZT_ClusterStatus));
  574. }
  575. /****************************************************************************/
  576. /* Node methods used only within node/ */
  577. /****************************************************************************/
  578. std::string Node::dataStoreGet(const char *name)
  579. {
  580. char buf[1024];
  581. std::string r;
  582. unsigned long olen = 0;
  583. do {
  584. long n = _dataStoreGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  585. if (n <= 0)
  586. return std::string();
  587. r.append(buf,n);
  588. } while (r.length() < olen);
  589. return r;
  590. }
  591. bool Node::shouldUsePathForZeroTierTraffic(const InetAddress &localAddress,const InetAddress &remoteAddress)
  592. {
  593. if (!Path::isAddressValidForPath(remoteAddress))
  594. return false;
  595. {
  596. Mutex::Lock _l(_networks_m);
  597. for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
  598. if (i->second->hasConfig()) {
  599. for(unsigned int k=0;k<i->second->config().staticIpCount;++k) {
  600. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  601. return false;
  602. }
  603. }
  604. }
  605. }
  606. if (_pathCheckFunction)
  607. return (_pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,reinterpret_cast<const struct sockaddr_storage *>(&localAddress),reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  608. else return true;
  609. }
  610. #ifdef ZT_TRACE
  611. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  612. {
  613. static Mutex traceLock;
  614. va_list ap;
  615. char tmp1[1024],tmp2[1024],tmp3[256];
  616. Mutex::Lock _l(traceLock);
  617. time_t now = (time_t)(_now / 1000ULL);
  618. #ifdef __WINDOWS__
  619. ctime_s(tmp3,sizeof(tmp3),&now);
  620. char *nowstr = tmp3;
  621. #else
  622. char *nowstr = ctime_r(&now,tmp3);
  623. #endif
  624. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  625. if (nowstr[nowstrlen-1] == '\n')
  626. nowstr[--nowstrlen] = (char)0;
  627. if (nowstr[nowstrlen-1] == '\r')
  628. nowstr[--nowstrlen] = (char)0;
  629. va_start(ap,fmt);
  630. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  631. va_end(ap);
  632. tmp2[sizeof(tmp2)-1] = (char)0;
  633. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  634. postEvent(ZT_EVENT_TRACE,tmp1);
  635. }
  636. #endif // ZT_TRACE
  637. uint64_t Node::prng()
  638. {
  639. unsigned int p = (++_prngStreamPtr % (sizeof(_prngStream) / sizeof(uint64_t)));
  640. if (!p)
  641. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  642. return _prngStream[p];
  643. }
  644. void Node::postCircuitTestReport(const ZT_CircuitTestReport *report)
  645. {
  646. std::vector< ZT_CircuitTest * > toNotify;
  647. {
  648. Mutex::Lock _l(_circuitTests_m);
  649. for(std::vector< ZT_CircuitTest * >::iterator i(_circuitTests.begin());i!=_circuitTests.end();++i) {
  650. if ((*i)->testId == report->testId)
  651. toNotify.push_back(*i);
  652. }
  653. }
  654. for(std::vector< ZT_CircuitTest * >::iterator i(toNotify.begin());i!=toNotify.end();++i)
  655. (reinterpret_cast<void (*)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *)>((*i)->_internalPtr))(reinterpret_cast<ZT_Node *>(this),*i,report);
  656. }
  657. void Node::setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  658. {
  659. RR->topology->setTrustedPaths(reinterpret_cast<const InetAddress *>(networks),ids,count);
  660. }
  661. } // namespace ZeroTier
  662. /****************************************************************************/
  663. /* CAPI bindings */
  664. /****************************************************************************/
  665. extern "C" {
  666. enum ZT_ResultCode ZT_Node_new(
  667. ZT_Node **node,
  668. void *uptr,
  669. uint64_t now,
  670. ZT_DataStoreGetFunction dataStoreGetFunction,
  671. ZT_DataStorePutFunction dataStorePutFunction,
  672. ZT_WirePacketSendFunction wirePacketSendFunction,
  673. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  674. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  675. ZT_PathCheckFunction pathCheckFunction,
  676. ZT_EventCallback eventCallback)
  677. {
  678. *node = (ZT_Node *)0;
  679. try {
  680. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,pathCheckFunction,eventCallback));
  681. return ZT_RESULT_OK;
  682. } catch (std::bad_alloc &exc) {
  683. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  684. } catch (std::runtime_error &exc) {
  685. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  686. } catch ( ... ) {
  687. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  688. }
  689. }
  690. void ZT_Node_delete(ZT_Node *node)
  691. {
  692. try {
  693. delete (reinterpret_cast<ZeroTier::Node *>(node));
  694. } catch ( ... ) {}
  695. }
  696. enum ZT_ResultCode ZT_Node_processWirePacket(
  697. ZT_Node *node,
  698. uint64_t now,
  699. const struct sockaddr_storage *localAddress,
  700. const struct sockaddr_storage *remoteAddress,
  701. const void *packetData,
  702. unsigned int packetLength,
  703. volatile uint64_t *nextBackgroundTaskDeadline)
  704. {
  705. try {
  706. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  707. } catch (std::bad_alloc &exc) {
  708. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  709. } catch ( ... ) {
  710. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  711. }
  712. }
  713. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  714. ZT_Node *node,
  715. uint64_t now,
  716. uint64_t nwid,
  717. uint64_t sourceMac,
  718. uint64_t destMac,
  719. unsigned int etherType,
  720. unsigned int vlanId,
  721. const void *frameData,
  722. unsigned int frameLength,
  723. volatile uint64_t *nextBackgroundTaskDeadline)
  724. {
  725. try {
  726. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  727. } catch (std::bad_alloc &exc) {
  728. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  729. } catch ( ... ) {
  730. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  731. }
  732. }
  733. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  734. {
  735. try {
  736. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  737. } catch (std::bad_alloc &exc) {
  738. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  739. } catch ( ... ) {
  740. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  741. }
  742. }
  743. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr)
  744. {
  745. try {
  746. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr);
  747. } catch (std::bad_alloc &exc) {
  748. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  749. } catch ( ... ) {
  750. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  751. }
  752. }
  753. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr)
  754. {
  755. try {
  756. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr);
  757. } catch (std::bad_alloc &exc) {
  758. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  759. } catch ( ... ) {
  760. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  761. }
  762. }
  763. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  764. {
  765. try {
  766. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  767. } catch (std::bad_alloc &exc) {
  768. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  769. } catch ( ... ) {
  770. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  771. }
  772. }
  773. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  774. {
  775. try {
  776. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  777. } catch (std::bad_alloc &exc) {
  778. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  779. } catch ( ... ) {
  780. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  781. }
  782. }
  783. uint64_t ZT_Node_address(ZT_Node *node)
  784. {
  785. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  786. }
  787. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  788. {
  789. try {
  790. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  791. } catch ( ... ) {}
  792. }
  793. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  794. {
  795. try {
  796. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  797. } catch ( ... ) {
  798. return (ZT_PeerList *)0;
  799. }
  800. }
  801. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  802. {
  803. try {
  804. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  805. } catch ( ... ) {
  806. return (ZT_VirtualNetworkConfig *)0;
  807. }
  808. }
  809. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  810. {
  811. try {
  812. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  813. } catch ( ... ) {
  814. return (ZT_VirtualNetworkList *)0;
  815. }
  816. }
  817. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  818. {
  819. try {
  820. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  821. } catch ( ... ) {}
  822. }
  823. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  824. {
  825. try {
  826. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  827. } catch ( ... ) {
  828. return 0;
  829. }
  830. }
  831. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  832. {
  833. try {
  834. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  835. } catch ( ... ) {}
  836. }
  837. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  838. {
  839. try {
  840. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  841. } catch ( ... ) {}
  842. }
  843. enum ZT_ResultCode ZT_Node_circuitTestBegin(ZT_Node *node,ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  844. {
  845. try {
  846. return reinterpret_cast<ZeroTier::Node *>(node)->circuitTestBegin(test,reportCallback);
  847. } catch ( ... ) {
  848. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  849. }
  850. }
  851. void ZT_Node_circuitTestEnd(ZT_Node *node,ZT_CircuitTest *test)
  852. {
  853. try {
  854. reinterpret_cast<ZeroTier::Node *>(node)->circuitTestEnd(test);
  855. } catch ( ... ) {}
  856. }
  857. void ZT_Node_pushNetworkRefresh(ZT_Node *node,uint64_t dest,uint64_t nwid,const uint64_t *blacklistAddresses,const uint64_t *blacklistBeforeTimestamps,unsigned int blacklistCount)
  858. {
  859. try {
  860. reinterpret_cast<ZeroTier::Node *>(node)->pushNetworkRefresh(dest,nwid,blacklistAddresses,blacklistBeforeTimestamps,blacklistCount);
  861. } catch ( ... ) {}
  862. }
  863. enum ZT_ResultCode ZT_Node_clusterInit(
  864. ZT_Node *node,
  865. unsigned int myId,
  866. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  867. unsigned int numZeroTierPhysicalEndpoints,
  868. int x,
  869. int y,
  870. int z,
  871. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  872. void *sendFunctionArg,
  873. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  874. void *addressToLocationFunctionArg)
  875. {
  876. try {
  877. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  878. } catch ( ... ) {
  879. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  880. }
  881. }
  882. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  883. {
  884. try {
  885. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  886. } catch ( ... ) {
  887. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  888. }
  889. }
  890. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  891. {
  892. try {
  893. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  894. } catch ( ... ) {}
  895. }
  896. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  897. {
  898. try {
  899. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  900. } catch ( ... ) {}
  901. }
  902. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  903. {
  904. try {
  905. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  906. } catch ( ... ) {}
  907. }
  908. void ZT_Node_setTrustedPaths(ZT_Node *node,const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  909. {
  910. try {
  911. reinterpret_cast<ZeroTier::Node *>(node)->setTrustedPaths(networks,ids,count);
  912. } catch ( ... ) {}
  913. }
  914. void ZT_version(int *major,int *minor,int *revision)
  915. {
  916. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  917. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  918. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  919. }
  920. } // extern "C"