Node.cpp 25 KB

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