Node.cpp 31 KB

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