Node.cpp 34 KB

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