Node.cpp 31 KB

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