Node.cpp 32 KB

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