Node.cpp 27 KB

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