Node.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "Constants.hpp"
  14. #include "SharedPtr.hpp"
  15. #include "Node.hpp"
  16. #include "NetworkController.hpp"
  17. #include "Topology.hpp"
  18. #include "Address.hpp"
  19. #include "Identity.hpp"
  20. #include "SelfAwareness.hpp"
  21. #include "Network.hpp"
  22. #include "Trace.hpp"
  23. #include "Locator.hpp"
  24. #include "Expect.hpp"
  25. #include "VL1.hpp"
  26. #include "VL2.hpp"
  27. #include "Buf.hpp"
  28. namespace ZeroTier {
  29. namespace {
  30. // Structure containing all the core objects for a ZeroTier node to reduce memory allocations.
  31. struct _NodeObjects
  32. {
  33. ZT_INLINE _NodeObjects(RuntimeEnvironment *const RR, void *const tPtr) :
  34. t(RR),
  35. expect(),
  36. vl2(RR),
  37. vl1(RR),
  38. sa(RR),
  39. topology(RR, tPtr)
  40. {
  41. RR->t = &t;
  42. RR->expect = &expect;
  43. RR->vl2 = &vl2;
  44. RR->vl1 = &vl1;
  45. RR->sa = &sa;
  46. RR->topology = &topology;
  47. }
  48. Trace t;
  49. Expect expect;
  50. VL2 vl2;
  51. VL1 vl1;
  52. SelfAwareness sa;
  53. Topology topology;
  54. };
  55. struct _sortPeerPtrsByAddress
  56. {
  57. ZT_INLINE bool operator()(const SharedPtr< Peer > &a, const SharedPtr< Peer > &b) const
  58. { return (a->address() < b->address()); }
  59. };
  60. } // anonymous namespace
  61. Node::Node(
  62. void *uPtr,
  63. void *tPtr,
  64. const struct ZT_Node_Callbacks *callbacks,
  65. int64_t now) :
  66. m_RR(this),
  67. RR(&m_RR),
  68. m_objects(nullptr),
  69. m_cb(*callbacks),
  70. m_uPtr(uPtr),
  71. m_networks(),
  72. m_lastPeerPulse(0),
  73. m_lastHousekeepingRun(0),
  74. m_lastNetworkHousekeepingRun(0),
  75. m_now(now),
  76. m_online(false)
  77. {
  78. ZT_SPEW("starting up...");
  79. // Load this node's identity.
  80. uint64_t idtmp[2];
  81. idtmp[0] = 0;
  82. idtmp[1] = 0;
  83. Vector< uint8_t > data(stateObjectGet(tPtr, ZT_STATE_OBJECT_IDENTITY_SECRET, idtmp));
  84. bool haveIdentity = false;
  85. if (!data.empty()) {
  86. data.push_back(0); // zero-terminate string
  87. if (RR->identity.fromString((const char *)data.data())) {
  88. RR->identity.toString(false, RR->publicIdentityStr);
  89. RR->identity.toString(true, RR->secretIdentityStr);
  90. haveIdentity = true;
  91. ZT_SPEW("loaded identity %s", RR->identity.toString().c_str());
  92. }
  93. }
  94. // Generate a new identity if we don't have one.
  95. if (!haveIdentity) {
  96. RR->identity.generate(Identity::C25519);
  97. RR->identity.toString(false, RR->publicIdentityStr);
  98. RR->identity.toString(true, RR->secretIdentityStr);
  99. idtmp[0] = RR->identity.address();
  100. idtmp[1] = 0;
  101. stateObjectPut(tPtr, ZT_STATE_OBJECT_IDENTITY_SECRET, idtmp, RR->secretIdentityStr, (unsigned int)strlen(RR->secretIdentityStr));
  102. stateObjectPut(tPtr, ZT_STATE_OBJECT_IDENTITY_PUBLIC, idtmp, RR->publicIdentityStr, (unsigned int)strlen(RR->publicIdentityStr));
  103. ZT_SPEW("no pre-existing identity found, created %s", RR->identity.toString().c_str());
  104. } else {
  105. idtmp[0] = RR->identity.address();
  106. idtmp[1] = 0;
  107. data = stateObjectGet(tPtr, ZT_STATE_OBJECT_IDENTITY_PUBLIC, idtmp);
  108. if ((data.empty()) || (memcmp(data.data(), RR->publicIdentityStr, strlen(RR->publicIdentityStr)) != 0))
  109. stateObjectPut(tPtr, ZT_STATE_OBJECT_IDENTITY_PUBLIC, idtmp, RR->publicIdentityStr, (unsigned int)strlen(RR->publicIdentityStr));
  110. }
  111. // 2X hash our identity private key(s) to obtain a symmetric key for encrypting
  112. // locally cached data at rest (as a defense in depth measure). This is not used
  113. // for any network level encryption or authentication.
  114. uint8_t tmph[ZT_SHA384_DIGEST_SIZE];
  115. RR->identity.hashWithPrivate(tmph);
  116. SHA384(tmph, tmph, ZT_SHA384_DIGEST_SIZE);
  117. RR->localCacheSymmetric.init(tmph);
  118. Utils::burn(tmph, ZT_SHA384_DIGEST_SIZE);
  119. // Generate a random sort order for privileged ports for use in NAT-t algorithms.
  120. for (unsigned int i = 0; i < 1023; ++i)
  121. RR->randomPrivilegedPortOrder[i] = (uint16_t)(i + 1);
  122. for (unsigned int i = 0; i < 512; ++i) {
  123. uint64_t rn = Utils::random();
  124. const unsigned int a = (unsigned int)rn % 1023;
  125. const unsigned int b = (unsigned int)(rn >> 32U) % 1023;
  126. if (a != b) {
  127. const uint16_t tmp = RR->randomPrivilegedPortOrder[a];
  128. RR->randomPrivilegedPortOrder[a] = RR->randomPrivilegedPortOrder[b];
  129. RR->randomPrivilegedPortOrder[b] = tmp;
  130. }
  131. }
  132. // This constructs all the components of the ZeroTier core within a single contiguous memory container,
  133. // which reduces memory fragmentation and may improve cache locality.
  134. ZT_SPEW("initializing subsystem objects...");
  135. m_objects = new _NodeObjects(RR, tPtr);
  136. ZT_SPEW("node initialized!");
  137. postEvent(tPtr, ZT_EVENT_UP);
  138. }
  139. Node::~Node()
  140. {
  141. ZT_SPEW("node destructor run");
  142. m_networks_l.lock();
  143. m_networks_l.unlock();
  144. m_networks.clear();
  145. m_networks_l.lock();
  146. m_networks_l.unlock();
  147. if (m_objects)
  148. delete (_NodeObjects *)m_objects;
  149. // Let go of cached Buf objects. If other nodes happen to be running in this
  150. // same process space new Bufs will be allocated as needed, but this is almost
  151. // never the case. Calling this here saves RAM if we are running inside something
  152. // that wants to keep running after tearing down its ZeroTier core instance.
  153. Buf::freePool();
  154. }
  155. void Node::shutdown(void *tPtr)
  156. {
  157. ZT_SPEW("explicit shutdown() called");
  158. postEvent(tPtr, ZT_EVENT_DOWN);
  159. if (RR->topology)
  160. RR->topology->saveAll(tPtr);
  161. }
  162. ZT_ResultCode Node::processWirePacket(
  163. void *tPtr,
  164. int64_t now,
  165. int64_t localSocket,
  166. const struct sockaddr_storage *remoteAddress,
  167. SharedPtr< Buf > &packetData,
  168. unsigned int packetLength,
  169. volatile int64_t *nextBackgroundTaskDeadline)
  170. {
  171. m_now = now;
  172. RR->vl1->onRemotePacket(tPtr, localSocket, (remoteAddress) ? InetAddress::NIL : *asInetAddress(remoteAddress), packetData, packetLength);
  173. return ZT_RESULT_OK;
  174. }
  175. ZT_ResultCode Node::processVirtualNetworkFrame(
  176. void *tPtr,
  177. int64_t now,
  178. uint64_t nwid,
  179. uint64_t sourceMac,
  180. uint64_t destMac,
  181. unsigned int etherType,
  182. unsigned int vlanId,
  183. SharedPtr< Buf > &frameData,
  184. unsigned int frameLength,
  185. volatile int64_t *nextBackgroundTaskDeadline)
  186. {
  187. m_now = now;
  188. SharedPtr< Network > nw(this->network(nwid));
  189. if (nw) {
  190. RR->vl2->onLocalEthernet(tPtr, nw, MAC(sourceMac), MAC(destMac), etherType, vlanId, frameData, frameLength);
  191. return ZT_RESULT_OK;
  192. } else {
  193. return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  194. }
  195. }
  196. ZT_ResultCode Node::processHTTPResponse(
  197. void *tptr,
  198. int64_t now,
  199. void *requestId,
  200. int responseCode,
  201. const char **headerNames,
  202. const char **headerValues,
  203. const void *body,
  204. unsigned int bodySize,
  205. unsigned int flags)
  206. {
  207. return ZT_RESULT_OK;
  208. }
  209. ZT_ResultCode Node::processBackgroundTasks(
  210. void *tPtr,
  211. int64_t now,
  212. volatile int64_t *nextBackgroundTaskDeadline)
  213. {
  214. m_now = now;
  215. Mutex::Lock bl(m_backgroundTasksLock);
  216. try {
  217. // Call peer pulse() method of all peers every ZT_PEER_PULSE_INTERVAL.
  218. if ((now - m_lastPeerPulse) >= ZT_PEER_PULSE_INTERVAL) {
  219. m_lastPeerPulse = now;
  220. ZT_SPEW("running pulse() on each peer...");
  221. try {
  222. Vector< SharedPtr< Peer > > allPeers, rootPeers;
  223. RR->topology->getAllPeers(allPeers, rootPeers);
  224. bool online = false;
  225. for (Vector< SharedPtr< Peer > >::iterator p(allPeers.begin()); p != allPeers.end(); ++p) {
  226. const bool isRoot = std::find(rootPeers.begin(), rootPeers.end(), *p) != rootPeers.end();
  227. (*p)->pulse(tPtr, now, isRoot);
  228. online |= ((isRoot || rootPeers.empty()) && (*p)->directlyConnected(now));
  229. }
  230. RR->topology->rankRoots();
  231. if (m_online.exchange(online) != online)
  232. postEvent(tPtr, online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  233. } catch (...) {
  234. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  235. }
  236. }
  237. // Perform network housekeeping and possibly request new certs and configs every ZT_NETWORK_HOUSEKEEPING_PERIOD.
  238. if ((now - m_lastNetworkHousekeepingRun) >= ZT_NETWORK_HOUSEKEEPING_PERIOD) {
  239. m_lastHousekeepingRun = now;
  240. ZT_SPEW("running networking housekeeping...");
  241. RWMutex::RLock l(m_networks_l);
  242. for (Map< uint64_t, SharedPtr< Network > >::const_iterator i(m_networks.begin()); i != m_networks.end(); ++i) {
  243. i->second->doPeriodicTasks(tPtr, now);
  244. }
  245. }
  246. // Clean up other stuff every ZT_HOUSEKEEPING_PERIOD.
  247. if ((now - m_lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  248. m_lastHousekeepingRun = now;
  249. ZT_SPEW("running housekeeping...");
  250. // Clean up any old local controller auth memoizations. This is an
  251. // optimization for network controllers to know whether to accept
  252. // or trust nodes without doing an extra cert check.
  253. m_localControllerAuthorizations_l.lock();
  254. for (Map< p_LocalControllerAuth, int64_t >::iterator i(m_localControllerAuthorizations.begin()); i != m_localControllerAuthorizations.end();) { // NOLINT(hicpp-use-auto,modernize-use-auto)
  255. if ((i->second - now) > (ZT_NETWORK_AUTOCONF_DELAY * 3))
  256. m_localControllerAuthorizations.erase(i++);
  257. else ++i;
  258. }
  259. m_localControllerAuthorizations_l.unlock();
  260. RR->topology->doPeriodicTasks(tPtr, now);
  261. RR->sa->clean(now);
  262. }
  263. *nextBackgroundTaskDeadline = now + ZT_TIMER_TASK_INTERVAL;
  264. } catch (...) {
  265. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  266. }
  267. return ZT_RESULT_OK;
  268. }
  269. ZT_ResultCode Node::join(
  270. uint64_t nwid,
  271. const ZT_Fingerprint *controllerFingerprint,
  272. void *uptr,
  273. void *tptr)
  274. {
  275. Fingerprint fp;
  276. if (controllerFingerprint) {
  277. fp = *controllerFingerprint;
  278. ZT_SPEW("joining network %.16llx with fingerprint %s", nwid, fp.toString().c_str());
  279. } else {
  280. ZT_SPEW("joining network %.16llx", nwid);
  281. }
  282. RWMutex::Lock l(m_networks_l);
  283. SharedPtr< Network > &nw = m_networks[nwid];
  284. if (nw)
  285. return ZT_RESULT_OK;
  286. nw.set(new Network(RR, tptr, nwid, fp, uptr, nullptr));
  287. return ZT_RESULT_OK;
  288. }
  289. ZT_ResultCode Node::leave(
  290. uint64_t nwid,
  291. void **uptr,
  292. void *tptr)
  293. {
  294. ZT_SPEW("leaving network %.16llx", nwid);
  295. ZT_VirtualNetworkConfig ctmp;
  296. m_networks_l.lock();
  297. Map< uint64_t, SharedPtr< Network > >::iterator nwi(m_networks.find(nwid)); // NOLINT(hicpp-use-auto,modernize-use-auto)
  298. if (nwi == m_networks.end()) {
  299. m_networks_l.unlock();
  300. return ZT_RESULT_OK;
  301. }
  302. SharedPtr< Network > nw(nwi->second);
  303. m_networks.erase(nwi);
  304. m_networks_l.unlock();
  305. if (uptr)
  306. *uptr = *nw->userPtr();
  307. nw->externalConfig(&ctmp);
  308. RR->node->configureVirtualNetworkPort(tptr, nwid, uptr, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY, &ctmp);
  309. nw->destroy();
  310. nw.zero();
  311. uint64_t tmp[2];
  312. tmp[0] = nwid;
  313. tmp[1] = 0;
  314. RR->node->stateObjectDelete(tptr, ZT_STATE_OBJECT_NETWORK_CONFIG, tmp);
  315. return ZT_RESULT_OK;
  316. }
  317. ZT_ResultCode Node::multicastSubscribe(
  318. void *tPtr,
  319. uint64_t nwid,
  320. uint64_t multicastGroup,
  321. unsigned long multicastAdi)
  322. {
  323. ZT_SPEW("multicast subscribe to %s:%lu", MAC(multicastGroup).toString().c_str(), multicastAdi);
  324. const SharedPtr< Network > nw(this->network(nwid));
  325. if (nw) {
  326. nw->multicastSubscribe(tPtr, MulticastGroup(MAC(multicastGroup), (uint32_t)(multicastAdi & 0xffffffff)));
  327. return ZT_RESULT_OK;
  328. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  329. }
  330. ZT_ResultCode Node::multicastUnsubscribe(
  331. uint64_t nwid,
  332. uint64_t multicastGroup,
  333. unsigned long multicastAdi)
  334. {
  335. ZT_SPEW("multicast unsubscribe from %s:%lu", MAC(multicastGroup).toString().c_str(), multicastAdi);
  336. const 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. ZT_ResultCode Node::addRoot(
  343. void *tPtr,
  344. const ZT_Identity *id)
  345. {
  346. return (RR->topology->addRoot(tPtr, *reinterpret_cast<const Identity *>(id))) ? ZT_RESULT_OK : ZT_RESULT_ERROR_BAD_PARAMETER;
  347. }
  348. ZT_ResultCode Node::removeRoot(
  349. void *tPtr,
  350. const uint64_t address)
  351. {
  352. RR->topology->removeRoot(tPtr, Address(address));
  353. return ZT_RESULT_OK;
  354. }
  355. uint64_t Node::address() const
  356. {
  357. return RR->identity.address().toInt();
  358. }
  359. void Node::status(ZT_NodeStatus *status) const
  360. {
  361. status->address = RR->identity.address().toInt();
  362. status->identity = reinterpret_cast<const ZT_Identity *>(&RR->identity);
  363. status->publicIdentity = RR->publicIdentityStr;
  364. status->secretIdentity = RR->secretIdentityStr;
  365. status->online = m_online ? 1 : 0;
  366. }
  367. ZT_PeerList *Node::peers() const
  368. {
  369. Vector< SharedPtr< Peer > > peers;
  370. RR->topology->getAllPeers(peers);
  371. std::sort(peers.begin(), peers.end(), _sortPeerPtrsByAddress());
  372. const unsigned int bufSize =
  373. sizeof(ZT_PeerList) +
  374. (sizeof(ZT_Peer) * peers.size()) +
  375. ((sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size()) +
  376. (sizeof(Identity) * peers.size()) +
  377. (ZT_LOCATOR_MARSHAL_SIZE_MAX * peers.size());
  378. char *buf = (char *)malloc(bufSize);
  379. if (!buf)
  380. return nullptr;
  381. Utils::zero(buf, bufSize);
  382. ZT_PeerList *pl = reinterpret_cast<ZT_PeerList *>(buf);
  383. buf += sizeof(ZT_PeerList);
  384. pl->peers = reinterpret_cast<ZT_Peer *>(buf);
  385. buf += sizeof(ZT_Peer) * peers.size();
  386. ZT_Path *peerPath = reinterpret_cast<ZT_Path *>(buf);
  387. buf += (sizeof(ZT_Path) * ZT_MAX_PEER_NETWORK_PATHS) * peers.size();
  388. Identity *identities = reinterpret_cast<Identity *>(buf);
  389. buf += sizeof(Identity) * peers.size();
  390. uint8_t *locatorBuf = reinterpret_cast<uint8_t *>(buf);
  391. const int64_t now = m_now;
  392. pl->peerCount = 0;
  393. for (Vector< SharedPtr< Peer > >::iterator pi(peers.begin()); pi != peers.end(); ++pi) {
  394. ZT_Peer *const p = pl->peers + pl->peerCount;
  395. p->address = (*pi)->address().toInt();
  396. identities[pl->peerCount] = (*pi)->identity(); // need to make a copy in case peer gets deleted
  397. p->identity = identities + pl->peerCount;
  398. p->fingerprint.address = p->address;
  399. Utils::copy< ZT_FINGERPRINT_HASH_SIZE >(p->fingerprint.hash, (*pi)->identity().fingerprint().hash);
  400. if ((*pi)->remoteVersionKnown()) {
  401. p->versionMajor = (int)(*pi)->remoteVersionMajor();
  402. p->versionMinor = (int)(*pi)->remoteVersionMinor();
  403. p->versionRev = (int)(*pi)->remoteVersionRevision();
  404. } else {
  405. p->versionMajor = -1;
  406. p->versionMinor = -1;
  407. p->versionRev = -1;
  408. }
  409. p->latency = (*pi)->latency();
  410. p->root = RR->topology->isRoot((*pi)->identity()) ? 1 : 0;
  411. p->networkCount = 0;
  412. // TODO: enumerate network memberships
  413. Vector< SharedPtr< Path > > paths;
  414. (*pi)->getAllPaths(paths);
  415. p->pathCount = (unsigned int)paths.size();
  416. p->paths = peerPath;
  417. for (Vector< SharedPtr< Path > >::iterator path(paths.begin()); path != paths.end(); ++path) {
  418. ZT_Path *const pp = peerPath++;
  419. pp->endpoint.type = ZT_ENDPOINT_TYPE_IP_UDP; // only type supported right now
  420. Utils::copy< sizeof(sockaddr_storage) >(&pp->endpoint.value.ss, &((*path)->address().as.ss));
  421. pp->lastSend = (*path)->lastOut();
  422. pp->lastReceive = (*path)->lastIn();
  423. pp->alive = (*path)->alive(now) ? 1 : 0;
  424. pp->preferred = (p->pathCount == 0) ? 1 : 0;
  425. }
  426. const SharedPtr< const Locator > loc((*pi)->locator());
  427. if (loc) {
  428. const int ls = loc->marshal(locatorBuf);
  429. if (ls > 0) {
  430. p->locatorSize = (unsigned int)ls;
  431. p->locator = locatorBuf;
  432. locatorBuf += ls;
  433. }
  434. }
  435. ++pl->peerCount;
  436. }
  437. return pl;
  438. }
  439. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  440. {
  441. SharedPtr< Network > nw(network(nwid));
  442. if (nw) {
  443. ZT_VirtualNetworkConfig *const nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  444. nw->externalConfig(nc);
  445. return nc;
  446. }
  447. return nullptr;
  448. }
  449. ZT_VirtualNetworkList *Node::networks() const
  450. {
  451. RWMutex::RLock l(m_networks_l);
  452. char *const buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * m_networks.size()));
  453. if (!buf)
  454. return nullptr;
  455. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf; // NOLINT(modernize-use-auto,hicpp-use-auto)
  456. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  457. nl->networkCount = 0;
  458. for (Map< uint64_t, SharedPtr< Network > >::const_iterator i(m_networks.begin()); i != m_networks.end(); ++i) // NOLINT(modernize-use-auto,modernize-loop-convert,hicpp-use-auto)
  459. i->second->externalConfig(&(nl->networks[nl->networkCount++]));
  460. return nl;
  461. }
  462. void Node::setNetworkUserPtr(
  463. uint64_t nwid,
  464. void *ptr)
  465. {
  466. SharedPtr< Network > nw(network(nwid));
  467. if (nw)
  468. *(nw->userPtr()) = ptr;
  469. }
  470. void Node::setInterfaceAddresses(
  471. const ZT_InterfaceAddress *addrs,
  472. unsigned int addrCount)
  473. {
  474. Mutex::Lock _l(m_localInterfaceAddresses_m);
  475. m_localInterfaceAddresses.clear();
  476. for (unsigned int i = 0; i < addrCount; ++i) {
  477. bool dupe = false;
  478. for (unsigned int j = 0; j < i; ++j) {
  479. if (*(reinterpret_cast<const InetAddress *>(&addrs[j].address)) == *(reinterpret_cast<const InetAddress *>(&addrs[i].address))) {
  480. dupe = true;
  481. break;
  482. }
  483. }
  484. if (!dupe)
  485. m_localInterfaceAddresses.push_back(addrs[i]);
  486. }
  487. }
  488. ZT_ResultCode Node::addPeer(
  489. void *tptr,
  490. const ZT_Identity *identity)
  491. {
  492. if (!identity)
  493. return ZT_RESULT_ERROR_BAD_PARAMETER;
  494. SharedPtr< Peer > peer(RR->topology->peer(tptr, reinterpret_cast<const Identity *>(identity)->address()));
  495. if (!peer) {
  496. peer.set(new Peer(RR));
  497. peer->init(*reinterpret_cast<const Identity *>(identity));
  498. peer = RR->topology->add(tptr, peer);
  499. }
  500. return (peer->identity() == *reinterpret_cast<const Identity *>(identity)) ? ZT_RESULT_OK : ZT_RESULT_ERROR_COLLIDING_OBJECT;
  501. }
  502. int Node::tryPeer(
  503. void *tptr,
  504. const ZT_Fingerprint *fp,
  505. const ZT_Endpoint *endpoint,
  506. int retries)
  507. {
  508. if ((!fp) || (!endpoint))
  509. return 0;
  510. const SharedPtr< Peer > peer(RR->topology->peer(tptr, fp->address, true));
  511. if ((peer) && (peer->identity().fingerprint().bestSpecificityEquals(*fp))) {
  512. peer->contact(tptr, m_now, Endpoint(*endpoint), std::min(retries, 1));
  513. return 1;
  514. }
  515. return 0;
  516. }
  517. int Node::sendUserMessage(
  518. void *tptr,
  519. uint64_t dest,
  520. uint64_t typeId,
  521. const void *data,
  522. unsigned int len)
  523. {
  524. try {
  525. if (RR->identity.address().toInt() != dest) {
  526. // TODO
  527. /*
  528. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  529. outp.append(typeId);
  530. outp.append(data,len);
  531. outp.compress();
  532. RR->sw->send(tptr,outp,true);
  533. */
  534. return 1;
  535. }
  536. } catch (...) {}
  537. return 0;
  538. }
  539. void Node::setController(void *networkControllerInstance)
  540. {
  541. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  542. if (networkControllerInstance)
  543. RR->localNetworkController->init(RR->identity, this);
  544. }
  545. // Methods used only within the core ----------------------------------------------------------------------------------
  546. Vector< uint8_t > Node::stateObjectGet(void *const tPtr, ZT_StateObjectType type, const uint64_t id[2])
  547. {
  548. Vector< uint8_t > r;
  549. if (m_cb.stateGetFunction) {
  550. void *data = nullptr;
  551. void (*freeFunc)(void *) = nullptr;
  552. int l = m_cb.stateGetFunction(
  553. reinterpret_cast<ZT_Node *>(this),
  554. m_uPtr,
  555. tPtr,
  556. type,
  557. id,
  558. &data,
  559. &freeFunc);
  560. if ((l > 0) && (data) && (freeFunc)) {
  561. r.assign(reinterpret_cast<const uint8_t *>(data), reinterpret_cast<const uint8_t *>(data) + l);
  562. freeFunc(data);
  563. }
  564. }
  565. return r;
  566. }
  567. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr, const Identity &id, const int64_t localSocket, const InetAddress &remoteAddress)
  568. {
  569. {
  570. RWMutex::RLock l(m_networks_l);
  571. for (Map< uint64_t, SharedPtr< Network > >::iterator i(m_networks.begin()); i != m_networks.end(); ++i) { // NOLINT(hicpp-use-auto,modernize-use-auto,modernize-loop-convert)
  572. for (unsigned int k = 0, j = i->second->config().staticIpCount; k < j; ++k) {
  573. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  574. return false;
  575. }
  576. }
  577. }
  578. if (m_cb.pathCheckFunction) {
  579. return (m_cb.pathCheckFunction(
  580. reinterpret_cast<ZT_Node *>(this),
  581. m_uPtr,
  582. tPtr,
  583. id.address().toInt(),
  584. (const ZT_Identity *)&id,
  585. localSocket,
  586. reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  587. }
  588. return true;
  589. }
  590. bool Node::externalPathLookup(void *tPtr, const Identity &id, int family, InetAddress &addr)
  591. {
  592. if (m_cb.pathLookupFunction) {
  593. return (m_cb.pathLookupFunction(
  594. reinterpret_cast<ZT_Node *>(this),
  595. m_uPtr,
  596. tPtr,
  597. id.address().toInt(),
  598. reinterpret_cast<const ZT_Identity *>(&id),
  599. family,
  600. reinterpret_cast<sockaddr_storage *>(&addr)) == ZT_RESULT_OK);
  601. }
  602. return false;
  603. }
  604. bool Node::localControllerHasAuthorized(const int64_t now, const uint64_t nwid, const Address &addr) const
  605. {
  606. m_localControllerAuthorizations_l.lock();
  607. const int64_t *const at = m_localControllerAuthorizations.get(p_LocalControllerAuth(nwid, addr));
  608. m_localControllerAuthorizations_l.unlock();
  609. if (at)
  610. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  611. return false;
  612. }
  613. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  614. void Node::ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address &destination, const NetworkConfig &nc, bool sendLegacyFormatConfig)
  615. {
  616. m_localControllerAuthorizations_l.lock();
  617. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  618. m_localControllerAuthorizations_l.unlock();
  619. if (destination == RR->identity.address()) {
  620. SharedPtr< Network > n(network(nwid));
  621. if (!n)
  622. return;
  623. n->setConfiguration((void *)0, nc, true);
  624. } else {
  625. Dictionary dconf;
  626. if (nc.toDictionary(dconf)) {
  627. uint64_t configUpdateId = Utils::random();
  628. if (!configUpdateId)
  629. ++configUpdateId;
  630. Vector< uint8_t > ddata;
  631. dconf.encode(ddata);
  632. // TODO
  633. /*
  634. unsigned int chunkIndex = 0;
  635. while (chunkIndex < totalSize) {
  636. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  637. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  638. if (requestPacketId) {
  639. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  640. outp.append(requestPacketId);
  641. }
  642. const unsigned int sigStart = outp.size();
  643. outp.append(nwid);
  644. outp.append((uint16_t)chunkLen);
  645. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  646. outp.append((uint8_t)0); // no flags
  647. outp.append((uint64_t)configUpdateId);
  648. outp.append((uint32_t)totalSize);
  649. outp.append((uint32_t)chunkIndex);
  650. uint8_t sig[256];
  651. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  652. outp.append((uint8_t)1);
  653. outp.append((uint16_t)siglen);
  654. outp.append(sig,siglen);
  655. outp.compress();
  656. RR->sw->send((void *)0,outp,true);
  657. chunkIndex += chunkLen;
  658. }
  659. */
  660. }
  661. }
  662. }
  663. void Node::ncSendRevocation(const Address &destination, const Revocation &rev)
  664. {
  665. if (destination == RR->identity.address()) {
  666. SharedPtr< Network > n(network(rev.networkId()));
  667. if (!n) return;
  668. n->addCredential(nullptr, RR->identity, rev);
  669. } else {
  670. // TODO
  671. /*
  672. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  673. outp.append((uint8_t)0x00);
  674. outp.append((uint16_t)0);
  675. outp.append((uint16_t)0);
  676. outp.append((uint16_t)1);
  677. rev.serialize(outp);
  678. outp.append((uint16_t)0);
  679. RR->sw->send((void *)0,outp,true);
  680. */
  681. }
  682. }
  683. void Node::ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address &destination, NetworkController::ErrorCode errorCode)
  684. {
  685. if (destination == RR->identity.address()) {
  686. SharedPtr< Network > n(network(nwid));
  687. if (!n) return;
  688. switch (errorCode) {
  689. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  690. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  691. n->setNotFound();
  692. break;
  693. case NetworkController::NC_ERROR_ACCESS_DENIED:
  694. n->setAccessDenied();
  695. break;
  696. default:
  697. break;
  698. }
  699. } else if (requestPacketId) {
  700. // TODO
  701. /*
  702. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  703. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  704. outp.append(requestPacketId);
  705. switch(errorCode) {
  706. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  707. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  708. default:
  709. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  710. break;
  711. case NetworkController::NC_ERROR_ACCESS_DENIED:
  712. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  713. break;
  714. }
  715. outp.append(nwid);
  716. RR->sw->send((void *)0,outp,true);
  717. */
  718. } // else we can't send an ERROR() in response to nothing, so discard
  719. }
  720. } // namespace ZeroTier
  721. // C API --------------------------------------------------------------------------------------------------------------
  722. extern "C" {
  723. // These macros make the idiom of passing buffers to outside code via the API work properly even
  724. // if the first address of Buf does not overlap with its data field, since the C++ standard does
  725. // not absolutely guarantee this.
  726. #define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) ))
  727. #define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
  728. void *ZT_getBuffer()
  729. {
  730. // When external code requests a Buf, grab one from the pool (or freshly allocated)
  731. // and return it with its reference count left at zero. It's the responsibility of
  732. // external code to bring it back via freeBuffer() or one of the processX() calls.
  733. // When this occurs it's either sent back to the pool with Buf's delete operator or
  734. // wrapped in a SharedPtr<> to be passed into the core.
  735. try {
  736. return _ZT_BUFTOPTR(new ZeroTier::Buf());
  737. } catch (...) {
  738. return nullptr; // can only happen on out of memory condition
  739. }
  740. }
  741. void ZT_freeBuffer(void *b)
  742. {
  743. if (b)
  744. delete _ZT_PTRTOBUF(b);
  745. }
  746. void ZT_freeQueryResult(void *qr)
  747. {
  748. if (qr)
  749. free(qr);
  750. }
  751. enum ZT_ResultCode ZT_Node_new(ZT_Node **node, void *uptr, void *tptr, const struct ZT_Node_Callbacks *callbacks, int64_t now)
  752. {
  753. *node = (ZT_Node *)0;
  754. try {
  755. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr, tptr, callbacks, now));
  756. return ZT_RESULT_OK;
  757. } catch (std::bad_alloc &exc) {
  758. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  759. } catch (std::runtime_error &exc) {
  760. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  761. } catch (...) {
  762. return ZT_RESULT_ERROR_INTERNAL;
  763. }
  764. }
  765. void ZT_Node_delete(ZT_Node *node, void *tPtr)
  766. {
  767. try {
  768. reinterpret_cast<ZeroTier::Node *>(node)->shutdown(tPtr);
  769. delete (reinterpret_cast<ZeroTier::Node *>(node));
  770. } catch (...) {}
  771. }
  772. enum ZT_ResultCode ZT_Node_processWirePacket(
  773. ZT_Node *node,
  774. void *tptr,
  775. int64_t now,
  776. int64_t localSocket,
  777. const struct sockaddr_storage *remoteAddress,
  778. const void *packetData,
  779. unsigned int packetLength,
  780. int isZtBuffer,
  781. volatile int64_t *nextBackgroundTaskDeadline)
  782. {
  783. try {
  784. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData, packetLength & ZT_BUF_MEM_MASK));
  785. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline);
  786. } catch (std::bad_alloc &exc) {
  787. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  788. } catch (...) {
  789. // "OK" since invalid packets are simply dropped, but the system is still up.
  790. // We should never make it here, but if we did that would be the interpretation.
  791. return ZT_RESULT_OK;
  792. }
  793. }
  794. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  795. ZT_Node *node,
  796. void *tptr,
  797. int64_t now,
  798. uint64_t nwid,
  799. uint64_t sourceMac,
  800. uint64_t destMac,
  801. unsigned int etherType,
  802. unsigned int vlanId,
  803. const void *frameData,
  804. unsigned int frameLength,
  805. int isZtBuffer,
  806. volatile int64_t *nextBackgroundTaskDeadline)
  807. {
  808. try {
  809. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData, frameLength & ZT_BUF_MEM_MASK));
  810. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline);
  811. } catch (std::bad_alloc &exc) {
  812. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  813. } catch (...) {
  814. return ZT_RESULT_ERROR_INTERNAL;
  815. }
  816. }
  817. enum ZT_ResultCode ZT_Node_processHTTPResponse(
  818. ZT_Node *node,
  819. void *tptr,
  820. int64_t now,
  821. void *requestId,
  822. int responseCode,
  823. const char **headerNames,
  824. const char **headerValues,
  825. const void *body,
  826. unsigned int bodySize,
  827. unsigned int flags)
  828. {
  829. try {
  830. return reinterpret_cast<ZeroTier::Node *>(node)->processHTTPResponse(tptr, now, requestId, responseCode, headerNames, headerValues, body, bodySize, flags);
  831. } catch (std::bad_alloc &exc) {
  832. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  833. } catch (...) {
  834. return ZT_RESULT_ERROR_INTERNAL;
  835. }
  836. }
  837. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node, void *tptr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline)
  838. {
  839. try {
  840. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr, now, nextBackgroundTaskDeadline);
  841. } catch (std::bad_alloc &exc) {
  842. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  843. } catch (...) {
  844. return ZT_RESULT_ERROR_INTERNAL;
  845. }
  846. }
  847. enum ZT_ResultCode ZT_Node_join(ZT_Node *node, uint64_t nwid, const ZT_Fingerprint *controllerFingerprint, void *uptr, void *tptr)
  848. {
  849. try {
  850. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid, controllerFingerprint, uptr, tptr);
  851. } catch (std::bad_alloc &exc) {
  852. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  853. } catch (...) {
  854. return ZT_RESULT_ERROR_INTERNAL;
  855. }
  856. }
  857. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node, uint64_t nwid, void **uptr, void *tptr)
  858. {
  859. try {
  860. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid, uptr, tptr);
  861. } catch (std::bad_alloc &exc) {
  862. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  863. } catch (...) {
  864. return ZT_RESULT_ERROR_INTERNAL;
  865. }
  866. }
  867. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node, void *tptr, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  868. {
  869. try {
  870. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr, nwid, multicastGroup, multicastAdi);
  871. } catch (std::bad_alloc &exc) {
  872. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  873. } catch (...) {
  874. return ZT_RESULT_ERROR_INTERNAL;
  875. }
  876. }
  877. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  878. {
  879. try {
  880. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid, multicastGroup, multicastAdi);
  881. } catch (std::bad_alloc &exc) {
  882. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  883. } catch (...) {
  884. return ZT_RESULT_ERROR_INTERNAL;
  885. }
  886. }
  887. enum ZT_ResultCode ZT_Node_addRoot(ZT_Node *node, void *tptr, const ZT_Identity *id)
  888. {
  889. try {
  890. return reinterpret_cast<ZeroTier::Node *>(node)->addRoot(tptr, id);
  891. } catch (std::bad_alloc &exc) {
  892. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  893. } catch (...) {
  894. return ZT_RESULT_ERROR_INTERNAL;
  895. }
  896. }
  897. enum ZT_ResultCode ZT_Node_removeRoot(ZT_Node *node, void *tptr, const uint64_t address)
  898. {
  899. try {
  900. return reinterpret_cast<ZeroTier::Node *>(node)->removeRoot(tptr, address);
  901. } catch (std::bad_alloc &exc) {
  902. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  903. } catch (...) {
  904. return ZT_RESULT_ERROR_INTERNAL;
  905. }
  906. }
  907. uint64_t ZT_Node_address(ZT_Node *node)
  908. {
  909. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  910. }
  911. const ZT_Identity *ZT_Node_identity(ZT_Node *node)
  912. {
  913. return (const ZT_Identity *)(&(reinterpret_cast<ZeroTier::Node *>(node)->identity()));
  914. }
  915. void ZT_Node_status(ZT_Node *node, ZT_NodeStatus *status)
  916. {
  917. try {
  918. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  919. } catch (...) {}
  920. }
  921. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  922. {
  923. try {
  924. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  925. } catch (...) {
  926. return (ZT_PeerList *)0;
  927. }
  928. }
  929. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node, uint64_t nwid)
  930. {
  931. try {
  932. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  933. } catch (...) {
  934. return (ZT_VirtualNetworkConfig *)0;
  935. }
  936. }
  937. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  938. {
  939. try {
  940. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  941. } catch (...) {
  942. return (ZT_VirtualNetworkList *)0;
  943. }
  944. }
  945. int ZT_Node_tryPeer(
  946. ZT_Node *node,
  947. void *tptr,
  948. const ZT_Fingerprint *fp,
  949. const ZT_Endpoint *endpoint,
  950. int retries)
  951. {
  952. try {
  953. return reinterpret_cast<ZeroTier::Node *>(node)->tryPeer(tptr, fp, endpoint, retries);
  954. } catch (...) {
  955. return 0;
  956. }
  957. }
  958. void ZT_Node_setNetworkUserPtr(ZT_Node *node, uint64_t nwid, void *ptr)
  959. {
  960. try {
  961. reinterpret_cast<ZeroTier::Node *>(node)->setNetworkUserPtr(nwid, ptr);
  962. } catch (...) {}
  963. }
  964. void ZT_Node_setInterfaceAddresses(ZT_Node *node, const ZT_InterfaceAddress *addrs, unsigned int addrCount)
  965. {
  966. try {
  967. reinterpret_cast<ZeroTier::Node *>(node)->setInterfaceAddresses(addrs, addrCount);
  968. } catch (...) {}
  969. }
  970. enum ZT_ResultCode ZT_Node_addPeer(
  971. ZT_Node *node,
  972. void *tptr,
  973. const ZT_Identity *id)
  974. {
  975. try {
  976. return reinterpret_cast<ZeroTier::Node *>(node)->addPeer(tptr, id);
  977. } catch (...) {
  978. return ZT_RESULT_ERROR_INTERNAL;
  979. }
  980. }
  981. int ZT_Node_sendUserMessage(ZT_Node *node, void *tptr, uint64_t dest, uint64_t typeId, const void *data, unsigned int len)
  982. {
  983. try {
  984. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr, dest, typeId, data, len);
  985. } catch (...) {
  986. return 0;
  987. }
  988. }
  989. void ZT_Node_setController(ZT_Node *node, void *networkControllerInstance)
  990. {
  991. try {
  992. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  993. } catch (...) {}
  994. }
  995. void ZT_version(int *major, int *minor, int *revision, int *build)
  996. {
  997. if (major)
  998. *major = ZEROTIER_VERSION_MAJOR;
  999. if (minor)
  1000. *minor = ZEROTIER_VERSION_MINOR;
  1001. if (revision)
  1002. *revision = ZEROTIER_VERSION_REVISION;
  1003. if (build)
  1004. *build = ZEROTIER_VERSION_BUILD;
  1005. }
  1006. } // extern "C"