Node.cpp 31 KB

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