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. #include "DeferredPackets.hpp"
  38. const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
  39. namespace ZeroTier {
  40. /****************************************************************************/
  41. /* Public Node interface (C++, exposed via CAPI bindings) */
  42. /****************************************************************************/
  43. Node::Node(
  44. uint64_t now,
  45. void *uptr,
  46. ZT_DataStoreGetFunction dataStoreGetFunction,
  47. ZT_DataStorePutFunction dataStorePutFunction,
  48. ZT_WirePacketSendFunction wirePacketSendFunction,
  49. ZT_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  50. ZT_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  51. ZT_PathCheckFunction pathCheckFunction,
  52. ZT_EventCallback eventCallback) :
  53. _RR(this),
  54. RR(&_RR),
  55. _uPtr(uptr),
  56. _dataStoreGetFunction(dataStoreGetFunction),
  57. _dataStorePutFunction(dataStorePutFunction),
  58. _wirePacketSendFunction(wirePacketSendFunction),
  59. _virtualNetworkFrameFunction(virtualNetworkFrameFunction),
  60. _virtualNetworkConfigFunction(virtualNetworkConfigFunction),
  61. _pathCheckFunction(pathCheckFunction),
  62. _eventCallback(eventCallback),
  63. _networks(),
  64. _networks_m(),
  65. _prngStreamPtr(0),
  66. _now(now),
  67. _lastPingCheck(0),
  68. _lastHousekeepingRun(0)
  69. {
  70. _online = false;
  71. // Use Salsa20 alone as a high-quality non-crypto PRNG
  72. {
  73. char foo[32];
  74. Utils::getSecureRandom(foo,32);
  75. _prng.init(foo,256,foo);
  76. memset(_prngStream,0,sizeof(_prngStream));
  77. _prng.encrypt12(_prngStream,_prngStream,sizeof(_prngStream));
  78. }
  79. {
  80. std::string idtmp(dataStoreGet("identity.secret"));
  81. if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
  82. TRACE("identity.secret not found, generating...");
  83. RR->identity.generate();
  84. idtmp = RR->identity.toString(true);
  85. if (!dataStorePut("identity.secret",idtmp,true))
  86. throw std::runtime_error("unable to write identity.secret");
  87. }
  88. RR->publicIdentityStr = RR->identity.toString(false);
  89. RR->secretIdentityStr = RR->identity.toString(true);
  90. idtmp = dataStoreGet("identity.public");
  91. if (idtmp != RR->publicIdentityStr) {
  92. if (!dataStorePut("identity.public",RR->publicIdentityStr,false))
  93. throw std::runtime_error("unable to write identity.public");
  94. }
  95. }
  96. try {
  97. RR->sw = new Switch(RR);
  98. RR->mc = new Multicaster(RR);
  99. RR->topology = new Topology(RR);
  100. RR->sa = new SelfAwareness(RR);
  101. RR->dp = new DeferredPackets(RR);
  102. } catch ( ... ) {
  103. delete RR->dp;
  104. delete RR->sa;
  105. delete RR->topology;
  106. delete RR->mc;
  107. delete RR->sw;
  108. throw;
  109. }
  110. postEvent(ZT_EVENT_UP);
  111. }
  112. Node::~Node()
  113. {
  114. Mutex::Lock _l(_networks_m);
  115. _networks.clear(); // ensure that networks are destroyed before shutdow
  116. RR->dpEnabled = 0;
  117. delete RR->dp;
  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. // If I am a root server, only ping other root servers -- roots don't ping "down"
  191. // since that would just be a waste of bandwidth and could potentially cause route
  192. // flapping in Cluster mode.
  193. if (RR->topology->amRoot())
  194. return;
  195. }
  196. if (upstream) {
  197. // "Upstream" devices are roots and relays and get special treatment -- they stay alive
  198. // forever and we try to keep (if available) both IPv4 and IPv6 channels open to them.
  199. bool needToContactIndirect = true;
  200. if (p->doPingAndKeepalive(_now,AF_INET)) {
  201. needToContactIndirect = false;
  202. } else {
  203. if (stableEndpoint4) {
  204. needToContactIndirect = false;
  205. p->sendHELLO(InetAddress(),stableEndpoint4,_now);
  206. }
  207. }
  208. if (p->doPingAndKeepalive(_now,AF_INET6)) {
  209. needToContactIndirect = false;
  210. } else {
  211. if (stableEndpoint6) {
  212. needToContactIndirect = false;
  213. p->sendHELLO(InetAddress(),stableEndpoint6,_now);
  214. }
  215. }
  216. if (needToContactIndirect) {
  217. // If this is an upstream and we have no stable endpoint for either IPv4 or IPv6,
  218. // send a NOP indirectly if possible to see if we can get to this peer in any
  219. // way whatsoever. This will e.g. find network preferred relays that lack
  220. // stable endpoints by using root servers.
  221. Packet outp(p->address(),RR->identity.address(),Packet::VERB_NOP);
  222. RR->sw->send(outp,true,0);
  223. }
  224. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  225. } else if (p->activelyTransferringFrames(_now)) {
  226. // Normal nodes get their preferred link kept alive if the node has generated frame traffic recently
  227. p->doPingAndKeepalive(_now,0);
  228. }
  229. }
  230. private:
  231. const RuntimeEnvironment *RR;
  232. uint64_t _now;
  233. World _world;
  234. };
  235. ZT_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  236. {
  237. _now = now;
  238. Mutex::Lock bl(_backgroundTasksLock);
  239. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  240. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  241. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  242. try {
  243. _lastPingCheck = now;
  244. // Get relays and networks that need config without leaving the mutex locked
  245. std::vector< SharedPtr<Network> > needConfig;
  246. {
  247. Mutex::Lock _l(_networks_m);
  248. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  249. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!n->second->hasConfig())) {
  250. needConfig.push_back(n->second);
  251. }
  252. }
  253. }
  254. // Request updated configuration for networks that need it
  255. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  256. (*n)->requestConfiguration();
  257. // Do pings and keepalives
  258. _PingPeersThatNeedPing pfunc(RR,now);
  259. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  260. // Update online status, post status change as event
  261. const bool oldOnline = _online;
  262. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  263. if (oldOnline != _online)
  264. postEvent(_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  265. } catch ( ... ) {
  266. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  267. }
  268. } else {
  269. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  270. }
  271. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  272. try {
  273. _lastHousekeepingRun = now;
  274. RR->topology->clean(now);
  275. RR->sa->clean(now);
  276. RR->mc->clean(now);
  277. } catch ( ... ) {
  278. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  279. }
  280. }
  281. try {
  282. #ifdef ZT_ENABLE_CLUSTER
  283. // If clustering is enabled we have to call cluster->doPeriodicTasks() very often, so we override normal timer deadline behavior
  284. if (RR->cluster) {
  285. RR->sw->doTimerTasks(now);
  286. RR->cluster->doPeriodicTasks();
  287. *nextBackgroundTaskDeadline = now + ZT_CLUSTER_PERIODIC_TASK_PERIOD; // this is really short so just tick at this rate
  288. } else {
  289. #endif
  290. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  291. #ifdef ZT_ENABLE_CLUSTER
  292. }
  293. #endif
  294. } catch ( ... ) {
  295. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  296. }
  297. return ZT_RESULT_OK;
  298. }
  299. ZT_ResultCode Node::join(uint64_t nwid,void *uptr)
  300. {
  301. Mutex::Lock _l(_networks_m);
  302. SharedPtr<Network> nw = _network(nwid);
  303. if(!nw)
  304. _networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid,uptr))));
  305. std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
  306. return ZT_RESULT_OK;
  307. }
  308. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr)
  309. {
  310. std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
  311. Mutex::Lock _l(_networks_m);
  312. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  313. if (n->first != nwid)
  314. newn.push_back(*n);
  315. else {
  316. if (uptr)
  317. *uptr = n->second->userPtr();
  318. n->second->destroy();
  319. }
  320. }
  321. _networks.swap(newn);
  322. return ZT_RESULT_OK;
  323. }
  324. ZT_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  325. {
  326. SharedPtr<Network> nw(this->network(nwid));
  327. if (nw) {
  328. nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  329. return ZT_RESULT_OK;
  330. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  331. }
  332. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  333. {
  334. SharedPtr<Network> nw(this->network(nwid));
  335. if (nw) {
  336. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  337. return ZT_RESULT_OK;
  338. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  339. }
  340. uint64_t Node::address() const
  341. {
  342. return RR->identity.address().toInt();
  343. }
  344. void Node::status(ZT_NodeStatus *status) const
  345. {
  346. status->address = RR->identity.address().toInt();
  347. status->worldId = RR->topology->worldId();
  348. status->worldTimestamp = RR->topology->worldTimestamp();
  349. status->publicIdentity = RR->publicIdentityStr.c_str();
  350. status->secretIdentity = RR->secretIdentityStr.c_str();
  351. status->online = _online ? 1 : 0;
  352. }
  353. ZT_PeerList *Node::peers() const
  354. {
  355. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  356. std::sort(peers.begin(),peers.end());
  357. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  358. if (!buf)
  359. return (ZT_PeerList *)0;
  360. ZT_PeerList *pl = (ZT_PeerList *)buf;
  361. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  362. pl->peerCount = 0;
  363. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  364. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  365. p->address = pi->second->address().toInt();
  366. p->lastUnicastFrame = pi->second->lastUnicastFrame();
  367. p->lastMulticastFrame = pi->second->lastMulticastFrame();
  368. if (pi->second->remoteVersionKnown()) {
  369. p->versionMajor = pi->second->remoteVersionMajor();
  370. p->versionMinor = pi->second->remoteVersionMinor();
  371. p->versionRev = pi->second->remoteVersionRevision();
  372. } else {
  373. p->versionMajor = -1;
  374. p->versionMinor = -1;
  375. p->versionRev = -1;
  376. }
  377. p->latency = pi->second->latency();
  378. p->role = RR->topology->isRoot(pi->second->identity()) ? ZT_PEER_ROLE_ROOT : ZT_PEER_ROLE_LEAF;
  379. std::vector<Path> paths(pi->second->paths());
  380. Path *bestPath = pi->second->getBestPath(_now);
  381. p->pathCount = 0;
  382. for(std::vector<Path>::iterator path(paths.begin());path!=paths.end();++path) {
  383. memcpy(&(p->paths[p->pathCount].address),&(path->address()),sizeof(struct sockaddr_storage));
  384. p->paths[p->pathCount].lastSend = path->lastSend();
  385. p->paths[p->pathCount].lastReceive = path->lastReceived();
  386. p->paths[p->pathCount].active = path->active(_now) ? 1 : 0;
  387. p->paths[p->pathCount].preferred = ((bestPath)&&(*path == *bestPath)) ? 1 : 0;
  388. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust(path->address());
  389. ++p->pathCount;
  390. }
  391. }
  392. return pl;
  393. }
  394. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  395. {
  396. Mutex::Lock _l(_networks_m);
  397. SharedPtr<Network> nw = _network(nwid);
  398. if(nw) {
  399. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  400. nw->externalConfig(nc);
  401. return nc;
  402. }
  403. return (ZT_VirtualNetworkConfig *)0;
  404. }
  405. ZT_VirtualNetworkList *Node::networks() const
  406. {
  407. Mutex::Lock _l(_networks_m);
  408. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  409. if (!buf)
  410. return (ZT_VirtualNetworkList *)0;
  411. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  412. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  413. nl->networkCount = 0;
  414. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  415. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  416. return nl;
  417. }
  418. void Node::freeQueryResult(void *qr)
  419. {
  420. if (qr)
  421. ::free(qr);
  422. }
  423. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  424. {
  425. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  426. Mutex::Lock _l(_directPaths_m);
  427. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  428. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  429. return 1;
  430. }
  431. }
  432. return 0;
  433. }
  434. void Node::clearLocalInterfaceAddresses()
  435. {
  436. Mutex::Lock _l(_directPaths_m);
  437. _directPaths.clear();
  438. }
  439. void Node::setNetconfMaster(void *networkControllerInstance)
  440. {
  441. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  442. }
  443. ZT_ResultCode Node::circuitTestBegin(ZT_CircuitTest *test,void (*reportCallback)(ZT_Node *,ZT_CircuitTest *,const ZT_CircuitTestReport *))
  444. {
  445. if (test->hopCount > 0) {
  446. try {
  447. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  448. RR->identity.address().appendTo(outp);
  449. outp.append((uint16_t)((test->reportAtEveryHop != 0) ? 0x03 : 0x02));
  450. outp.append((uint64_t)test->timestamp);
  451. outp.append((uint64_t)test->testId);
  452. outp.append((uint16_t)0); // originator credential length, updated later
  453. if (test->credentialNetworkId) {
  454. outp.append((uint8_t)0x01);
  455. outp.append((uint64_t)test->credentialNetworkId);
  456. outp.setAt<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23,(uint16_t)9);
  457. }
  458. outp.append((uint16_t)0);
  459. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const char *>(outp.data()) + ZT_PACKET_IDX_PAYLOAD,outp.size() - ZT_PACKET_IDX_PAYLOAD));
  460. outp.append((uint16_t)sig.size());
  461. outp.append(sig.data,(unsigned int)sig.size());
  462. outp.append((uint16_t)0); // originator doesn't need an extra credential, since it's the originator
  463. for(unsigned int h=1;h<test->hopCount;++h) {
  464. outp.append((uint8_t)0);
  465. outp.append((uint8_t)(test->hops[h].breadth & 0xff));
  466. for(unsigned int a=0;a<test->hops[h].breadth;++a)
  467. Address(test->hops[h].addresses[a]).appendTo(outp);
  468. }
  469. for(unsigned int a=0;a<test->hops[0].breadth;++a) {
  470. outp.newInitializationVector();
  471. outp.setDestination(Address(test->hops[0].addresses[a]));
  472. RR->sw->send(outp,true,0);
  473. }
  474. } catch ( ... ) {
  475. return ZT_RESULT_FATAL_ERROR_INTERNAL; // probably indicates FIFO too big for packet
  476. }
  477. }
  478. {
  479. test->_internalPtr = reinterpret_cast<void *>(reportCallback);
  480. Mutex::Lock _l(_circuitTests_m);
  481. if (std::find(_circuitTests.begin(),_circuitTests.end(),test) == _circuitTests.end())
  482. _circuitTests.push_back(test);
  483. }
  484. return ZT_RESULT_OK;
  485. }
  486. void Node::circuitTestEnd(ZT_CircuitTest *test)
  487. {
  488. Mutex::Lock _l(_circuitTests_m);
  489. for(;;) {
  490. std::vector< ZT_CircuitTest * >::iterator ct(std::find(_circuitTests.begin(),_circuitTests.end(),test));
  491. if (ct == _circuitTests.end())
  492. break;
  493. else _circuitTests.erase(ct);
  494. }
  495. }
  496. ZT_ResultCode Node::clusterInit(
  497. unsigned int myId,
  498. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  499. unsigned int numZeroTierPhysicalEndpoints,
  500. int x,
  501. int y,
  502. int z,
  503. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  504. void *sendFunctionArg,
  505. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  506. void *addressToLocationFunctionArg)
  507. {
  508. #ifdef ZT_ENABLE_CLUSTER
  509. if (RR->cluster)
  510. return ZT_RESULT_ERROR_BAD_PARAMETER;
  511. std::vector<InetAddress> eps;
  512. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  513. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  514. std::sort(eps.begin(),eps.end());
  515. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  516. return ZT_RESULT_OK;
  517. #else
  518. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  519. #endif
  520. }
  521. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  522. {
  523. #ifdef ZT_ENABLE_CLUSTER
  524. if (!RR->cluster)
  525. return ZT_RESULT_ERROR_BAD_PARAMETER;
  526. RR->cluster->addMember((uint16_t)memberId);
  527. return ZT_RESULT_OK;
  528. #else
  529. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  530. #endif
  531. }
  532. void Node::clusterRemoveMember(unsigned int memberId)
  533. {
  534. #ifdef ZT_ENABLE_CLUSTER
  535. if (RR->cluster)
  536. RR->cluster->removeMember((uint16_t)memberId);
  537. #endif
  538. }
  539. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  540. {
  541. #ifdef ZT_ENABLE_CLUSTER
  542. if (RR->cluster)
  543. RR->cluster->handleIncomingStateMessage(msg,len);
  544. #endif
  545. }
  546. void Node::clusterStatus(ZT_ClusterStatus *cs)
  547. {
  548. if (!cs)
  549. return;
  550. #ifdef ZT_ENABLE_CLUSTER
  551. if (RR->cluster)
  552. RR->cluster->status(*cs);
  553. else
  554. #endif
  555. memset(cs,0,sizeof(ZT_ClusterStatus));
  556. }
  557. void Node::backgroundThreadMain()
  558. {
  559. ++RR->dpEnabled;
  560. for(;;) {
  561. try {
  562. if (RR->dp->process() < 0)
  563. break;
  564. } catch ( ... ) {} // sanity check -- should not throw
  565. }
  566. --RR->dpEnabled;
  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. enum ZT_ResultCode ZT_Node_clusterInit(
  851. ZT_Node *node,
  852. unsigned int myId,
  853. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  854. unsigned int numZeroTierPhysicalEndpoints,
  855. int x,
  856. int y,
  857. int z,
  858. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  859. void *sendFunctionArg,
  860. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  861. void *addressToLocationFunctionArg)
  862. {
  863. try {
  864. return reinterpret_cast<ZeroTier::Node *>(node)->clusterInit(myId,zeroTierPhysicalEndpoints,numZeroTierPhysicalEndpoints,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  865. } catch ( ... ) {
  866. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  867. }
  868. }
  869. enum ZT_ResultCode ZT_Node_clusterAddMember(ZT_Node *node,unsigned int memberId)
  870. {
  871. try {
  872. return reinterpret_cast<ZeroTier::Node *>(node)->clusterAddMember(memberId);
  873. } catch ( ... ) {
  874. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  875. }
  876. }
  877. void ZT_Node_clusterRemoveMember(ZT_Node *node,unsigned int memberId)
  878. {
  879. try {
  880. reinterpret_cast<ZeroTier::Node *>(node)->clusterRemoveMember(memberId);
  881. } catch ( ... ) {}
  882. }
  883. void ZT_Node_clusterHandleIncomingMessage(ZT_Node *node,const void *msg,unsigned int len)
  884. {
  885. try {
  886. reinterpret_cast<ZeroTier::Node *>(node)->clusterHandleIncomingMessage(msg,len);
  887. } catch ( ... ) {}
  888. }
  889. void ZT_Node_clusterStatus(ZT_Node *node,ZT_ClusterStatus *cs)
  890. {
  891. try {
  892. reinterpret_cast<ZeroTier::Node *>(node)->clusterStatus(cs);
  893. } catch ( ... ) {}
  894. }
  895. void ZT_Node_setTrustedPaths(ZT_Node *node,const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  896. {
  897. try {
  898. reinterpret_cast<ZeroTier::Node *>(node)->setTrustedPaths(networks,ids,count);
  899. } catch ( ... ) {}
  900. }
  901. void ZT_Node_backgroundThreadMain(ZT_Node *node)
  902. {
  903. try {
  904. reinterpret_cast<ZeroTier::Node *>(node)->backgroundThreadMain();
  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"