2
0

Node.cpp 33 KB

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