Node.cpp 34 KB

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