Node.cpp 34 KB

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