Node.cpp 25 KB

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