Node.cpp 21 KB

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