Node.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <stdarg.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include "../version.h"
  32. #include "Constants.hpp"
  33. #include "SharedPtr.hpp"
  34. #include "Node.hpp"
  35. #include "RuntimeEnvironment.hpp"
  36. #include "NetworkController.hpp"
  37. #include "Switch.hpp"
  38. #include "Multicaster.hpp"
  39. #include "Topology.hpp"
  40. #include "Buffer.hpp"
  41. #include "Packet.hpp"
  42. #include "Address.hpp"
  43. #include "Identity.hpp"
  44. #include "SelfAwareness.hpp"
  45. #include "Cluster.hpp"
  46. #include "Network.hpp"
  47. const struct sockaddr_storage ZT_SOCKADDR_NULL = {0};
  48. namespace ZeroTier {
  49. /****************************************************************************/
  50. /* Public Node interface (C++, exposed via CAPI bindings) */
  51. /****************************************************************************/
  52. Node::Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now) :
  53. _RR(this),
  54. RR(&_RR),
  55. _uPtr(uptr),
  56. _networks(8),
  57. _now(now),
  58. _lastPingCheck(0),
  59. _lastHousekeepingRun(0)
  60. {
  61. if (callbacks->version != 0)
  62. throw std::runtime_error("callbacks struct version mismatch");
  63. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  64. Utils::getSecureRandom((void *)_prngState,sizeof(_prngState));
  65. _online = false;
  66. memset(_expectingRepliesToBucketPtr,0,sizeof(_expectingRepliesToBucketPtr));
  67. memset(_expectingRepliesTo,0,sizeof(_expectingRepliesTo));
  68. memset(_lastIdentityVerification,0,sizeof(_lastIdentityVerification));
  69. char tmp[512];
  70. std::string tmp2;
  71. int n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,0,tmp,sizeof(tmp) - 1);
  72. if (n > 0) {
  73. tmp[n] = (char)0;
  74. if (!RR->identity.fromString(tmp))
  75. n = -1;
  76. }
  77. if (n <= 0) {
  78. RR->identity.generate();
  79. tmp2 = RR->identity.toString(true);
  80. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,RR->identity.address().toInt(),tmp2.data(),(unsigned int)tmp2.length());
  81. tmp2 = RR->identity.toString(false);
  82. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,RR->identity.address().toInt(),tmp2.data(),(unsigned int)tmp2.length());
  83. } else {
  84. n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,RR->identity.address().toInt(),tmp,sizeof(tmp) - 1);
  85. if (n > 0) {
  86. tmp[n] = (char)0;
  87. if (RR->identity.toString(false) != tmp)
  88. n = -1;
  89. }
  90. if (n <= 0) {
  91. tmp2 = RR->identity.toString(false);
  92. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,RR->identity.address().toInt(),tmp2.data(),(unsigned int)tmp2.length());
  93. }
  94. }
  95. try {
  96. RR->sw = new Switch(RR);
  97. RR->mc = new Multicaster(RR);
  98. RR->topology = new Topology(RR,tptr);
  99. RR->sa = new SelfAwareness(RR);
  100. } catch ( ... ) {
  101. delete RR->sa;
  102. delete RR->topology;
  103. delete RR->mc;
  104. delete RR->sw;
  105. throw;
  106. }
  107. postEvent(tptr,ZT_EVENT_UP);
  108. }
  109. Node::~Node()
  110. {
  111. Mutex::Lock _l(_networks_m);
  112. _networks.clear(); // destroy all networks before shutdown
  113. delete RR->sa;
  114. delete RR->topology;
  115. delete RR->mc;
  116. delete RR->sw;
  117. #ifdef ZT_ENABLE_CLUSTER
  118. delete RR->cluster;
  119. #endif
  120. }
  121. ZT_ResultCode Node::processStateUpdate(
  122. void *tptr,
  123. ZT_StateObjectType type,
  124. uint64_t id,
  125. const void *data,
  126. unsigned int len)
  127. {
  128. ZT_ResultCode r = ZT_RESULT_OK_IGNORED;
  129. switch(type) {
  130. case ZT_STATE_OBJECT_PEER:
  131. if (len) {
  132. }
  133. break;
  134. case ZT_STATE_OBJECT_PEER_IDENTITY:
  135. if (len) {
  136. }
  137. break;
  138. case ZT_STATE_OBJECT_NETWORK_CONFIG:
  139. if (len <= (ZT_NETWORKCONFIG_DICT_CAPACITY - 1)) {
  140. if (len < 2) {
  141. Mutex::Lock _l(_networks_m);
  142. SharedPtr<Network> &nw = _networks[id];
  143. if (!nw) {
  144. nw = SharedPtr<Network>(new Network(RR,tptr,id,(void *)0,(const NetworkConfig *)0));
  145. r = ZT_RESULT_OK;
  146. }
  147. } else {
  148. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>(reinterpret_cast<const char *>(data),len);
  149. try {
  150. NetworkConfig *nconf = new NetworkConfig();
  151. try {
  152. if (nconf->fromDictionary(*dict)) {
  153. Mutex::Lock _l(_networks_m);
  154. SharedPtr<Network> &nw = _networks[id];
  155. if (nw) {
  156. switch (nw->setConfiguration(tptr,*nconf,false)) {
  157. default:
  158. r = ZT_RESULT_ERROR_BAD_PARAMETER;
  159. break;
  160. case 1:
  161. r = ZT_RESULT_OK_IGNORED;
  162. break;
  163. case 2:
  164. r = ZT_RESULT_OK;
  165. break;
  166. }
  167. } else {
  168. nw = SharedPtr<Network>(new Network(RR,tptr,id,(void *)0,nconf));
  169. }
  170. } else {
  171. r = ZT_RESULT_ERROR_BAD_PARAMETER;
  172. }
  173. } catch ( ... ) {
  174. r = ZT_RESULT_ERROR_BAD_PARAMETER;
  175. }
  176. delete nconf;
  177. } catch ( ... ) {
  178. r = ZT_RESULT_ERROR_BAD_PARAMETER;
  179. }
  180. delete dict;
  181. }
  182. } else {
  183. r = ZT_RESULT_ERROR_BAD_PARAMETER;
  184. }
  185. break;
  186. case ZT_STATE_OBJECT_PLANET:
  187. case ZT_STATE_OBJECT_MOON:
  188. if (len <= ZT_WORLD_MAX_SERIALIZED_LENGTH) {
  189. World w;
  190. try {
  191. w.deserialize(Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH>(data,len));
  192. if (( (w.type() == World::TYPE_MOON)&&(type == ZT_STATE_OBJECT_MOON) )||( (w.type() == World::TYPE_PLANET)&&(type == ZT_STATE_OBJECT_PLANET) )) {
  193. r = (RR->topology->addWorld(tptr,w,false)) ? ZT_RESULT_OK : ZT_RESULT_OK_IGNORED;
  194. }
  195. } catch ( ... ) {
  196. r = ZT_RESULT_ERROR_BAD_PARAMETER;
  197. }
  198. } else {
  199. r = ZT_RESULT_ERROR_BAD_PARAMETER;
  200. }
  201. break;
  202. default: break;
  203. }
  204. return r;
  205. }
  206. ZT_ResultCode Node::processWirePacket(
  207. void *tptr,
  208. uint64_t now,
  209. const struct sockaddr_storage *localAddress,
  210. const struct sockaddr_storage *remoteAddress,
  211. const void *packetData,
  212. unsigned int packetLength,
  213. volatile uint64_t *nextBackgroundTaskDeadline)
  214. {
  215. _now = now;
  216. RR->sw->onRemotePacket(tptr,*(reinterpret_cast<const InetAddress *>(localAddress)),*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  217. return ZT_RESULT_OK;
  218. }
  219. ZT_ResultCode Node::processVirtualNetworkFrame(
  220. void *tptr,
  221. uint64_t now,
  222. uint64_t nwid,
  223. uint64_t sourceMac,
  224. uint64_t destMac,
  225. unsigned int etherType,
  226. unsigned int vlanId,
  227. const void *frameData,
  228. unsigned int frameLength,
  229. volatile uint64_t *nextBackgroundTaskDeadline)
  230. {
  231. _now = now;
  232. SharedPtr<Network> nw(this->network(nwid));
  233. if (nw) {
  234. RR->sw->onLocalEthernet(tptr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  235. return ZT_RESULT_OK;
  236. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  237. }
  238. // Closure used to ping upstream and active/online peers
  239. class _PingPeersThatNeedPing
  240. {
  241. public:
  242. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,void *tPtr,Hashtable< Address,std::vector<InetAddress> > &upstreamsToContact,uint64_t now) :
  243. lastReceiveFromUpstream(0),
  244. RR(renv),
  245. _tPtr(tPtr),
  246. _upstreamsToContact(upstreamsToContact),
  247. _now(now),
  248. _bestCurrentUpstream(RR->topology->getUpstreamPeer())
  249. {
  250. }
  251. uint64_t lastReceiveFromUpstream; // tracks last time we got a packet from an 'upstream' peer like a root or a relay
  252. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  253. {
  254. const std::vector<InetAddress> *const upstreamStableEndpoints = _upstreamsToContact.get(p->address());
  255. if (upstreamStableEndpoints) {
  256. bool contacted = false;
  257. // Upstreams must be pinged constantly over both IPv4 and IPv6 to allow
  258. // them to perform three way handshake introductions for both stacks.
  259. if (!p->doPingAndKeepalive(_tPtr,_now,AF_INET)) {
  260. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  261. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  262. if (addr.ss_family == AF_INET) {
  263. p->sendHELLO(_tPtr,InetAddress(),addr,_now,0);
  264. contacted = true;
  265. break;
  266. }
  267. }
  268. } else contacted = true;
  269. if (!p->doPingAndKeepalive(_tPtr,_now,AF_INET6)) {
  270. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  271. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  272. if (addr.ss_family == AF_INET6) {
  273. p->sendHELLO(_tPtr,InetAddress(),addr,_now,0);
  274. contacted = true;
  275. break;
  276. }
  277. }
  278. } else contacted = true;
  279. if ((!contacted)&&(_bestCurrentUpstream)) {
  280. const SharedPtr<Path> up(_bestCurrentUpstream->getBestPath(_now,true));
  281. if (up)
  282. p->sendHELLO(_tPtr,up->localAddress(),up->address(),_now,up->nextOutgoingCounter());
  283. }
  284. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  285. _upstreamsToContact.erase(p->address()); // erase from upstreams to contact so that we can WHOIS those that remain
  286. } else if (p->isActive(_now)) {
  287. p->doPingAndKeepalive(_tPtr,_now,-1);
  288. }
  289. }
  290. private:
  291. const RuntimeEnvironment *RR;
  292. void *_tPtr;
  293. Hashtable< Address,std::vector<InetAddress> > &_upstreamsToContact;
  294. const uint64_t _now;
  295. const SharedPtr<Peer> _bestCurrentUpstream;
  296. };
  297. ZT_ResultCode Node::processBackgroundTasks(void *tptr,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  298. {
  299. _now = now;
  300. Mutex::Lock bl(_backgroundTasksLock);
  301. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  302. const uint64_t timeSinceLastPingCheck = now - _lastPingCheck;
  303. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  304. try {
  305. _lastPingCheck = now;
  306. // Get networks that need config without leaving mutex locked
  307. std::vector< SharedPtr<Network> > needConfig;
  308. {
  309. Mutex::Lock _l(_networks_m);
  310. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  311. uint64_t *k = (uint64_t *)0;
  312. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  313. while (i.next(k,v)) {
  314. if (((now - (*v)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!(*v)->hasConfig()))
  315. needConfig.push_back(*v);
  316. (*v)->sendUpdatesToMembers(tptr);
  317. }
  318. }
  319. for(std::vector< SharedPtr<Network> >::const_iterator n(needConfig.begin());n!=needConfig.end();++n)
  320. (*n)->requestConfiguration(tptr);
  321. // Do pings and keepalives
  322. Hashtable< Address,std::vector<InetAddress> > upstreamsToContact;
  323. RR->topology->getUpstreamsToContact(upstreamsToContact);
  324. _PingPeersThatNeedPing pfunc(RR,tptr,upstreamsToContact,now);
  325. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  326. // Run WHOIS to create Peer for any upstreams we could not contact (including pending moon seeds)
  327. Hashtable< Address,std::vector<InetAddress> >::Iterator i(upstreamsToContact);
  328. Address *upstreamAddress = (Address *)0;
  329. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  330. while (i.next(upstreamAddress,upstreamStableEndpoints))
  331. RR->sw->requestWhois(tptr,*upstreamAddress);
  332. // Update online status, post status change as event
  333. const bool oldOnline = _online;
  334. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  335. if (oldOnline != _online)
  336. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  337. } catch ( ... ) {
  338. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  339. }
  340. } else {
  341. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  342. }
  343. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  344. try {
  345. _lastHousekeepingRun = now;
  346. RR->topology->clean(now);
  347. RR->sa->clean(now);
  348. RR->mc->clean(now);
  349. } catch ( ... ) {
  350. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  351. }
  352. }
  353. try {
  354. #ifdef ZT_ENABLE_CLUSTER
  355. // If clustering is enabled we have to call cluster->doPeriodicTasks() very often, so we override normal timer deadline behavior
  356. if (RR->cluster) {
  357. RR->sw->doTimerTasks(tptr,now);
  358. RR->cluster->doPeriodicTasks();
  359. *nextBackgroundTaskDeadline = now + ZT_CLUSTER_PERIODIC_TASK_PERIOD; // this is really short so just tick at this rate
  360. } else {
  361. #endif
  362. *nextBackgroundTaskDeadline = now + (uint64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  363. #ifdef ZT_ENABLE_CLUSTER
  364. }
  365. #endif
  366. } catch ( ... ) {
  367. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  368. }
  369. return ZT_RESULT_OK;
  370. }
  371. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  372. {
  373. Mutex::Lock _l(_networks_m);
  374. SharedPtr<Network> &nw = _networks[nwid];
  375. if (!nw)
  376. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  377. return ZT_RESULT_OK;
  378. }
  379. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  380. {
  381. ZT_VirtualNetworkConfig ctmp;
  382. void **nUserPtr = (void **)0;
  383. {
  384. Mutex::Lock _l(_networks_m);
  385. SharedPtr<Network> *nw = _networks.get(nwid);
  386. if (!nw)
  387. return ZT_RESULT_OK;
  388. if (uptr)
  389. *uptr = (*nw)->userPtr();
  390. (*nw)->externalConfig(&ctmp);
  391. (*nw)->destroy();
  392. nUserPtr = (*nw)->userPtr();
  393. }
  394. if (nUserPtr)
  395. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  396. {
  397. Mutex::Lock _l(_networks_m);
  398. _networks.erase(nwid);
  399. }
  400. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,nwid);
  401. return ZT_RESULT_OK;
  402. }
  403. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  404. {
  405. SharedPtr<Network> nw(this->network(nwid));
  406. if (nw) {
  407. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  408. return ZT_RESULT_OK;
  409. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  410. }
  411. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  412. {
  413. SharedPtr<Network> nw(this->network(nwid));
  414. if (nw) {
  415. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  416. return ZT_RESULT_OK;
  417. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  418. }
  419. ZT_ResultCode Node::orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  420. {
  421. RR->topology->addMoon(tptr,moonWorldId,Address(moonSeed));
  422. return ZT_RESULT_OK;
  423. }
  424. ZT_ResultCode Node::deorbit(void *tptr,uint64_t moonWorldId)
  425. {
  426. RR->topology->removeMoon(tptr,moonWorldId);
  427. return ZT_RESULT_OK;
  428. }
  429. uint64_t Node::address() const
  430. {
  431. return RR->identity.address().toInt();
  432. }
  433. void Node::status(ZT_NodeStatus *status) const
  434. {
  435. status->address = RR->identity.address().toInt();
  436. status->publicIdentity = RR->publicIdentityStr.c_str();
  437. status->secretIdentity = RR->secretIdentityStr.c_str();
  438. status->online = _online ? 1 : 0;
  439. }
  440. ZT_PeerList *Node::peers() const
  441. {
  442. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  443. std::sort(peers.begin(),peers.end());
  444. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  445. if (!buf)
  446. return (ZT_PeerList *)0;
  447. ZT_PeerList *pl = (ZT_PeerList *)buf;
  448. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  449. pl->peerCount = 0;
  450. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  451. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  452. p->address = pi->second->address().toInt();
  453. if (pi->second->remoteVersionKnown()) {
  454. p->versionMajor = pi->second->remoteVersionMajor();
  455. p->versionMinor = pi->second->remoteVersionMinor();
  456. p->versionRev = pi->second->remoteVersionRevision();
  457. } else {
  458. p->versionMajor = -1;
  459. p->versionMinor = -1;
  460. p->versionRev = -1;
  461. }
  462. p->latency = pi->second->latency();
  463. p->role = RR->topology->role(pi->second->identity().address());
  464. std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
  465. SharedPtr<Path> bestp(pi->second->getBestPath(_now,false));
  466. p->pathCount = 0;
  467. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  468. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  469. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  470. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  471. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  472. p->paths[p->pathCount].linkQuality = (int)(*path)->linkQuality();
  473. p->paths[p->pathCount].expired = 0;
  474. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  475. ++p->pathCount;
  476. }
  477. }
  478. return pl;
  479. }
  480. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  481. {
  482. Mutex::Lock _l(_networks_m);
  483. const SharedPtr<Network> *nw = _networks.get(nwid);
  484. if (nw) {
  485. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  486. (*nw)->externalConfig(nc);
  487. return nc;
  488. }
  489. return (ZT_VirtualNetworkConfig *)0;
  490. }
  491. ZT_VirtualNetworkList *Node::networks() const
  492. {
  493. Mutex::Lock _l(_networks_m);
  494. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  495. if (!buf)
  496. return (ZT_VirtualNetworkList *)0;
  497. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  498. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  499. nl->networkCount = 0;
  500. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  501. uint64_t *k = (uint64_t *)0;
  502. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  503. while (i.next(k,v))
  504. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  505. return nl;
  506. }
  507. void Node::freeQueryResult(void *qr)
  508. {
  509. if (qr)
  510. ::free(qr);
  511. }
  512. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  513. {
  514. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  515. Mutex::Lock _l(_directPaths_m);
  516. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  517. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  518. return 1;
  519. }
  520. }
  521. return 0;
  522. }
  523. void Node::clearLocalInterfaceAddresses()
  524. {
  525. Mutex::Lock _l(_directPaths_m);
  526. _directPaths.clear();
  527. }
  528. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  529. {
  530. try {
  531. if (RR->identity.address().toInt() != dest) {
  532. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  533. outp.append(typeId);
  534. outp.append(data,len);
  535. outp.compress();
  536. RR->sw->send(tptr,outp,true);
  537. return 1;
  538. }
  539. } catch ( ... ) {}
  540. return 0;
  541. }
  542. void Node::setNetconfMaster(void *networkControllerInstance)
  543. {
  544. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  545. if (networkControllerInstance)
  546. RR->localNetworkController->init(RR->identity,this);
  547. }
  548. /*
  549. ZT_ResultCode Node::clusterInit(
  550. unsigned int myId,
  551. const struct sockaddr_storage *zeroTierPhysicalEndpoints,
  552. unsigned int numZeroTierPhysicalEndpoints,
  553. int x,
  554. int y,
  555. int z,
  556. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  557. void *sendFunctionArg,
  558. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  559. void *addressToLocationFunctionArg)
  560. {
  561. #ifdef ZT_ENABLE_CLUSTER
  562. if (RR->cluster)
  563. return ZT_RESULT_ERROR_BAD_PARAMETER;
  564. std::vector<InetAddress> eps;
  565. for(unsigned int i=0;i<numZeroTierPhysicalEndpoints;++i)
  566. eps.push_back(InetAddress(zeroTierPhysicalEndpoints[i]));
  567. std::sort(eps.begin(),eps.end());
  568. RR->cluster = new Cluster(RR,myId,eps,x,y,z,sendFunction,sendFunctionArg,addressToLocationFunction,addressToLocationFunctionArg);
  569. return ZT_RESULT_OK;
  570. #else
  571. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  572. #endif
  573. }
  574. ZT_ResultCode Node::clusterAddMember(unsigned int memberId)
  575. {
  576. #ifdef ZT_ENABLE_CLUSTER
  577. if (!RR->cluster)
  578. return ZT_RESULT_ERROR_BAD_PARAMETER;
  579. RR->cluster->addMember((uint16_t)memberId);
  580. return ZT_RESULT_OK;
  581. #else
  582. return ZT_RESULT_ERROR_UNSUPPORTED_OPERATION;
  583. #endif
  584. }
  585. void Node::clusterRemoveMember(unsigned int memberId)
  586. {
  587. #ifdef ZT_ENABLE_CLUSTER
  588. if (RR->cluster)
  589. RR->cluster->removeMember((uint16_t)memberId);
  590. #endif
  591. }
  592. void Node::clusterHandleIncomingMessage(const void *msg,unsigned int len)
  593. {
  594. #ifdef ZT_ENABLE_CLUSTER
  595. if (RR->cluster)
  596. RR->cluster->handleIncomingStateMessage(msg,len);
  597. #endif
  598. }
  599. void Node::clusterStatus(ZT_ClusterStatus *cs)
  600. {
  601. if (!cs)
  602. return;
  603. #ifdef ZT_ENABLE_CLUSTER
  604. if (RR->cluster)
  605. RR->cluster->status(*cs);
  606. else
  607. #endif
  608. memset(cs,0,sizeof(ZT_ClusterStatus));
  609. }
  610. */
  611. /****************************************************************************/
  612. /* Node methods used only within node/ */
  613. /****************************************************************************/
  614. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const InetAddress &localAddress,const InetAddress &remoteAddress)
  615. {
  616. if (!Path::isAddressValidForPath(remoteAddress))
  617. return false;
  618. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  619. return false;
  620. {
  621. Mutex::Lock _l(_networks_m);
  622. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  623. uint64_t *k = (uint64_t *)0;
  624. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  625. while (i.next(k,v)) {
  626. if ((*v)->hasConfig()) {
  627. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  628. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  629. return false;
  630. }
  631. }
  632. }
  633. }
  634. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),reinterpret_cast<const struct sockaddr_storage *>(&localAddress),reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  635. }
  636. #ifdef ZT_TRACE
  637. void Node::postTrace(const char *module,unsigned int line,const char *fmt,...)
  638. {
  639. static Mutex traceLock;
  640. va_list ap;
  641. char tmp1[1024],tmp2[1024],tmp3[256];
  642. Mutex::Lock _l(traceLock);
  643. time_t now = (time_t)(_now / 1000ULL);
  644. #ifdef __WINDOWS__
  645. ctime_s(tmp3,sizeof(tmp3),&now);
  646. char *nowstr = tmp3;
  647. #else
  648. char *nowstr = ctime_r(&now,tmp3);
  649. #endif
  650. unsigned long nowstrlen = (unsigned long)strlen(nowstr);
  651. if (nowstr[nowstrlen-1] == '\n')
  652. nowstr[--nowstrlen] = (char)0;
  653. if (nowstr[nowstrlen-1] == '\r')
  654. nowstr[--nowstrlen] = (char)0;
  655. va_start(ap,fmt);
  656. vsnprintf(tmp2,sizeof(tmp2),fmt,ap);
  657. va_end(ap);
  658. tmp2[sizeof(tmp2)-1] = (char)0;
  659. Utils::snprintf(tmp1,sizeof(tmp1),"[%s] %s:%u %s",nowstr,module,line,tmp2);
  660. postEvent((void *)0,ZT_EVENT_TRACE,tmp1);
  661. }
  662. #endif // ZT_TRACE
  663. uint64_t Node::prng()
  664. {
  665. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  666. uint64_t x = _prngState[0];
  667. const uint64_t y = _prngState[1];
  668. _prngState[0] = y;
  669. x ^= x << 23;
  670. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  671. _prngState[1] = z;
  672. return z + y;
  673. }
  674. void Node::setTrustedPaths(const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  675. {
  676. RR->topology->setTrustedPaths(reinterpret_cast<const InetAddress *>(networks),ids,count);
  677. }
  678. World Node::planet() const
  679. {
  680. return RR->topology->planet();
  681. }
  682. std::vector<World> Node::moons() const
  683. {
  684. return RR->topology->moons();
  685. }
  686. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  687. {
  688. if (destination == RR->identity.address()) {
  689. SharedPtr<Network> n(network(nwid));
  690. if (!n) return;
  691. n->setConfiguration((void *)0,nc,true);
  692. } else {
  693. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  694. try {
  695. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  696. uint64_t configUpdateId = prng();
  697. if (!configUpdateId) ++configUpdateId;
  698. const unsigned int totalSize = dconf->sizeBytes();
  699. unsigned int chunkIndex = 0;
  700. while (chunkIndex < totalSize) {
  701. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_UDP_DEFAULT_PAYLOAD_MTU - (ZT_PACKET_IDX_PAYLOAD + 256)));
  702. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  703. if (requestPacketId) {
  704. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  705. outp.append(requestPacketId);
  706. }
  707. const unsigned int sigStart = outp.size();
  708. outp.append(nwid);
  709. outp.append((uint16_t)chunkLen);
  710. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  711. outp.append((uint8_t)0); // no flags
  712. outp.append((uint64_t)configUpdateId);
  713. outp.append((uint32_t)totalSize);
  714. outp.append((uint32_t)chunkIndex);
  715. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  716. outp.append((uint8_t)1);
  717. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  718. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  719. outp.compress();
  720. RR->sw->send((void *)0,outp,true);
  721. chunkIndex += chunkLen;
  722. }
  723. }
  724. delete dconf;
  725. } catch ( ... ) {
  726. delete dconf;
  727. throw;
  728. }
  729. }
  730. }
  731. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  732. {
  733. if (destination == RR->identity.address()) {
  734. SharedPtr<Network> n(network(rev.networkId()));
  735. if (!n) return;
  736. n->addCredential((void *)0,RR->identity.address(),rev);
  737. } else {
  738. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  739. outp.append((uint8_t)0x00);
  740. outp.append((uint16_t)0);
  741. outp.append((uint16_t)0);
  742. outp.append((uint16_t)1);
  743. rev.serialize(outp);
  744. outp.append((uint16_t)0);
  745. RR->sw->send((void *)0,outp,true);
  746. }
  747. }
  748. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  749. {
  750. if (destination == RR->identity.address()) {
  751. SharedPtr<Network> n(network(nwid));
  752. if (!n) return;
  753. switch(errorCode) {
  754. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  755. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  756. n->setNotFound();
  757. break;
  758. case NetworkController::NC_ERROR_ACCESS_DENIED:
  759. n->setAccessDenied();
  760. break;
  761. default: break;
  762. }
  763. } else if (requestPacketId) {
  764. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  765. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  766. outp.append(requestPacketId);
  767. switch(errorCode) {
  768. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  769. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  770. default:
  771. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  772. break;
  773. case NetworkController::NC_ERROR_ACCESS_DENIED:
  774. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  775. break;
  776. }
  777. outp.append(nwid);
  778. RR->sw->send((void *)0,outp,true);
  779. } // else we can't send an ERROR() in response to nothing, so discard
  780. }
  781. } // namespace ZeroTier
  782. /****************************************************************************/
  783. /* CAPI bindings */
  784. /****************************************************************************/
  785. extern "C" {
  786. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,uint64_t now)
  787. {
  788. *node = (ZT_Node *)0;
  789. try {
  790. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  791. return ZT_RESULT_OK;
  792. } catch (std::bad_alloc &exc) {
  793. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  794. } catch (std::runtime_error &exc) {
  795. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  796. } catch ( ... ) {
  797. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  798. }
  799. }
  800. void ZT_Node_delete(ZT_Node *node)
  801. {
  802. try {
  803. delete (reinterpret_cast<ZeroTier::Node *>(node));
  804. } catch ( ... ) {}
  805. }
  806. enum ZT_ResultCode ZT_Node_processStateUpdate(
  807. ZT_Node *node,
  808. void *tptr,
  809. ZT_StateObjectType type,
  810. uint64_t id,
  811. const void *data,
  812. unsigned int len)
  813. {
  814. try {
  815. return reinterpret_cast<ZeroTier::Node *>(node)->processStateUpdate(tptr,type,id,data,len);
  816. } catch (std::bad_alloc &exc) {
  817. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  818. } catch ( ... ) {
  819. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  820. }
  821. }
  822. enum ZT_ResultCode ZT_Node_processWirePacket(
  823. ZT_Node *node,
  824. void *tptr,
  825. uint64_t now,
  826. const struct sockaddr_storage *localAddress,
  827. const struct sockaddr_storage *remoteAddress,
  828. const void *packetData,
  829. unsigned int packetLength,
  830. volatile uint64_t *nextBackgroundTaskDeadline)
  831. {
  832. try {
  833. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localAddress,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  834. } catch (std::bad_alloc &exc) {
  835. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  836. } catch ( ... ) {
  837. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  838. }
  839. }
  840. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  841. ZT_Node *node,
  842. void *tptr,
  843. uint64_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. volatile uint64_t *nextBackgroundTaskDeadline)
  852. {
  853. try {
  854. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  855. } catch (std::bad_alloc &exc) {
  856. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  857. } catch ( ... ) {
  858. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  859. }
  860. }
  861. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,uint64_t now,volatile uint64_t *nextBackgroundTaskDeadline)
  862. {
  863. try {
  864. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  865. } catch (std::bad_alloc &exc) {
  866. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  867. } catch ( ... ) {
  868. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  869. }
  870. }
  871. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  872. {
  873. try {
  874. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  875. } catch (std::bad_alloc &exc) {
  876. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  877. } catch ( ... ) {
  878. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  879. }
  880. }
  881. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  882. {
  883. try {
  884. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  885. } catch (std::bad_alloc &exc) {
  886. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  887. } catch ( ... ) {
  888. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  889. }
  890. }
  891. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  892. {
  893. try {
  894. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  895. } catch (std::bad_alloc &exc) {
  896. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  897. } catch ( ... ) {
  898. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  899. }
  900. }
  901. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  902. {
  903. try {
  904. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  905. } catch (std::bad_alloc &exc) {
  906. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  907. } catch ( ... ) {
  908. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  909. }
  910. }
  911. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  912. {
  913. try {
  914. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  915. } catch ( ... ) {
  916. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  917. }
  918. }
  919. ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  920. {
  921. try {
  922. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  923. } catch ( ... ) {
  924. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  925. }
  926. }
  927. uint64_t ZT_Node_address(ZT_Node *node)
  928. {
  929. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  930. }
  931. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  932. {
  933. try {
  934. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  935. } catch ( ... ) {}
  936. }
  937. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  938. {
  939. try {
  940. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  941. } catch ( ... ) {
  942. return (ZT_PeerList *)0;
  943. }
  944. }
  945. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  946. {
  947. try {
  948. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  949. } catch ( ... ) {
  950. return (ZT_VirtualNetworkConfig *)0;
  951. }
  952. }
  953. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  954. {
  955. try {
  956. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  957. } catch ( ... ) {
  958. return (ZT_VirtualNetworkList *)0;
  959. }
  960. }
  961. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  962. {
  963. try {
  964. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  965. } catch ( ... ) {}
  966. }
  967. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  968. {
  969. try {
  970. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  971. } catch ( ... ) {
  972. return 0;
  973. }
  974. }
  975. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  976. {
  977. try {
  978. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  979. } catch ( ... ) {}
  980. }
  981. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  982. {
  983. try {
  984. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  985. } catch ( ... ) {
  986. return 0;
  987. }
  988. }
  989. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  990. {
  991. try {
  992. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  993. } catch ( ... ) {}
  994. }
  995. void ZT_Node_setTrustedPaths(ZT_Node *node,const struct sockaddr_storage *networks,const uint64_t *ids,unsigned int count)
  996. {
  997. try {
  998. reinterpret_cast<ZeroTier::Node *>(node)->setTrustedPaths(networks,ids,count);
  999. } catch ( ... ) {}
  1000. }
  1001. void ZT_version(int *major,int *minor,int *revision)
  1002. {
  1003. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  1004. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  1005. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  1006. }
  1007. } // extern "C"