Node.cpp 31 KB

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