Node.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. Map<Node::p_LocalControllerAuth, int64_t>::const_iterator i(m_localControllerAuthorizations.find(p_LocalControllerAuth(nwid, addr)));
  606. const int64_t at = (i == m_localControllerAuthorizations.end()) ? -1LL : i->second;
  607. m_localControllerAuthorizations_l.unlock();
  608. if (at > 0)
  609. return ((now - at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  610. return false;
  611. }
  612. // Implementation of NetworkController::Sender ------------------------------------------------------------------------
  613. void Node::ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address &destination, const NetworkConfig &nc, bool sendLegacyFormatConfig)
  614. {
  615. m_localControllerAuthorizations_l.lock();
  616. m_localControllerAuthorizations[p_LocalControllerAuth(nwid, destination)] = now();
  617. m_localControllerAuthorizations_l.unlock();
  618. if (destination == RR->identity.address()) {
  619. SharedPtr< Network > n(network(nwid));
  620. if (!n)
  621. return;
  622. n->setConfiguration((void *)0, nc, true);
  623. } else {
  624. Dictionary dconf;
  625. if (nc.toDictionary(dconf)) {
  626. uint64_t configUpdateId = Utils::random();
  627. if (!configUpdateId)
  628. ++configUpdateId;
  629. Vector< uint8_t > ddata;
  630. dconf.encode(ddata);
  631. // TODO
  632. /*
  633. unsigned int chunkIndex = 0;
  634. while (chunkIndex < totalSize) {
  635. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  636. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  637. if (requestPacketId) {
  638. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  639. outp.append(requestPacketId);
  640. }
  641. const unsigned int sigStart = outp.size();
  642. outp.append(nwid);
  643. outp.append((uint16_t)chunkLen);
  644. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  645. outp.append((uint8_t)0); // no flags
  646. outp.append((uint64_t)configUpdateId);
  647. outp.append((uint32_t)totalSize);
  648. outp.append((uint32_t)chunkIndex);
  649. uint8_t sig[256];
  650. const unsigned int siglen = RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart,sig,sizeof(sig));
  651. outp.append((uint8_t)1);
  652. outp.append((uint16_t)siglen);
  653. outp.append(sig,siglen);
  654. outp.compress();
  655. RR->sw->send((void *)0,outp,true);
  656. chunkIndex += chunkLen;
  657. }
  658. */
  659. }
  660. }
  661. }
  662. void Node::ncSendRevocation(const Address &destination, const RevocationCredential &rev)
  663. {
  664. if (destination == RR->identity.address()) {
  665. SharedPtr< Network > n(network(rev.networkId()));
  666. if (!n) return;
  667. n->addCredential(nullptr, RR->identity, rev);
  668. } else {
  669. // TODO
  670. /*
  671. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  672. outp.append((uint8_t)0x00);
  673. outp.append((uint16_t)0);
  674. outp.append((uint16_t)0);
  675. outp.append((uint16_t)1);
  676. rev.serialize(outp);
  677. outp.append((uint16_t)0);
  678. RR->sw->send((void *)0,outp,true);
  679. */
  680. }
  681. }
  682. void Node::ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address &destination, NetworkController::ErrorCode errorCode)
  683. {
  684. if (destination == RR->identity.address()) {
  685. SharedPtr< Network > n(network(nwid));
  686. if (!n) return;
  687. switch (errorCode) {
  688. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  689. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  690. n->setNotFound();
  691. break;
  692. case NetworkController::NC_ERROR_ACCESS_DENIED:
  693. n->setAccessDenied();
  694. break;
  695. default:
  696. break;
  697. }
  698. } else if (requestPacketId) {
  699. // TODO
  700. /*
  701. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  702. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  703. outp.append(requestPacketId);
  704. switch(errorCode) {
  705. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  706. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  707. default:
  708. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  709. break;
  710. case NetworkController::NC_ERROR_ACCESS_DENIED:
  711. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  712. break;
  713. }
  714. outp.append(nwid);
  715. RR->sw->send((void *)0,outp,true);
  716. */
  717. } // else we can't send an ERROR() in response to nothing, so discard
  718. }
  719. } // namespace ZeroTier
  720. // C API --------------------------------------------------------------------------------------------------------------
  721. extern "C" {
  722. // These macros make the idiom of passing buffers to outside code via the API work properly even
  723. // if the first address of Buf does not overlap with its data field, since the C++ standard does
  724. // not absolutely guarantee this.
  725. #define _ZT_PTRTOBUF(p) ((ZeroTier::Buf *)( ((uintptr_t)(p)) - ((uintptr_t)&(((ZeroTier::Buf *)0)->unsafeData[0])) ))
  726. #define _ZT_BUFTOPTR(b) ((void *)(&((b)->unsafeData[0])))
  727. void *ZT_getBuffer()
  728. {
  729. // When external code requests a Buf, grab one from the pool (or freshly allocated)
  730. // and return it with its reference count left at zero. It's the responsibility of
  731. // external code to bring it back via freeBuffer() or one of the processX() calls.
  732. // When this occurs it's either sent back to the pool with Buf's delete operator or
  733. // wrapped in a SharedPtr<> to be passed into the core.
  734. try {
  735. return _ZT_BUFTOPTR(new ZeroTier::Buf());
  736. } catch (...) {
  737. return nullptr; // can only happen on out of memory condition
  738. }
  739. }
  740. void ZT_freeBuffer(void *b)
  741. {
  742. if (b)
  743. delete _ZT_PTRTOBUF(b);
  744. }
  745. void ZT_freeQueryResult(void *qr)
  746. {
  747. if (qr)
  748. free(qr);
  749. }
  750. enum ZT_ResultCode ZT_Node_new(ZT_Node **node, void *uptr, void *tptr, const struct ZT_Node_Callbacks *callbacks, int64_t now)
  751. {
  752. *node = (ZT_Node *)0;
  753. try {
  754. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr, tptr, callbacks, now));
  755. return ZT_RESULT_OK;
  756. } catch (std::bad_alloc &exc) {
  757. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  758. } catch (std::runtime_error &exc) {
  759. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  760. } catch (...) {
  761. return ZT_RESULT_ERROR_INTERNAL;
  762. }
  763. }
  764. void ZT_Node_delete(ZT_Node *node, void *tPtr)
  765. {
  766. try {
  767. reinterpret_cast<ZeroTier::Node *>(node)->shutdown(tPtr);
  768. delete (reinterpret_cast<ZeroTier::Node *>(node));
  769. } catch (...) {}
  770. }
  771. enum ZT_ResultCode ZT_Node_processWirePacket(
  772. ZT_Node *node,
  773. void *tptr,
  774. int64_t now,
  775. int64_t localSocket,
  776. const struct sockaddr_storage *remoteAddress,
  777. const void *packetData,
  778. unsigned int packetLength,
  779. int isZtBuffer,
  780. volatile int64_t *nextBackgroundTaskDeadline)
  781. {
  782. try {
  783. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(packetData) : new ZeroTier::Buf(packetData, packetLength & ZT_BUF_MEM_MASK));
  784. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr, now, localSocket, remoteAddress, buf, packetLength, nextBackgroundTaskDeadline);
  785. } catch (std::bad_alloc &exc) {
  786. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  787. } catch (...) {
  788. // "OK" since invalid packets are simply dropped, but the system is still up.
  789. // We should never make it here, but if we did that would be the interpretation.
  790. return ZT_RESULT_OK;
  791. }
  792. }
  793. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  794. ZT_Node *node,
  795. void *tptr,
  796. int64_t now,
  797. uint64_t nwid,
  798. uint64_t sourceMac,
  799. uint64_t destMac,
  800. unsigned int etherType,
  801. unsigned int vlanId,
  802. const void *frameData,
  803. unsigned int frameLength,
  804. int isZtBuffer,
  805. volatile int64_t *nextBackgroundTaskDeadline)
  806. {
  807. try {
  808. ZeroTier::SharedPtr< ZeroTier::Buf > buf((isZtBuffer) ? _ZT_PTRTOBUF(frameData) : new ZeroTier::Buf(frameData, frameLength & ZT_BUF_MEM_MASK));
  809. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr, now, nwid, sourceMac, destMac, etherType, vlanId, buf, frameLength, nextBackgroundTaskDeadline);
  810. } catch (std::bad_alloc &exc) {
  811. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  812. } catch (...) {
  813. return ZT_RESULT_ERROR_INTERNAL;
  814. }
  815. }
  816. enum ZT_ResultCode ZT_Node_processHTTPResponse(
  817. ZT_Node *node,
  818. void *tptr,
  819. int64_t now,
  820. void *requestId,
  821. int responseCode,
  822. const char **headerNames,
  823. const char **headerValues,
  824. const void *body,
  825. unsigned int bodySize,
  826. unsigned int flags)
  827. {
  828. try {
  829. return reinterpret_cast<ZeroTier::Node *>(node)->processHTTPResponse(tptr, now, requestId, responseCode, headerNames, headerValues, body, bodySize, flags);
  830. } catch (std::bad_alloc &exc) {
  831. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  832. } catch (...) {
  833. return ZT_RESULT_ERROR_INTERNAL;
  834. }
  835. }
  836. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node, void *tptr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline)
  837. {
  838. try {
  839. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr, now, nextBackgroundTaskDeadline);
  840. } catch (std::bad_alloc &exc) {
  841. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  842. } catch (...) {
  843. return ZT_RESULT_ERROR_INTERNAL;
  844. }
  845. }
  846. enum ZT_ResultCode ZT_Node_join(ZT_Node *node, uint64_t nwid, const ZT_Fingerprint *controllerFingerprint, void *uptr, void *tptr)
  847. {
  848. try {
  849. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid, controllerFingerprint, uptr, tptr);
  850. } catch (std::bad_alloc &exc) {
  851. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  852. } catch (...) {
  853. return ZT_RESULT_ERROR_INTERNAL;
  854. }
  855. }
  856. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node, uint64_t nwid, void **uptr, void *tptr)
  857. {
  858. try {
  859. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid, uptr, tptr);
  860. } catch (std::bad_alloc &exc) {
  861. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  862. } catch (...) {
  863. return ZT_RESULT_ERROR_INTERNAL;
  864. }
  865. }
  866. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node, void *tptr, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  867. {
  868. try {
  869. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr, nwid, multicastGroup, multicastAdi);
  870. } catch (std::bad_alloc &exc) {
  871. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  872. } catch (...) {
  873. return ZT_RESULT_ERROR_INTERNAL;
  874. }
  875. }
  876. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi)
  877. {
  878. try {
  879. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid, multicastGroup, multicastAdi);
  880. } catch (std::bad_alloc &exc) {
  881. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  882. } catch (...) {
  883. return ZT_RESULT_ERROR_INTERNAL;
  884. }
  885. }
  886. enum ZT_ResultCode ZT_Node_addRoot(ZT_Node *node, void *tptr, const ZT_Identity *id)
  887. {
  888. try {
  889. return reinterpret_cast<ZeroTier::Node *>(node)->addRoot(tptr, id);
  890. } catch (std::bad_alloc &exc) {
  891. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  892. } catch (...) {
  893. return ZT_RESULT_ERROR_INTERNAL;
  894. }
  895. }
  896. enum ZT_ResultCode ZT_Node_removeRoot(ZT_Node *node, void *tptr, const uint64_t address)
  897. {
  898. try {
  899. return reinterpret_cast<ZeroTier::Node *>(node)->removeRoot(tptr, address);
  900. } catch (std::bad_alloc &exc) {
  901. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  902. } catch (...) {
  903. return ZT_RESULT_ERROR_INTERNAL;
  904. }
  905. }
  906. uint64_t ZT_Node_address(ZT_Node *node)
  907. {
  908. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  909. }
  910. const ZT_Identity *ZT_Node_identity(ZT_Node *node)
  911. {
  912. return (const ZT_Identity *)(&(reinterpret_cast<ZeroTier::Node *>(node)->identity()));
  913. }
  914. void ZT_Node_status(ZT_Node *node, ZT_NodeStatus *status)
  915. {
  916. try {
  917. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  918. } catch (...) {}
  919. }
  920. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  921. {
  922. try {
  923. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  924. } catch (...) {
  925. return (ZT_PeerList *)0;
  926. }
  927. }
  928. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node, uint64_t nwid)
  929. {
  930. try {
  931. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  932. } catch (...) {
  933. return (ZT_VirtualNetworkConfig *)0;
  934. }
  935. }
  936. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  937. {
  938. try {
  939. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  940. } catch (...) {
  941. return (ZT_VirtualNetworkList *)0;
  942. }
  943. }
  944. int ZT_Node_tryPeer(
  945. ZT_Node *node,
  946. void *tptr,
  947. const ZT_Fingerprint *fp,
  948. const ZT_Endpoint *endpoint,
  949. int retries)
  950. {
  951. try {
  952. return reinterpret_cast<ZeroTier::Node *>(node)->tryPeer(tptr, fp, endpoint, retries);
  953. } catch (...) {
  954. return 0;
  955. }
  956. }
  957. void ZT_Node_setNetworkUserPtr(ZT_Node *node, uint64_t nwid, void *ptr)
  958. {
  959. try {
  960. reinterpret_cast<ZeroTier::Node *>(node)->setNetworkUserPtr(nwid, ptr);
  961. } catch (...) {}
  962. }
  963. void ZT_Node_setInterfaceAddresses(ZT_Node *node, const ZT_InterfaceAddress *addrs, unsigned int addrCount)
  964. {
  965. try {
  966. reinterpret_cast<ZeroTier::Node *>(node)->setInterfaceAddresses(addrs, addrCount);
  967. } catch (...) {}
  968. }
  969. enum ZT_ResultCode ZT_Node_addPeer(
  970. ZT_Node *node,
  971. void *tptr,
  972. const ZT_Identity *id)
  973. {
  974. try {
  975. return reinterpret_cast<ZeroTier::Node *>(node)->addPeer(tptr, id);
  976. } catch (...) {
  977. return ZT_RESULT_ERROR_INTERNAL;
  978. }
  979. }
  980. int ZT_Node_sendUserMessage(ZT_Node *node, void *tptr, uint64_t dest, uint64_t typeId, const void *data, unsigned int len)
  981. {
  982. try {
  983. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr, dest, typeId, data, len);
  984. } catch (...) {
  985. return 0;
  986. }
  987. }
  988. void ZT_Node_setController(ZT_Node *node, void *networkControllerInstance)
  989. {
  990. try {
  991. reinterpret_cast<ZeroTier::Node *>(node)->setController(networkControllerInstance);
  992. } catch (...) {}
  993. }
  994. void ZT_version(int *major, int *minor, int *revision, int *build)
  995. {
  996. if (major)
  997. *major = ZEROTIER_VERSION_MAJOR;
  998. if (minor)
  999. *minor = ZEROTIER_VERSION_MINOR;
  1000. if (revision)
  1001. *revision = ZEROTIER_VERSION_REVISION;
  1002. if (build)
  1003. *build = ZEROTIER_VERSION_BUILD;
  1004. }
  1005. } // extern "C"