Node.cpp 34 KB

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