Node.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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. ZT_ResultCode Node::deleteCertificate(
  523. void *tptr,
  524. const void *serialNo)
  525. {
  526. if (!serialNo)
  527. return ZT_RESULT_ERROR_BAD_PARAMETER;
  528. RR->topology->deleteCertificate(tptr, reinterpret_cast<const uint8_t *>(serialNo));
  529. return ZT_RESULT_OK;
  530. }
  531. struct p_certificateListInternal
  532. {
  533. Vector< SharedPtr< const Certificate > > c;
  534. Vector< unsigned int > t;
  535. };
  536. static void p_freeCertificateList(const void *cl)
  537. {
  538. if (cl) {
  539. reinterpret_cast<const p_certificateListInternal *>(reinterpret_cast<const uint8_t *>(cl) + sizeof(ZT_CertificateList))->~p_certificateListInternal();
  540. free(const_cast<void *>(cl));
  541. }
  542. }
  543. ZT_CertificateList *Node::listCertificates()
  544. {
  545. ZT_CertificateList *const cl = (ZT_CertificateList *)malloc(sizeof(ZT_CertificateList) + sizeof(p_certificateListInternal));
  546. if (!cl)
  547. return nullptr;
  548. p_certificateListInternal *const clint = reinterpret_cast<p_certificateListInternal *>(reinterpret_cast<uint8_t *>(cl) + sizeof(ZT_CertificateList));
  549. new (clint) p_certificateListInternal;
  550. RR->topology->allCerts(clint->c, clint->t);
  551. cl->freeFunction = p_freeCertificateList;
  552. static_assert(sizeof(SharedPtr< const Certificate >) == sizeof(void *), "SharedPtr<> is not just a wrapped pointer");
  553. cl->certs = reinterpret_cast<const ZT_Certificate **>(clint->c.data());
  554. cl->localTrust = clint->t.data();
  555. cl->certCount = (unsigned long)clint->c.size();
  556. return cl;
  557. }
  558. int Node::sendUserMessage(
  559. void *tptr,
  560. uint64_t dest,
  561. uint64_t typeId,
  562. const void *data,
  563. unsigned int len)
  564. {
  565. try {
  566. if (RR->identity.address().toInt() != dest) {
  567. // TODO
  568. /*
  569. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  570. outp.append(typeId);
  571. outp.append(data,len);
  572. outp.compress();
  573. RR->sw->send(tptr,outp,true);
  574. */
  575. return 1;
  576. }
  577. } catch (...) {}
  578. return 0;
  579. }
  580. void Node::setController(void *networkControllerInstance)
  581. {
  582. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  583. if (networkControllerInstance)
  584. RR->localNetworkController->init(RR->identity, this);
  585. }
  586. // Methods used only within the core ----------------------------------------------------------------------------------
  587. Vector< uint8_t > Node::stateObjectGet(void *const tPtr, ZT_StateObjectType type, const uint64_t *id)
  588. {
  589. Vector< uint8_t > r;
  590. if (m_cb.stateGetFunction) {
  591. void *data = nullptr;
  592. void (*freeFunc)(void *) = nullptr;
  593. int l = m_cb.stateGetFunction(
  594. reinterpret_cast<ZT_Node *>(this),
  595. m_uPtr,
  596. tPtr,
  597. type,
  598. id,
  599. &data,
  600. &freeFunc);
  601. if ((l > 0) && (data) && (freeFunc)) {
  602. r.assign(reinterpret_cast<const uint8_t *>(data), reinterpret_cast<const uint8_t *>(data) + l);
  603. freeFunc(data);
  604. }
  605. }
  606. return r;
  607. }
  608. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr, const Identity &id, const int64_t localSocket, const InetAddress &remoteAddress)
  609. {
  610. {
  611. RWMutex::RLock l(m_networks_l);
  612. 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)
  613. for (unsigned int k = 0, j = i->second->config().staticIpCount; k < j; ++k) {
  614. if (i->second->config().staticIps[k].containsAddress(remoteAddress))
  615. return false;
  616. }
  617. }
  618. }
  619. if (m_cb.pathCheckFunction) {
  620. return (m_cb.pathCheckFunction(
  621. reinterpret_cast<ZT_Node *>(this),
  622. m_uPtr,
  623. tPtr,
  624. id.address().toInt(),
  625. (const ZT_Identity *)&id,
  626. localSocket,
  627. reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0);
  628. }
  629. return true;
  630. }
  631. bool Node::externalPathLookup(void *tPtr, const Identity &id, int family, InetAddress &addr)
  632. {
  633. if (m_cb.pathLookupFunction) {
  634. return (m_cb.pathLookupFunction(
  635. reinterpret_cast<ZT_Node *>(this),
  636. m_uPtr,
  637. tPtr,
  638. id.address().toInt(),
  639. reinterpret_cast<const ZT_Identity *>(&id),
  640. family,
  641. reinterpret_cast<sockaddr_storage *>(&addr)) == ZT_RESULT_OK);
  642. }
  643. return false;
  644. }
  645. bool Node::localControllerHasAuthorized(const int64_t now, const uint64_t nwid, const Address &addr) const
  646. {
  647. m_localControllerAuthorizations_l.lock();
  648. Map<Node::p_LocalControllerAuth, int64_t>::const_iterator i(m_localControllerAuthorizations.find(p_LocalControllerAuth(nwid, addr)));
  649. const int64_t at = (i == m_localControllerAuthorizations.end()) ? -1LL : i->second;
  650. m_localControllerAuthorizations_l.unlock();
  651. if (at > 0)
  652. return ((now - at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  653. return false;
  654. }
  655. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  656. void Node::ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address &destination, const NetworkConfig &nc, bool sendLegacyFormatConfig)
  657. {
  658. m_localControllerAuthorizations_l.lock();
  659. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  660. m_localControllerAuthorizations_l.unlock();
  661. if (destination == RR->identity.address()) {
  662. SharedPtr< Network > n(network(nwid));
  663. if (!n)
  664. return;
  665. n->setConfiguration((void *)0, nc, true);
  666. } else {
  667. Dictionary dconf;
  668. if (nc.toDictionary(dconf)) {
  669. uint64_t configUpdateId = Utils::random();
  670. if (!configUpdateId)
  671. ++configUpdateId;
  672. Vector< uint8_t > ddata;
  673. dconf.encode(ddata);
  674. // TODO
  675. /*
  676. unsigned int chunkIndex = 0;
  677. while (chunkIndex < totalSize) {
  678. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  679. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  680. if (requestPacketId) {
  681. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  682. outp.append(requestPacketId);
  683. }
  684. const unsigned int sigStart = outp.size();
  685. outp.append(nwid);
  686. outp.append((uint16_t)chunkLen);
  687. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  688. outp.append((uint8_t)0); // no flags
  689. outp.append((uint64_t)configUpdateId);
  690. outp.append((uint32_t)totalSize);
  691. outp.append((uint32_t)chunkIndex);
  692. uint8_t sig[256];
  693. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  694. outp.append((uint8_t)1);
  695. outp.append((uint16_t)siglen);
  696. outp.append(sig,siglen);
  697. outp.compress();
  698. RR->sw->send((void *)0,outp,true);
  699. chunkIndex += chunkLen;
  700. }
  701. */
  702. }
  703. }
  704. }
  705. void Node::ncSendRevocation(const Address &destination, const RevocationCredential &rev)
  706. {
  707. if (destination == RR->identity.address()) {
  708. SharedPtr< Network > n(network(rev.networkId()));
  709. if (!n) return;
  710. n->addCredential(nullptr, RR->identity, rev);
  711. } else {
  712. // TODO
  713. /*
  714. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  715. outp.append((uint8_t)0x00);
  716. outp.append((uint16_t)0);
  717. outp.append((uint16_t)0);
  718. outp.append((uint16_t)1);
  719. rev.serialize(outp);
  720. outp.append((uint16_t)0);
  721. RR->sw->send((void *)0,outp,true);
  722. */
  723. }
  724. }
  725. void Node::ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address &destination, NetworkController::ErrorCode errorCode)
  726. {
  727. if (destination == RR->identity.address()) {
  728. SharedPtr< Network > n(network(nwid));
  729. if (!n) return;
  730. switch (errorCode) {
  731. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  732. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  733. n->setNotFound();
  734. break;
  735. case NetworkController::NC_ERROR_ACCESS_DENIED:
  736. n->setAccessDenied();
  737. break;
  738. default:
  739. break;
  740. }
  741. } else if (requestPacketId) {
  742. // TODO
  743. /*
  744. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  745. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  746. outp.append(requestPacketId);
  747. switch(errorCode) {
  748. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  749. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  750. default:
  751. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  752. break;
  753. case NetworkController::NC_ERROR_ACCESS_DENIED:
  754. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  755. break;
  756. }
  757. outp.append(nwid);
  758. RR->sw->send((void *)0,outp,true);
  759. */
  760. } // else we can't send an ERROR() in response to nothing, so discard
  761. }
  762. } // namespace ZeroTier
  763. // C API --------------------------------------------------------------------------------------------------------------
  764. extern "C" {
  765. // These macros make the idiom of passing buffers to outside code via the API work properly even
  766. // if the first address of Buf does not overlap with its data field, since the C++ standard does
  767. // not absolutely guarantee this.
  768. #define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) ))
  769. #define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
  770. void *ZT_getBuffer()
  771. {
  772. // When external code requests a Buf, grab one from the pool (or freshly allocated)
  773. // and return it with its reference count left at zero. It's the responsibility of
  774. // external code to bring it back via freeBuffer() or one of the processX() calls.
  775. // When this occurs it's either sent back to the pool with Buf's delete operator or
  776. // wrapped in a SharedPtr<> to be passed into the core.
  777. try {
  778. return _ZT_BUFTOPTR(new ZeroTier::Buf());
  779. } catch (...) {
  780. return nullptr; // can only happen on out of memory condition
  781. }
  782. }
  783. void ZT_freeBuffer(void *b)
  784. {
  785. if (b)
  786. delete _ZT_PTRTOBUF(b);
  787. }
  788. struct p_queryResultBase
  789. {
  790. void (*freeFunction)(const void *);
  791. };
  792. void ZT_freeQueryResult(const void *qr)
  793. {
  794. if ((qr) && (reinterpret_cast<const p_queryResultBase *>(qr)->freeFunction))
  795. reinterpret_cast<const p_queryResultBase *>(qr)->freeFunction(qr);
  796. }
  797. enum ZT_ResultCode ZT_Node_new(ZT_Node **node, void *uptr, void *tptr, const struct ZT_Node_Callbacks *callbacks, int64_t now)
  798. {
  799. *node = (ZT_Node *)0;
  800. try {
  801. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr, tptr, callbacks, now));
  802. return ZT_RESULT_OK;
  803. } catch (std::bad_alloc &exc) {
  804. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  805. } catch (std::runtime_error &exc) {
  806. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  807. } catch (...) {
  808. return ZT_RESULT_ERROR_INTERNAL;
  809. }
  810. }
  811. void ZT_Node_delete(ZT_Node *node, void *tPtr)
  812. {
  813. try {
  814. reinterpret_cast<ZeroTier::Node *>(node)->shutdown(tPtr);
  815. delete (reinterpret_cast<ZeroTier::Node *>(node));
  816. } catch (...) {}
  817. }
  818. enum ZT_ResultCode ZT_Node_processWirePacket(
  819. ZT_Node *node,
  820. void *tptr,
  821. int64_t now,
  822. int64_t localSocket,
  823. const struct sockaddr_storage *remoteAddress,
  824. const void *packetData,
  825. unsigned int packetLength,
  826. int isZtBuffer,
  827. volatile int64_t *nextBackgroundTaskDeadline)
  828. {
  829. try {
  830. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData, packetLength & ZT_BUF_MEM_MASK));
  831. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline);
  832. } catch (std::bad_alloc &exc) {
  833. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  834. } catch (...) {
  835. // "OK" since invalid packets are simply dropped, but the system is still up.
  836. // We should never make it here, but if we did that would be the interpretation.
  837. return ZT_RESULT_OK;
  838. }
  839. }
  840. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  841. ZT_Node *node,
  842. void *tptr,
  843. int64_t now,
  844. uint64_t nwid,
  845. uint64_t sourceMac,
  846. uint64_t destMac,
  847. unsigned int etherType,
  848. unsigned int vlanId,
  849. const void *frameData,
  850. unsigned int frameLength,
  851. int isZtBuffer,
  852. volatile int64_t *nextBackgroundTaskDeadline)
  853. {
  854. try {
  855. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData, frameLength & ZT_BUF_MEM_MASK));
  856. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline);
  857. } catch (std::bad_alloc &exc) {
  858. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  859. } catch (...) {
  860. return ZT_RESULT_ERROR_INTERNAL;
  861. }
  862. }
  863. enum ZT_ResultCode ZT_Node_processHTTPResponse(
  864. ZT_Node *node,
  865. void *tptr,
  866. int64_t now,
  867. void *requestId,
  868. int responseCode,
  869. const char **headerNames,
  870. const char **headerValues,
  871. const void *body,
  872. unsigned int bodySize,
  873. unsigned int flags)
  874. {
  875. try {
  876. return reinterpret_cast<ZeroTier::Node *>(node)->processHTTPResponse(tptr, now, requestId, responseCode, headerNames, headerValues, body, bodySize, flags);
  877. } catch (std::bad_alloc &exc) {
  878. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  879. } catch (...) {
  880. return ZT_RESULT_ERROR_INTERNAL;
  881. }
  882. }
  883. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node, void *tptr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline)
  884. {
  885. try {
  886. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr, now, nextBackgroundTaskDeadline);
  887. } catch (std::bad_alloc &exc) {
  888. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  889. } catch (...) {
  890. return ZT_RESULT_ERROR_INTERNAL;
  891. }
  892. }
  893. enum ZT_ResultCode ZT_Node_join(ZT_Node *node, uint64_t nwid, const ZT_Fingerprint *controllerFingerprint, void *uptr, void *tptr)
  894. {
  895. try {
  896. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid, controllerFingerprint, uptr, tptr);
  897. } catch (std::bad_alloc &exc) {
  898. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  899. } catch (...) {
  900. return ZT_RESULT_ERROR_INTERNAL;
  901. }
  902. }
  903. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node, uint64_t nwid, void **uptr, void *tptr)
  904. {
  905. try {
  906. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid, uptr, tptr);
  907. } catch (std::bad_alloc &exc) {
  908. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  909. } catch (...) {
  910. return ZT_RESULT_ERROR_INTERNAL;
  911. }
  912. }
  913. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node, void *tptr, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  914. {
  915. try {
  916. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr, nwid, multicastGroup, multicastAdi);
  917. } catch (std::bad_alloc &exc) {
  918. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  919. } catch (...) {
  920. return ZT_RESULT_ERROR_INTERNAL;
  921. }
  922. }
  923. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  924. {
  925. try {
  926. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid, multicastGroup, multicastAdi);
  927. } catch (std::bad_alloc &exc) {
  928. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  929. } catch (...) {
  930. return ZT_RESULT_ERROR_INTERNAL;
  931. }
  932. }
  933. uint64_t ZT_Node_address(ZT_Node *node)
  934. {
  935. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  936. }
  937. const ZT_Identity *ZT_Node_identity(ZT_Node *node)
  938. {
  939. return (const ZT_Identity *)(&(reinterpret_cast<ZeroTier::Node *>(node)->identity()));
  940. }
  941. void ZT_Node_status(ZT_Node *node, ZT_NodeStatus *status)
  942. {
  943. try {
  944. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  945. } catch (...) {}
  946. }
  947. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  948. {
  949. try {
  950. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  951. } catch (...) {
  952. return (ZT_PeerList *)0;
  953. }
  954. }
  955. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node, uint64_t nwid)
  956. {
  957. try {
  958. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  959. } catch (...) {
  960. return (ZT_VirtualNetworkConfig *)0;
  961. }
  962. }
  963. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  964. {
  965. try {
  966. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  967. } catch (...) {
  968. return (ZT_VirtualNetworkList *)0;
  969. }
  970. }
  971. int ZT_Node_tryPeer(
  972. ZT_Node *node,
  973. void *tptr,
  974. const ZT_Fingerprint *fp,
  975. const ZT_Endpoint *endpoint,
  976. int retries)
  977. {
  978. try {
  979. return reinterpret_cast<ZeroTier::Node *>(node)->tryPeer(tptr, fp, endpoint, retries);
  980. } catch (...) {
  981. return 0;
  982. }
  983. }
  984. enum ZT_CertificateError ZT_Node_addCertificate(
  985. ZT_Node *node,
  986. void *tptr,
  987. int64_t now,
  988. unsigned int localTrust,
  989. const ZT_Certificate *cert,
  990. const void *certData,
  991. unsigned int certSize)
  992. {
  993. try {
  994. return reinterpret_cast<ZeroTier::Node *>(node)->addCertificate(tptr, now, localTrust, cert, certData, certSize);
  995. } catch (...) {
  996. return ZT_CERTIFICATE_ERROR_INVALID_FORMAT;
  997. }
  998. }
  999. ZT_SDK_API enum ZT_ResultCode ZT_Node_deleteCertificate(
  1000. ZT_Node *node,
  1001. void *tptr,
  1002. const void *serialNo)
  1003. {
  1004. try {
  1005. return reinterpret_cast<ZeroTier::Node *>(node)->deleteCertificate(tptr, serialNo);
  1006. } catch (...) {
  1007. return ZT_RESULT_ERROR_INTERNAL;
  1008. }
  1009. }
  1010. ZT_SDK_API ZT_CertificateList *ZT_Node_listCertificates(ZT_Node *node)
  1011. {
  1012. try {
  1013. return reinterpret_cast<ZeroTier::Node *>(node)->listCertificates();
  1014. } catch (...) {
  1015. return nullptr;
  1016. }
  1017. }
  1018. void ZT_Node_setNetworkUserPtr(ZT_Node *node, uint64_t nwid, void *ptr)
  1019. {
  1020. try {
  1021. reinterpret_cast<ZeroTier::Node *>(node)->setNetworkUserPtr(nwid, ptr);
  1022. } catch (...) {}
  1023. }
  1024. void ZT_Node_setInterfaceAddresses(ZT_Node *node, const ZT_InterfaceAddress *addrs, unsigned int addrCount)
  1025. {
  1026. try {
  1027. reinterpret_cast<ZeroTier::Node *>(node)->setInterfaceAddresses(addrs, addrCount);
  1028. } catch (...) {}
  1029. }
  1030. enum ZT_ResultCode ZT_Node_addPeer(
  1031. ZT_Node *node,
  1032. void *tptr,
  1033. const ZT_Identity *id)
  1034. {
  1035. try {
  1036. return reinterpret_cast<ZeroTier::Node *>(node)->addPeer(tptr, id);
  1037. } catch (...) {
  1038. return ZT_RESULT_ERROR_INTERNAL;
  1039. }
  1040. }
  1041. int ZT_Node_sendUserMessage(ZT_Node *node, void *tptr, uint64_t dest, uint64_t typeId, const void *data, unsigned int len)
  1042. {
  1043. try {
  1044. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr, dest, typeId, data, len);
  1045. } catch (...) {
  1046. return 0;
  1047. }
  1048. }
  1049. void ZT_Node_setController(ZT_Node *node, void *networkControllerInstance)
  1050. {
  1051. try {
  1052. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  1053. } catch (...) {}
  1054. }
  1055. void ZT_version(int *major, int *minor, int *revision, int *build)
  1056. {
  1057. if (major)
  1058. *major = ZEROTIER_VERSION_MAJOR;
  1059. if (minor)
  1060. *minor = ZEROTIER_VERSION_MINOR;
  1061. if (revision)
  1062. *revision = ZEROTIER_VERSION_REVISION;
  1063. if (build)
  1064. *build = ZEROTIER_VERSION_BUILD;
  1065. }
  1066. } // extern "C"