Node.cpp 33 KB

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