Node.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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 "Defaults.hpp"
  47. namespace ZeroTier {
  48. /****************************************************************************/
  49. /* Public Node interface (C++, exposed via CAPI bindings) */
  50. /****************************************************************************/
  51. Node::Node(
  52. uint64_t now,
  53. void *uptr,
  54. ZT1_DataStoreGetFunction dataStoreGetFunction,
  55. ZT1_DataStorePutFunction dataStorePutFunction,
  56. ZT1_WirePacketSendFunction wirePacketSendFunction,
  57. ZT1_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  58. ZT1_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  59. ZT1_EventCallback eventCallback,
  60. const char *overrideRootTopology) :
  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. _newestVersionSeen[0] = ZEROTIER_ONE_VERSION_MAJOR;
  78. _newestVersionSeen[1] = ZEROTIER_ONE_VERSION_MINOR;
  79. _newestVersionSeen[2] = ZEROTIER_ONE_VERSION_REVISION;
  80. _online = false;
  81. // Use Salsa20 alone as a high-quality non-crypto PRNG
  82. {
  83. char foo[32];
  84. Utils::getSecureRandom(foo,32);
  85. _prng.init(foo,256,foo,8);
  86. memset(_prngStream,0,sizeof(_prngStream));
  87. _prng.encrypt(_prngStream,_prngStream,sizeof(_prngStream));
  88. }
  89. std::string idtmp(dataStoreGet("identity.secret"));
  90. if ((!idtmp.length())||(!RR->identity.fromString(idtmp))||(!RR->identity.hasPrivate())) {
  91. TRACE("identity.secret not found, generating...");
  92. RR->identity.generate();
  93. idtmp = RR->identity.toString(true);
  94. if (!dataStorePut("identity.secret",idtmp,true))
  95. throw std::runtime_error("unable to write identity.secret");
  96. }
  97. RR->publicIdentityStr = RR->identity.toString(false);
  98. RR->secretIdentityStr = RR->identity.toString(true);
  99. idtmp = dataStoreGet("identity.public");
  100. if (idtmp != RR->publicIdentityStr) {
  101. if (!dataStorePut("identity.public",RR->publicIdentityStr,false))
  102. throw std::runtime_error("unable to write identity.public");
  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. } catch ( ... ) {
  111. delete RR->sa;
  112. delete RR->topology;
  113. delete RR->antiRec;
  114. delete RR->mc;
  115. delete RR->sw;
  116. throw;
  117. }
  118. Dictionary rt;
  119. if (overrideRootTopology) {
  120. rt.fromString(std::string(overrideRootTopology));
  121. } else {
  122. std::string rttmp(dataStoreGet("root-topology"));
  123. if (rttmp.length() > 0) {
  124. rt.fromString(rttmp);
  125. if (!Topology::authenticateRootTopology(rt))
  126. rt.clear();
  127. }
  128. if ((!rt.size())||(!rt.contains("rootservers")))
  129. rt.fromString(ZT_DEFAULTS.defaultRootTopology);
  130. }
  131. RR->topology->setRootServers(Dictionary(rt.get("rootservers","")));
  132. postEvent(ZT1_EVENT_UP);
  133. }
  134. Node::~Node()
  135. {
  136. Mutex::Lock _l(_networks_m);
  137. _networks.clear(); // ensure that networks are destroyed before shutdown
  138. delete RR->sa;
  139. delete RR->topology;
  140. delete RR->antiRec;
  141. delete RR->mc;
  142. delete RR->sw;
  143. }
  144. ZT1_ResultCode Node::processWirePacket(
  145. uint64_t now,
  146. const struct sockaddr_storage *remoteAddress,
  147. const void *packetData,
  148. unsigned int packetLength,
  149. volatile uint64_t *nextBackgroundTaskDeadline)
  150. {
  151. _now = now;
  152. RR->sw->onRemotePacket(*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  153. return ZT1_RESULT_OK;
  154. }
  155. ZT1_ResultCode Node::processVirtualNetworkFrame(
  156. uint64_t now,
  157. uint64_t nwid,
  158. uint64_t sourceMac,
  159. uint64_t destMac,
  160. unsigned int etherType,
  161. unsigned int vlanId,
  162. const void *frameData,
  163. unsigned int frameLength,
  164. volatile uint64_t *nextBackgroundTaskDeadline)
  165. {
  166. _now = now;
  167. SharedPtr<Network> nw(this->network(nwid));
  168. if (nw) {
  169. RR->sw->onLocalEthernet(nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  170. return ZT1_RESULT_OK;
  171. } else return ZT1_RESULT_ERROR_NETWORK_NOT_FOUND;
  172. }
  173. class _PingPeersThatNeedPing
  174. {
  175. public:
  176. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,uint64_t now,const std::vector< std::pair<Address,InetAddress> > &relays) :
  177. lastReceiveFromUpstream(0),
  178. RR(renv),
  179. _now(now),
  180. _relays(relays),
  181. _rootAddresses(RR->topology->rootAddresses())
  182. {
  183. }
  184. uint64_t lastReceiveFromUpstream;
  185. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  186. {
  187. bool isRelay = false;
  188. for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(_relays.begin());r!=_relays.end();++r) {
  189. if (r->first == p->address()) {
  190. isRelay = true;
  191. break;
  192. }
  193. }
  194. if ((isRelay)||(std::find(_rootAddresses.begin(),_rootAddresses.end(),p->address()) != _rootAddresses.end())) {
  195. p->doPingAndKeepalive(RR,_now);
  196. if (p->lastReceive() > lastReceiveFromUpstream)
  197. lastReceiveFromUpstream = p->lastReceive();
  198. } else {
  199. if (p->alive(_now))
  200. p->doPingAndKeepalive(RR,_now);
  201. }
  202. }
  203. private:
  204. const RuntimeEnvironment *RR;
  205. uint64_t _now;
  206. const std::vector< std::pair<Address,InetAddress> > &_relays;
  207. std::vector<Address> _rootAddresses;
  208. };
  209. ZT1_ResultCode Node::processBackgroundTasks(uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  210. {
  211. _now = now;
  212. Mutex::Lock bl(_backgroundTasksLock);
  213. if ((now - _lastPingCheck) >= ZT_PING_CHECK_INVERVAL) {
  214. try {
  215. _lastPingCheck = now;
  216. // Get relays and networks that need config without leaving the mutex locked
  217. std::vector< std::pair<Address,InetAddress> > networkRelays;
  218. std::vector< SharedPtr<Network> > needConfig;
  219. {
  220. Mutex::Lock _l(_networks_m);
  221. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  222. SharedPtr<NetworkConfig> nc(n->second->config2());
  223. if (((now - n->second->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!nc))
  224. needConfig.push_back(n->second);
  225. if (nc)
  226. networkRelays.insert(networkRelays.end(),nc->relays().begin(),nc->relays().end());
  227. }
  228. }
  229. // Request updated configuration for networks that need it
  230. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  231. (*n)->requestConfiguration();
  232. // Attempt to contact network preferred relays that we don't have direct links to
  233. std::sort(networkRelays.begin(),networkRelays.end());
  234. networkRelays.erase(std::unique(networkRelays.begin(),networkRelays.end()),networkRelays.end());
  235. for(std::vector< std::pair<Address,InetAddress> >::const_iterator nr(networkRelays.begin());nr!=networkRelays.end();++nr) {
  236. if (nr->second) {
  237. SharedPtr<Peer> rp(RR->topology->getPeer(nr->first));
  238. if ((rp)&&(!rp->hasActiveDirectPath(now)))
  239. rp->attemptToContactAt(RR,nr->second,now);
  240. }
  241. }
  242. // Ping living or root server/relay peers
  243. _PingPeersThatNeedPing pfunc(RR,now,networkRelays);
  244. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  245. // Update online status, post status change as event
  246. bool oldOnline = _online;
  247. _online = ((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT);
  248. if (oldOnline != _online)
  249. postEvent(_online ? ZT1_EVENT_ONLINE : ZT1_EVENT_OFFLINE);
  250. } catch ( ... ) {
  251. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  252. }
  253. }
  254. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  255. try {
  256. _lastHousekeepingRun = now;
  257. RR->topology->clean(now);
  258. RR->sa->clean(now);
  259. RR->mc->clean(now);
  260. } catch ( ... ) {
  261. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  262. }
  263. }
  264. try {
  265. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min((unsigned long)ZT_PING_CHECK_INVERVAL,RR->sw->doTimerTasks(now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  266. } catch ( ... ) {
  267. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  268. }
  269. return ZT1_RESULT_OK;
  270. }
  271. ZT1_ResultCode Node::join(uint64_t nwid)
  272. {
  273. Mutex::Lock _l(_networks_m);
  274. SharedPtr<Network> nw = _network(nwid);
  275. if(!nw)
  276. _networks.push_back(std::pair< uint64_t,SharedPtr<Network> >(nwid,SharedPtr<Network>(new Network(RR,nwid))));
  277. std::sort(_networks.begin(),_networks.end()); // will sort by nwid since it's the first in a pair<>
  278. return ZT1_RESULT_OK;
  279. }
  280. ZT1_ResultCode Node::leave(uint64_t nwid)
  281. {
  282. std::vector< std::pair< uint64_t,SharedPtr<Network> > > newn;
  283. Mutex::Lock _l(_networks_m);
  284. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n) {
  285. if (n->first != nwid)
  286. newn.push_back(*n);
  287. else n->second->destroy();
  288. }
  289. _networks.swap(newn);
  290. return ZT1_RESULT_OK;
  291. }
  292. ZT1_ResultCode Node::multicastSubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  293. {
  294. SharedPtr<Network> nw(this->network(nwid));
  295. if (nw) {
  296. nw->multicastSubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  297. return ZT1_RESULT_OK;
  298. } else return ZT1_RESULT_ERROR_NETWORK_NOT_FOUND;
  299. }
  300. ZT1_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  301. {
  302. SharedPtr<Network> nw(this->network(nwid));
  303. if (nw) {
  304. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  305. return ZT1_RESULT_OK;
  306. } else return ZT1_RESULT_ERROR_NETWORK_NOT_FOUND;
  307. }
  308. uint64_t Node::address() const
  309. {
  310. return RR->identity.address().toInt();
  311. }
  312. void Node::status(ZT1_NodeStatus *status) const
  313. {
  314. status->address = RR->identity.address().toInt();
  315. status->publicIdentity = RR->publicIdentityStr.c_str();
  316. status->secretIdentity = RR->secretIdentityStr.c_str();
  317. status->online = _online ? 1 : 0;
  318. }
  319. ZT1_PeerList *Node::peers() const
  320. {
  321. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  322. std::sort(peers.begin(),peers.end());
  323. char *buf = (char *)::malloc(sizeof(ZT1_PeerList) + (sizeof(ZT1_Peer) * peers.size()));
  324. if (!buf)
  325. return (ZT1_PeerList *)0;
  326. ZT1_PeerList *pl = (ZT1_PeerList *)buf;
  327. pl->peers = (ZT1_Peer *)(buf + sizeof(ZT1_PeerList));
  328. pl->peerCount = 0;
  329. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  330. ZT1_Peer *p = &(pl->peers[pl->peerCount++]);
  331. p->address = pi->second->address().toInt();
  332. p->lastUnicastFrame = pi->second->lastUnicastFrame();
  333. p->lastMulticastFrame = pi->second->lastMulticastFrame();
  334. if (pi->second->remoteVersionKnown()) {
  335. p->versionMajor = pi->second->remoteVersionMajor();
  336. p->versionMinor = pi->second->remoteVersionMinor();
  337. p->versionRev = pi->second->remoteVersionRevision();
  338. } else {
  339. p->versionMajor = -1;
  340. p->versionMinor = -1;
  341. p->versionRev = -1;
  342. }
  343. p->latency = pi->second->latency();
  344. p->role = RR->topology->isRoot(pi->second->identity()) ? ZT1_PEER_ROLE_ROOT : ZT1_PEER_ROLE_LEAF;
  345. std::vector<RemotePath> paths(pi->second->paths());
  346. RemotePath *bestPath = pi->second->getBestPath(_now);
  347. p->pathCount = 0;
  348. for(std::vector<RemotePath>::iterator path(paths.begin());path!=paths.end();++path) {
  349. memcpy(&(p->paths[p->pathCount].address),&(path->address()),sizeof(struct sockaddr_storage));
  350. p->paths[p->pathCount].lastSend = path->lastSend();
  351. p->paths[p->pathCount].lastReceive = path->lastReceived();
  352. p->paths[p->pathCount].fixed = path->fixed() ? 1 : 0;
  353. p->paths[p->pathCount].active = path->active(_now) ? 1 : 0;
  354. p->paths[p->pathCount].preferred = ((bestPath)&&(*path == *bestPath)) ? 1 : 0;
  355. ++p->pathCount;
  356. }
  357. }
  358. return pl;
  359. }
  360. ZT1_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  361. {
  362. Mutex::Lock _l(_networks_m);
  363. SharedPtr<Network> nw = _network(nwid);
  364. if(nw) {
  365. ZT1_VirtualNetworkConfig *nc = (ZT1_VirtualNetworkConfig *)::malloc(sizeof(ZT1_VirtualNetworkConfig));
  366. nw->externalConfig(nc);
  367. return nc;
  368. }
  369. return (ZT1_VirtualNetworkConfig *)0;
  370. }
  371. ZT1_VirtualNetworkList *Node::networks() const
  372. {
  373. Mutex::Lock _l(_networks_m);
  374. char *buf = (char *)::malloc(sizeof(ZT1_VirtualNetworkList) + (sizeof(ZT1_VirtualNetworkConfig) * _networks.size()));
  375. if (!buf)
  376. return (ZT1_VirtualNetworkList *)0;
  377. ZT1_VirtualNetworkList *nl = (ZT1_VirtualNetworkList *)buf;
  378. nl->networks = (ZT1_VirtualNetworkConfig *)(buf + sizeof(ZT1_VirtualNetworkList));
  379. nl->networkCount = 0;
  380. for(std::vector< std::pair< uint64_t,SharedPtr<Network> > >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  381. n->second->externalConfig(&(nl->networks[nl->networkCount++]));
  382. return nl;
  383. }
  384. void Node::freeQueryResult(void *qr)
  385. {
  386. if (qr)
  387. ::free(qr);
  388. }
  389. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr,int metric,ZT1_LocalInterfaceAddressTrust trust)
  390. {
  391. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  392. Mutex::Lock _l(_directPaths_m);
  393. _directPaths.push_back(Path(*(reinterpret_cast<const InetAddress *>(addr)),metric,(Path::Trust)trust));
  394. std::sort(_directPaths.begin(),_directPaths.end());
  395. _directPaths.erase(std::unique(_directPaths.begin(),_directPaths.end()),_directPaths.end());
  396. return 1;
  397. }
  398. return 0;
  399. }
  400. void Node::clearLocalInterfaceAddresses()
  401. {
  402. Mutex::Lock _l(_directPaths_m);
  403. _directPaths.clear();
  404. }
  405. void Node::setNetconfMaster(void *networkControllerInstance)
  406. {
  407. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  408. }
  409. /****************************************************************************/
  410. /* Node methods used only within node/ */
  411. /****************************************************************************/
  412. std::string Node::dataStoreGet(const char *name)
  413. {
  414. char buf[16384];
  415. std::string r;
  416. unsigned long olen = 0;
  417. do {
  418. long n = _dataStoreGetFunction(reinterpret_cast<ZT1_Node *>(this),_uPtr,name,buf,sizeof(buf),(unsigned long)r.length(),&olen);
  419. if (n <= 0)
  420. return std::string();
  421. r.append(buf,n);
  422. } while (r.length() < olen);
  423. return r;
  424. }
  425. void Node::postNewerVersionIfNewer(unsigned int major,unsigned int minor,unsigned int rev)
  426. {
  427. if (Utils::compareVersion(major,minor,rev,_newestVersionSeen[0],_newestVersionSeen[1],_newestVersionSeen[2]) > 0) {
  428. _newestVersionSeen[0] = major;
  429. _newestVersionSeen[1] = minor;
  430. _newestVersionSeen[2] = rev;
  431. this->postEvent(ZT1_EVENT_SAW_MORE_RECENT_VERSION,(const void *)_newestVersionSeen);
  432. }
  433. }
  434. #ifdef ZT_TRACE
  435. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  436. {
  437. static Mutex traceLock;
  438. va_list ap;
  439. char tmp1[1024],tmp2[1024],tmp3[256];
  440. Mutex::Lock _l(traceLock);
  441. time_t now = (time_t)(_now / 1000ULL);
  442. #ifdef __WINDOWS__
  443. ctime_s(tmp3,sizeof(tmp3),&now);
  444. char *nowstr = tmp3;
  445. #else
  446. char *nowstr = ctime_r(&now,tmp3);
  447. #endif
  448. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  449. if (nowstr[nowstrlen-1] == '\n')
  450. nowstr[--nowstrlen] = (char)0;
  451. if (nowstr[nowstrlen-1] == '\r')
  452. nowstr[--nowstrlen] = (char)0;
  453. va_start(ap,fmt);
  454. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  455. va_end(ap);
  456. tmp2[sizeof(tmp2)-1] = (char)0;
  457. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  458. postEvent(ZT1_EVENT_TRACE,tmp1);
  459. }
  460. #endif // ZT_TRACE
  461. uint64_t Node::prng()
  462. {
  463. unsigned int p = (++_prngStreamPtr % (sizeof(_prngStream) / sizeof(uint64_t)));
  464. if (!p)
  465. _prng.encrypt(_prngStream,_prngStream,sizeof(_prngStream));
  466. return _prngStream[p];
  467. }
  468. } // namespace ZeroTier
  469. /****************************************************************************/
  470. /* CAPI bindings */
  471. /****************************************************************************/
  472. extern "C" {
  473. enum ZT1_ResultCode ZT1_Node_new(
  474. ZT1_Node **node,
  475. void *uptr,
  476. uint64_t now,
  477. ZT1_DataStoreGetFunction dataStoreGetFunction,
  478. ZT1_DataStorePutFunction dataStorePutFunction,
  479. ZT1_WirePacketSendFunction wirePacketSendFunction,
  480. ZT1_VirtualNetworkFrameFunction virtualNetworkFrameFunction,
  481. ZT1_VirtualNetworkConfigFunction virtualNetworkConfigFunction,
  482. ZT1_EventCallback eventCallback,
  483. const char *overrideRootTopology)
  484. {
  485. *node = (ZT1_Node *)0;
  486. try {
  487. *node = reinterpret_cast<ZT1_Node *>(new ZeroTier::Node(now,uptr,dataStoreGetFunction,dataStorePutFunction,wirePacketSendFunction,virtualNetworkFrameFunction,virtualNetworkConfigFunction,eventCallback,overrideRootTopology));
  488. return ZT1_RESULT_OK;
  489. } catch (std::bad_alloc &exc) {
  490. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  491. } catch (std::runtime_error &exc) {
  492. return ZT1_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  493. } catch ( ... ) {
  494. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  495. }
  496. }
  497. void ZT1_Node_delete(ZT1_Node *node)
  498. {
  499. try {
  500. delete (reinterpret_cast<ZeroTier::Node *>(node));
  501. } catch ( ... ) {}
  502. }
  503. enum ZT1_ResultCode ZT1_Node_processWirePacket(
  504. ZT1_Node *node,
  505. uint64_t now,
  506. const struct sockaddr_storage *remoteAddress,
  507. const void *packetData,
  508. unsigned int packetLength,
  509. volatile uint64_t *nextBackgroundTaskDeadline)
  510. {
  511. try {
  512. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(now,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  513. } catch (std::bad_alloc &exc) {
  514. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  515. } catch ( ... ) {
  516. reinterpret_cast<ZeroTier::Node *>(node)->postEvent(ZT1_EVENT_INVALID_PACKET,(const void *)remoteAddress);
  517. return ZT1_RESULT_OK;
  518. }
  519. }
  520. enum ZT1_ResultCode ZT1_Node_processVirtualNetworkFrame(
  521. ZT1_Node *node,
  522. uint64_t now,
  523. uint64_t nwid,
  524. uint64_t sourceMac,
  525. uint64_t destMac,
  526. unsigned int etherType,
  527. unsigned int vlanId,
  528. const void *frameData,
  529. unsigned int frameLength,
  530. volatile uint64_t *nextBackgroundTaskDeadline)
  531. {
  532. try {
  533. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  534. } catch (std::bad_alloc &exc) {
  535. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  536. } catch ( ... ) {
  537. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  538. }
  539. }
  540. enum ZT1_ResultCode ZT1_Node_processBackgroundTasks(ZT1_Node *node,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  541. {
  542. try {
  543. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(now,nextBackgroundTaskDeadline);
  544. } catch (std::bad_alloc &exc) {
  545. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  546. } catch ( ... ) {
  547. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  548. }
  549. }
  550. enum ZT1_ResultCode ZT1_Node_join(ZT1_Node *node,uint64_t nwid)
  551. {
  552. try {
  553. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid);
  554. } catch (std::bad_alloc &exc) {
  555. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  556. } catch ( ... ) {
  557. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  558. }
  559. }
  560. enum ZT1_ResultCode ZT1_Node_leave(ZT1_Node *node,uint64_t nwid)
  561. {
  562. try {
  563. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid);
  564. } catch (std::bad_alloc &exc) {
  565. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  566. } catch ( ... ) {
  567. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  568. }
  569. }
  570. enum ZT1_ResultCode ZT1_Node_multicastSubscribe(ZT1_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  571. {
  572. try {
  573. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(nwid,multicastGroup,multicastAdi);
  574. } catch (std::bad_alloc &exc) {
  575. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  576. } catch ( ... ) {
  577. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  578. }
  579. }
  580. enum ZT1_ResultCode ZT1_Node_multicastUnsubscribe(ZT1_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  581. {
  582. try {
  583. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  584. } catch (std::bad_alloc &exc) {
  585. return ZT1_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  586. } catch ( ... ) {
  587. return ZT1_RESULT_FATAL_ERROR_INTERNAL;
  588. }
  589. }
  590. uint64_t ZT1_Node_address(ZT1_Node *node)
  591. {
  592. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  593. }
  594. void ZT1_Node_status(ZT1_Node *node,ZT1_NodeStatus *status)
  595. {
  596. try {
  597. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  598. } catch ( ... ) {}
  599. }
  600. ZT1_PeerList *ZT1_Node_peers(ZT1_Node *node)
  601. {
  602. try {
  603. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  604. } catch ( ... ) {
  605. return (ZT1_PeerList *)0;
  606. }
  607. }
  608. ZT1_VirtualNetworkConfig *ZT1_Node_networkConfig(ZT1_Node *node,uint64_t nwid)
  609. {
  610. try {
  611. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  612. } catch ( ... ) {
  613. return (ZT1_VirtualNetworkConfig *)0;
  614. }
  615. }
  616. ZT1_VirtualNetworkList *ZT1_Node_networks(ZT1_Node *node)
  617. {
  618. try {
  619. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  620. } catch ( ... ) {
  621. return (ZT1_VirtualNetworkList *)0;
  622. }
  623. }
  624. void ZT1_Node_freeQueryResult(ZT1_Node *node,void *qr)
  625. {
  626. try {
  627. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  628. } catch ( ... ) {}
  629. }
  630. void ZT1_Node_setNetconfMaster(ZT1_Node *node,void *networkControllerInstance)
  631. {
  632. try {
  633. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  634. } catch ( ... ) {}
  635. }
  636. int ZT1_Node_addLocalInterfaceAddress(ZT1_Node *node,const struct sockaddr_storage *addr,int metric,ZT1_LocalInterfaceAddressTrust trust)
  637. {
  638. try {
  639. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr,metric,trust);
  640. } catch ( ... ) {
  641. return 0;
  642. }
  643. }
  644. void ZT1_Node_clearLocalInterfaceAddresses(ZT1_Node *node)
  645. {
  646. try {
  647. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  648. } catch ( ... ) {}
  649. }
  650. void ZT1_version(int *major,int *minor,int *revision,unsigned long *featureFlags)
  651. {
  652. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  653. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  654. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  655. if (featureFlags) {
  656. *featureFlags = (
  657. ZT1_FEATURE_FLAG_THREAD_SAFE
  658. );
  659. }
  660. }
  661. } // extern "C"