Node.cpp 23 KB

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