Node.cpp 32 KB

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