Node.cpp 22 KB

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