Node.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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. #include "Trace.hpp"
  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,int64_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 ZT_EXCEPTION_INVALID_ARGUMENT;
  62. memcpy(&_cb,callbacks,sizeof(ZT_Node_Callbacks));
  63. // Initialize non-cryptographic PRNG from a good random source
  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. uint64_t idtmp[2];
  70. idtmp[0] = 0; idtmp[1] = 0;
  71. char tmp[2048];
  72. int n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,tmp,sizeof(tmp) - 1);
  73. if (n > 0) {
  74. tmp[n] = (char)0;
  75. if (RR->identity.fromString(tmp)) {
  76. RR->identity.toString(false,RR->publicIdentityStr);
  77. RR->identity.toString(true,RR->secretIdentityStr);
  78. } else {
  79. n = -1;
  80. }
  81. }
  82. if (n <= 0) {
  83. RR->identity.generate();
  84. RR->identity.toString(false,RR->publicIdentityStr);
  85. RR->identity.toString(true,RR->secretIdentityStr);
  86. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  87. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_SECRET,idtmp,RR->secretIdentityStr,(unsigned int)strlen(RR->secretIdentityStr));
  88. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  89. } else {
  90. idtmp[0] = RR->identity.address().toInt(); idtmp[1] = 0;
  91. n = stateObjectGet(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,tmp,sizeof(tmp) - 1);
  92. if ((n > 0)&&(n < (int)sizeof(RR->publicIdentityStr))&&(n < (int)sizeof(tmp))) {
  93. if (memcmp(tmp,RR->publicIdentityStr,n))
  94. stateObjectPut(tptr,ZT_STATE_OBJECT_IDENTITY_PUBLIC,idtmp,RR->publicIdentityStr,(unsigned int)strlen(RR->publicIdentityStr));
  95. }
  96. }
  97. try {
  98. RR->t = new Trace(RR);
  99. RR->sw = new Switch(RR);
  100. RR->mc = new Multicaster(RR);
  101. RR->topology = new Topology(RR,tptr);
  102. RR->sa = new SelfAwareness(RR);
  103. } catch ( ... ) {
  104. delete RR->sa;
  105. delete RR->topology;
  106. delete RR->mc;
  107. delete RR->sw;
  108. delete RR->t;
  109. throw;
  110. }
  111. postEvent(tptr,ZT_EVENT_UP);
  112. }
  113. Node::~Node()
  114. {
  115. {
  116. Mutex::Lock _l(_networks_m);
  117. _networks.clear(); // destroy all networks before shutdown
  118. }
  119. delete RR->sa;
  120. delete RR->topology;
  121. delete RR->mc;
  122. delete RR->sw;
  123. delete RR->t;
  124. }
  125. ZT_ResultCode Node::processWirePacket(
  126. void *tptr,
  127. int64_t now,
  128. int64_t localSocket,
  129. const struct sockaddr_storage *remoteAddress,
  130. const void *packetData,
  131. unsigned int packetLength,
  132. volatile int64_t *nextBackgroundTaskDeadline)
  133. {
  134. _now = now;
  135. RR->sw->onRemotePacket(tptr,localSocket,*(reinterpret_cast<const InetAddress *>(remoteAddress)),packetData,packetLength);
  136. return ZT_RESULT_OK;
  137. }
  138. ZT_ResultCode Node::processVirtualNetworkFrame(
  139. void *tptr,
  140. int64_t now,
  141. uint64_t nwid,
  142. uint64_t sourceMac,
  143. uint64_t destMac,
  144. unsigned int etherType,
  145. unsigned int vlanId,
  146. const void *frameData,
  147. unsigned int frameLength,
  148. volatile int64_t *nextBackgroundTaskDeadline)
  149. {
  150. _now = now;
  151. SharedPtr<Network> nw(this->network(nwid));
  152. if (nw) {
  153. RR->sw->onLocalEthernet(tptr,nw,MAC(sourceMac),MAC(destMac),etherType,vlanId,frameData,frameLength);
  154. return ZT_RESULT_OK;
  155. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  156. }
  157. // Closure used to ping upstream and active/online peers
  158. class _PingPeersThatNeedPing
  159. {
  160. public:
  161. _PingPeersThatNeedPing(const RuntimeEnvironment *renv,void *tPtr,Hashtable< Address,std::vector<InetAddress> > &upstreamsToContact,int64_t now) :
  162. lastReceiveFromUpstream(0),
  163. RR(renv),
  164. _tPtr(tPtr),
  165. _upstreamsToContact(upstreamsToContact),
  166. _now(now),
  167. _bestCurrentUpstream(RR->topology->getUpstreamPeer())
  168. {
  169. }
  170. int64_t lastReceiveFromUpstream; // tracks last time we got a packet from an 'upstream' peer like a root or a relay
  171. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  172. {
  173. const std::vector<InetAddress> *const upstreamStableEndpoints = _upstreamsToContact.get(p->address());
  174. if (upstreamStableEndpoints) {
  175. // Upstreams must be pinged constantly over both IPv4 and IPv6 to allow
  176. // them to perform three way handshake introductions for both stacks.
  177. const unsigned int sent = p->doPingAndKeepalive(_tPtr,_now);
  178. bool contacted = (sent != 0);
  179. if ((sent & 0x1) == 0) { // bit 0x1 == IPv4 sent
  180. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  181. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  182. if (addr.ss_family == AF_INET) {
  183. p->sendHELLO(_tPtr,-1,addr,_now,0);
  184. contacted = true;
  185. break;
  186. }
  187. }
  188. }
  189. if ((sent & 0x2) == 0) { // bit 0x2 == IPv6 sent
  190. for(unsigned long k=0,ptr=(unsigned long)RR->node->prng();k<(unsigned long)upstreamStableEndpoints->size();++k) {
  191. const InetAddress &addr = (*upstreamStableEndpoints)[ptr++ % upstreamStableEndpoints->size()];
  192. if (addr.ss_family == AF_INET6) {
  193. p->sendHELLO(_tPtr,-1,addr,_now,0);
  194. contacted = true;
  195. break;
  196. }
  197. }
  198. }
  199. // If we have no memoized addresses for this upstream peer, attempt to contact
  200. // it indirectly so we will be introduced.
  201. if ((!contacted)&&(_bestCurrentUpstream)) {
  202. const SharedPtr<Path> up(_bestCurrentUpstream->getBestPath(_now,true));
  203. if (up)
  204. p->sendHELLO(_tPtr,up->localSocket(),up->address(),_now,up->nextOutgoingCounter());
  205. }
  206. lastReceiveFromUpstream = std::max(p->lastReceive(),lastReceiveFromUpstream);
  207. _upstreamsToContact.erase(p->address()); // after this we'll WHOIS all upstreams that remain
  208. } else if (p->isActive(_now)) {
  209. // Regular non-upstream nodes get pinged if they appear active.
  210. p->doPingAndKeepalive(_tPtr,_now);
  211. }
  212. }
  213. private:
  214. const RuntimeEnvironment *RR;
  215. void *_tPtr;
  216. Hashtable< Address,std::vector<InetAddress> > &_upstreamsToContact;
  217. const int64_t _now;
  218. const SharedPtr<Peer> _bestCurrentUpstream;
  219. };
  220. ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  221. {
  222. _now = now;
  223. Mutex::Lock bl(_backgroundTasksLock);
  224. unsigned long timeUntilNextPingCheck = ZT_PING_CHECK_INVERVAL;
  225. const int64_t timeSinceLastPingCheck = now - _lastPingCheck;
  226. if (timeSinceLastPingCheck >= ZT_PING_CHECK_INVERVAL) {
  227. try {
  228. _lastPingCheck = now;
  229. // Do pings and keepalives
  230. Hashtable< Address,std::vector<InetAddress> > upstreamsToContact;
  231. RR->topology->getUpstreamsToContact(upstreamsToContact);
  232. _PingPeersThatNeedPing pfunc(RR,tptr,upstreamsToContact,now);
  233. RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
  234. // Run WHOIS to create Peer for any upstreams we could not contact (including pending moon seeds)
  235. Hashtable< Address,std::vector<InetAddress> >::Iterator i(upstreamsToContact);
  236. Address *upstreamAddress = (Address *)0;
  237. std::vector<InetAddress> *upstreamStableEndpoints = (std::vector<InetAddress> *)0;
  238. while (i.next(upstreamAddress,upstreamStableEndpoints))
  239. RR->sw->requestWhois(tptr,now,*upstreamAddress);
  240. // Get networks that need config without leaving mutex locked
  241. {
  242. std::vector< std::pair< SharedPtr<Network>,bool > > nwl;
  243. {
  244. Mutex::Lock _l(_networks_m);
  245. nwl.reserve(_networks.size()+1);
  246. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  247. uint64_t *k = (uint64_t *)0;
  248. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  249. while (i.next(k,v))
  250. nwl.push_back( std::pair< SharedPtr<Network>,bool >(*v,(((now - (*v)->lastConfigUpdate()) >= ZT_NETWORK_AUTOCONF_DELAY)||(!(*v)->hasConfig()))) );
  251. }
  252. for(std::vector< std::pair< SharedPtr<Network>,bool > >::const_iterator n(nwl.begin());n!=nwl.end();++n) {
  253. if (n->second)
  254. n->first->requestConfiguration(tptr);
  255. n->first->sendUpdatesToMembers(tptr);
  256. }
  257. }
  258. // Update online status, post status change as event
  259. const bool oldOnline = _online;
  260. _online = (((now - pfunc.lastReceiveFromUpstream) < ZT_PEER_ACTIVITY_TIMEOUT)||(RR->topology->amRoot()));
  261. if (oldOnline != _online)
  262. postEvent(tptr,_online ? ZT_EVENT_ONLINE : ZT_EVENT_OFFLINE);
  263. } catch ( ... ) {
  264. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  265. }
  266. } else {
  267. timeUntilNextPingCheck -= (unsigned long)timeSinceLastPingCheck;
  268. }
  269. if ((now - _lastHousekeepingRun) >= ZT_HOUSEKEEPING_PERIOD) {
  270. _lastHousekeepingRun = now;
  271. try {
  272. RR->topology->doPeriodicTasks(tptr,now);
  273. RR->sa->clean(now);
  274. RR->mc->clean(now);
  275. } catch ( ... ) {
  276. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  277. }
  278. }
  279. try {
  280. *nextBackgroundTaskDeadline = now + (int64_t)std::max(std::min(timeUntilNextPingCheck,RR->sw->doTimerTasks(tptr,now)),(unsigned long)ZT_CORE_TIMER_TASK_GRANULARITY);
  281. } catch ( ... ) {
  282. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  283. }
  284. return ZT_RESULT_OK;
  285. }
  286. ZT_ResultCode Node::join(uint64_t nwid,void *uptr,void *tptr)
  287. {
  288. Mutex::Lock _l(_networks_m);
  289. SharedPtr<Network> &nw = _networks[nwid];
  290. if (!nw)
  291. nw = SharedPtr<Network>(new Network(RR,tptr,nwid,uptr,(const NetworkConfig *)0));
  292. return ZT_RESULT_OK;
  293. }
  294. ZT_ResultCode Node::leave(uint64_t nwid,void **uptr,void *tptr)
  295. {
  296. ZT_VirtualNetworkConfig ctmp;
  297. void **nUserPtr = (void **)0;
  298. {
  299. Mutex::Lock _l(_networks_m);
  300. SharedPtr<Network> *nw = _networks.get(nwid);
  301. if (!nw)
  302. return ZT_RESULT_OK;
  303. if (uptr)
  304. *uptr = (*nw)->userPtr();
  305. (*nw)->externalConfig(&ctmp);
  306. (*nw)->destroy();
  307. nUserPtr = (*nw)->userPtr();
  308. }
  309. if (nUserPtr)
  310. RR->node->configureVirtualNetworkPort(tptr,nwid,nUserPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  311. {
  312. Mutex::Lock _l(_networks_m);
  313. _networks.erase(nwid);
  314. }
  315. uint64_t tmp[2];
  316. tmp[0] = nwid; tmp[1] = 0;
  317. RR->node->stateObjectDelete(tptr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp);
  318. return ZT_RESULT_OK;
  319. }
  320. ZT_ResultCode Node::multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  321. {
  322. SharedPtr<Network> nw(this->network(nwid));
  323. if (nw) {
  324. nw->multicastSubscribe(tptr,MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  325. return ZT_RESULT_OK;
  326. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  327. }
  328. ZT_ResultCode Node::multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  329. {
  330. SharedPtr<Network> nw(this->network(nwid));
  331. if (nw) {
  332. nw->multicastUnsubscribe(MulticastGroup(MAC(multicastGroup),(uint32_t)(multicastAdi & 0xffffffff)));
  333. return ZT_RESULT_OK;
  334. } else return ZT_RESULT_ERROR_NETWORK_NOT_FOUND;
  335. }
  336. ZT_ResultCode Node::orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  337. {
  338. RR->topology->addMoon(tptr,moonWorldId,Address(moonSeed));
  339. return ZT_RESULT_OK;
  340. }
  341. ZT_ResultCode Node::deorbit(void *tptr,uint64_t moonWorldId)
  342. {
  343. RR->topology->removeMoon(tptr,moonWorldId);
  344. return ZT_RESULT_OK;
  345. }
  346. uint64_t Node::address() const
  347. {
  348. return RR->identity.address().toInt();
  349. }
  350. void Node::status(ZT_NodeStatus *status) const
  351. {
  352. status->address = RR->identity.address().toInt();
  353. status->publicIdentity = RR->publicIdentityStr;
  354. status->secretIdentity = RR->secretIdentityStr;
  355. status->online = _online ? 1 : 0;
  356. }
  357. ZT_PeerList *Node::peers() const
  358. {
  359. std::vector< std::pair< Address,SharedPtr<Peer> > > peers(RR->topology->allPeers());
  360. std::sort(peers.begin(),peers.end());
  361. char *buf = (char *)::malloc(sizeof(ZT_PeerList) + (sizeof(ZT_Peer) * peers.size()));
  362. if (!buf)
  363. return (ZT_PeerList *)0;
  364. ZT_PeerList *pl = (ZT_PeerList *)buf;
  365. pl->peers = (ZT_Peer *)(buf + sizeof(ZT_PeerList));
  366. pl->peerCount = 0;
  367. for(std::vector< std::pair< Address,SharedPtr<Peer> > >::iterator pi(peers.begin());pi!=peers.end();++pi) {
  368. ZT_Peer *p = &(pl->peers[pl->peerCount++]);
  369. p->address = pi->second->address().toInt();
  370. if (pi->second->remoteVersionKnown()) {
  371. p->versionMajor = pi->second->remoteVersionMajor();
  372. p->versionMinor = pi->second->remoteVersionMinor();
  373. p->versionRev = pi->second->remoteVersionRevision();
  374. } else {
  375. p->versionMajor = -1;
  376. p->versionMinor = -1;
  377. p->versionRev = -1;
  378. }
  379. p->latency = pi->second->latency(_now);
  380. p->role = RR->topology->role(pi->second->identity().address());
  381. std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
  382. SharedPtr<Path> bestp(pi->second->getBestPath(_now,false));
  383. p->pathCount = 0;
  384. for(std::vector< SharedPtr<Path> >::iterator path(paths.begin());path!=paths.end();++path) {
  385. memcpy(&(p->paths[p->pathCount].address),&((*path)->address()),sizeof(struct sockaddr_storage));
  386. p->paths[p->pathCount].lastSend = (*path)->lastOut();
  387. p->paths[p->pathCount].lastReceive = (*path)->lastIn();
  388. p->paths[p->pathCount].trustedPathId = RR->topology->getOutboundPathTrust((*path)->address());
  389. p->paths[p->pathCount].linkQuality = (int)(*path)->linkQuality();
  390. p->paths[p->pathCount].expired = 0;
  391. p->paths[p->pathCount].preferred = ((*path) == bestp) ? 1 : 0;
  392. ++p->pathCount;
  393. }
  394. }
  395. return pl;
  396. }
  397. ZT_VirtualNetworkConfig *Node::networkConfig(uint64_t nwid) const
  398. {
  399. Mutex::Lock _l(_networks_m);
  400. const SharedPtr<Network> *nw = _networks.get(nwid);
  401. if (nw) {
  402. ZT_VirtualNetworkConfig *nc = (ZT_VirtualNetworkConfig *)::malloc(sizeof(ZT_VirtualNetworkConfig));
  403. (*nw)->externalConfig(nc);
  404. return nc;
  405. }
  406. return (ZT_VirtualNetworkConfig *)0;
  407. }
  408. ZT_VirtualNetworkList *Node::networks() const
  409. {
  410. Mutex::Lock _l(_networks_m);
  411. char *buf = (char *)::malloc(sizeof(ZT_VirtualNetworkList) + (sizeof(ZT_VirtualNetworkConfig) * _networks.size()));
  412. if (!buf)
  413. return (ZT_VirtualNetworkList *)0;
  414. ZT_VirtualNetworkList *nl = (ZT_VirtualNetworkList *)buf;
  415. nl->networks = (ZT_VirtualNetworkConfig *)(buf + sizeof(ZT_VirtualNetworkList));
  416. nl->networkCount = 0;
  417. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > *>(&_networks));
  418. uint64_t *k = (uint64_t *)0;
  419. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  420. while (i.next(k,v))
  421. (*v)->externalConfig(&(nl->networks[nl->networkCount++]));
  422. return nl;
  423. }
  424. void Node::freeQueryResult(void *qr)
  425. {
  426. if (qr)
  427. ::free(qr);
  428. }
  429. int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
  430. {
  431. if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
  432. Mutex::Lock _l(_directPaths_m);
  433. if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
  434. _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
  435. return 1;
  436. }
  437. }
  438. return 0;
  439. }
  440. void Node::clearLocalInterfaceAddresses()
  441. {
  442. Mutex::Lock _l(_directPaths_m);
  443. _directPaths.clear();
  444. }
  445. int Node::sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  446. {
  447. try {
  448. if (RR->identity.address().toInt() != dest) {
  449. Packet outp(Address(dest),RR->identity.address(),Packet::VERB_USER_MESSAGE);
  450. outp.append(typeId);
  451. outp.append(data,len);
  452. outp.compress();
  453. RR->sw->send(tptr,outp,true);
  454. return 1;
  455. }
  456. } catch ( ... ) {}
  457. return 0;
  458. }
  459. void Node::setNetconfMaster(void *networkControllerInstance)
  460. {
  461. RR->localNetworkController = reinterpret_cast<NetworkController *>(networkControllerInstance);
  462. if (networkControllerInstance)
  463. RR->localNetworkController->init(RR->identity,this);
  464. }
  465. /****************************************************************************/
  466. /* Node methods used only within node/ */
  467. /****************************************************************************/
  468. bool Node::shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress)
  469. {
  470. if (!Path::isAddressValidForPath(remoteAddress))
  471. return false;
  472. if (RR->topology->isProhibitedEndpoint(ztaddr,remoteAddress))
  473. return false;
  474. {
  475. Mutex::Lock _l(_networks_m);
  476. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(_networks);
  477. uint64_t *k = (uint64_t *)0;
  478. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  479. while (i.next(k,v)) {
  480. if ((*v)->hasConfig()) {
  481. for(unsigned int k=0;k<(*v)->config().staticIpCount;++k) {
  482. if ((*v)->config().staticIps[k].containsAddress(remoteAddress))
  483. return false;
  484. }
  485. }
  486. }
  487. }
  488. return ( (_cb.pathCheckFunction) ? (_cb.pathCheckFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),localSocket,reinterpret_cast<const struct sockaddr_storage *>(&remoteAddress)) != 0) : true);
  489. }
  490. uint64_t Node::prng()
  491. {
  492. // https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
  493. uint64_t x = _prngState[0];
  494. const uint64_t y = _prngState[1];
  495. _prngState[0] = y;
  496. x ^= x << 23;
  497. const uint64_t z = x ^ y ^ (x >> 17) ^ (y >> 26);
  498. _prngState[1] = z;
  499. return z + y;
  500. }
  501. ZT_ResultCode Node::setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork, const ZT_PhysicalPathConfiguration *pathConfig)
  502. {
  503. RR->topology->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  504. return ZT_RESULT_OK;
  505. }
  506. World Node::planet() const
  507. {
  508. return RR->topology->planet();
  509. }
  510. std::vector<World> Node::moons() const
  511. {
  512. return RR->topology->moons();
  513. }
  514. void Node::ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig)
  515. {
  516. if (destination == RR->identity.address()) {
  517. SharedPtr<Network> n(network(nwid));
  518. if (!n) return;
  519. n->setConfiguration((void *)0,nc,true);
  520. } else {
  521. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  522. try {
  523. if (nc.toDictionary(*dconf,sendLegacyFormatConfig)) {
  524. uint64_t configUpdateId = prng();
  525. if (!configUpdateId) ++configUpdateId;
  526. const unsigned int totalSize = dconf->sizeBytes();
  527. unsigned int chunkIndex = 0;
  528. while (chunkIndex < totalSize) {
  529. const unsigned int chunkLen = std::min(totalSize - chunkIndex,(unsigned int)(ZT_PROTO_MAX_PACKET_LENGTH - (ZT_PACKET_IDX_PAYLOAD + 256)));
  530. Packet outp(destination,RR->identity.address(),(requestPacketId) ? Packet::VERB_OK : Packet::VERB_NETWORK_CONFIG);
  531. if (requestPacketId) {
  532. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  533. outp.append(requestPacketId);
  534. }
  535. const unsigned int sigStart = outp.size();
  536. outp.append(nwid);
  537. outp.append((uint16_t)chunkLen);
  538. outp.append((const void *)(dconf->data() + chunkIndex),chunkLen);
  539. outp.append((uint8_t)0); // no flags
  540. outp.append((uint64_t)configUpdateId);
  541. outp.append((uint32_t)totalSize);
  542. outp.append((uint32_t)chunkIndex);
  543. C25519::Signature sig(RR->identity.sign(reinterpret_cast<const uint8_t *>(outp.data()) + sigStart,outp.size() - sigStart));
  544. outp.append((uint8_t)1);
  545. outp.append((uint16_t)ZT_C25519_SIGNATURE_LEN);
  546. outp.append(sig.data,ZT_C25519_SIGNATURE_LEN);
  547. outp.compress();
  548. RR->sw->send((void *)0,outp,true);
  549. chunkIndex += chunkLen;
  550. }
  551. }
  552. delete dconf;
  553. } catch ( ... ) {
  554. delete dconf;
  555. throw;
  556. }
  557. }
  558. }
  559. void Node::ncSendRevocation(const Address &destination,const Revocation &rev)
  560. {
  561. if (destination == RR->identity.address()) {
  562. SharedPtr<Network> n(network(rev.networkId()));
  563. if (!n) return;
  564. n->addCredential((void *)0,RR->identity.address(),rev);
  565. } else {
  566. Packet outp(destination,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  567. outp.append((uint8_t)0x00);
  568. outp.append((uint16_t)0);
  569. outp.append((uint16_t)0);
  570. outp.append((uint16_t)1);
  571. rev.serialize(outp);
  572. outp.append((uint16_t)0);
  573. RR->sw->send((void *)0,outp,true);
  574. }
  575. }
  576. void Node::ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode)
  577. {
  578. if (destination == RR->identity.address()) {
  579. SharedPtr<Network> n(network(nwid));
  580. if (!n) return;
  581. switch(errorCode) {
  582. case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  583. case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  584. n->setNotFound();
  585. break;
  586. case NetworkController::NC_ERROR_ACCESS_DENIED:
  587. n->setAccessDenied();
  588. break;
  589. default: break;
  590. }
  591. } else if (requestPacketId) {
  592. Packet outp(destination,RR->identity.address(),Packet::VERB_ERROR);
  593. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  594. outp.append(requestPacketId);
  595. switch(errorCode) {
  596. //case NetworkController::NC_ERROR_OBJECT_NOT_FOUND:
  597. //case NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR:
  598. default:
  599. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  600. break;
  601. case NetworkController::NC_ERROR_ACCESS_DENIED:
  602. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  603. break;
  604. }
  605. outp.append(nwid);
  606. RR->sw->send((void *)0,outp,true);
  607. } // else we can't send an ERROR() in response to nothing, so discard
  608. }
  609. } // namespace ZeroTier
  610. /****************************************************************************/
  611. /* CAPI bindings */
  612. /****************************************************************************/
  613. extern "C" {
  614. enum ZT_ResultCode ZT_Node_new(ZT_Node **node,void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now)
  615. {
  616. *node = (ZT_Node *)0;
  617. try {
  618. *node = reinterpret_cast<ZT_Node *>(new ZeroTier::Node(uptr,tptr,callbacks,now));
  619. return ZT_RESULT_OK;
  620. } catch (std::bad_alloc &exc) {
  621. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  622. } catch (std::runtime_error &exc) {
  623. return ZT_RESULT_FATAL_ERROR_DATA_STORE_FAILED;
  624. } catch ( ... ) {
  625. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  626. }
  627. }
  628. void ZT_Node_delete(ZT_Node *node)
  629. {
  630. try {
  631. delete (reinterpret_cast<ZeroTier::Node *>(node));
  632. } catch ( ... ) {}
  633. }
  634. enum ZT_ResultCode ZT_Node_processWirePacket(
  635. ZT_Node *node,
  636. void *tptr,
  637. int64_t now,
  638. int64_t localSocket,
  639. const struct sockaddr_storage *remoteAddress,
  640. const void *packetData,
  641. unsigned int packetLength,
  642. volatile int64_t *nextBackgroundTaskDeadline)
  643. {
  644. try {
  645. return reinterpret_cast<ZeroTier::Node *>(node)->processWirePacket(tptr,now,localSocket,remoteAddress,packetData,packetLength,nextBackgroundTaskDeadline);
  646. } catch (std::bad_alloc &exc) {
  647. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  648. } catch ( ... ) {
  649. return ZT_RESULT_OK; // "OK" since invalid packets are simply dropped, but the system is still up
  650. }
  651. }
  652. enum ZT_ResultCode ZT_Node_processVirtualNetworkFrame(
  653. ZT_Node *node,
  654. void *tptr,
  655. int64_t now,
  656. uint64_t nwid,
  657. uint64_t sourceMac,
  658. uint64_t destMac,
  659. unsigned int etherType,
  660. unsigned int vlanId,
  661. const void *frameData,
  662. unsigned int frameLength,
  663. volatile int64_t *nextBackgroundTaskDeadline)
  664. {
  665. try {
  666. return reinterpret_cast<ZeroTier::Node *>(node)->processVirtualNetworkFrame(tptr,now,nwid,sourceMac,destMac,etherType,vlanId,frameData,frameLength,nextBackgroundTaskDeadline);
  667. } catch (std::bad_alloc &exc) {
  668. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  669. } catch ( ... ) {
  670. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  671. }
  672. }
  673. enum ZT_ResultCode ZT_Node_processBackgroundTasks(ZT_Node *node,void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
  674. {
  675. try {
  676. return reinterpret_cast<ZeroTier::Node *>(node)->processBackgroundTasks(tptr,now,nextBackgroundTaskDeadline);
  677. } catch (std::bad_alloc &exc) {
  678. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  679. } catch ( ... ) {
  680. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  681. }
  682. }
  683. enum ZT_ResultCode ZT_Node_join(ZT_Node *node,uint64_t nwid,void *uptr,void *tptr)
  684. {
  685. try {
  686. return reinterpret_cast<ZeroTier::Node *>(node)->join(nwid,uptr,tptr);
  687. } catch (std::bad_alloc &exc) {
  688. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  689. } catch ( ... ) {
  690. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  691. }
  692. }
  693. enum ZT_ResultCode ZT_Node_leave(ZT_Node *node,uint64_t nwid,void **uptr,void *tptr)
  694. {
  695. try {
  696. return reinterpret_cast<ZeroTier::Node *>(node)->leave(nwid,uptr,tptr);
  697. } catch (std::bad_alloc &exc) {
  698. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  699. } catch ( ... ) {
  700. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  701. }
  702. }
  703. enum ZT_ResultCode ZT_Node_multicastSubscribe(ZT_Node *node,void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  704. {
  705. try {
  706. return reinterpret_cast<ZeroTier::Node *>(node)->multicastSubscribe(tptr,nwid,multicastGroup,multicastAdi);
  707. } catch (std::bad_alloc &exc) {
  708. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  709. } catch ( ... ) {
  710. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  711. }
  712. }
  713. enum ZT_ResultCode ZT_Node_multicastUnsubscribe(ZT_Node *node,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi)
  714. {
  715. try {
  716. return reinterpret_cast<ZeroTier::Node *>(node)->multicastUnsubscribe(nwid,multicastGroup,multicastAdi);
  717. } catch (std::bad_alloc &exc) {
  718. return ZT_RESULT_FATAL_ERROR_OUT_OF_MEMORY;
  719. } catch ( ... ) {
  720. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  721. }
  722. }
  723. enum ZT_ResultCode ZT_Node_orbit(ZT_Node *node,void *tptr,uint64_t moonWorldId,uint64_t moonSeed)
  724. {
  725. try {
  726. return reinterpret_cast<ZeroTier::Node *>(node)->orbit(tptr,moonWorldId,moonSeed);
  727. } catch ( ... ) {
  728. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  729. }
  730. }
  731. enum ZT_ResultCode ZT_Node_deorbit(ZT_Node *node,void *tptr,uint64_t moonWorldId)
  732. {
  733. try {
  734. return reinterpret_cast<ZeroTier::Node *>(node)->deorbit(tptr,moonWorldId);
  735. } catch ( ... ) {
  736. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  737. }
  738. }
  739. uint64_t ZT_Node_address(ZT_Node *node)
  740. {
  741. return reinterpret_cast<ZeroTier::Node *>(node)->address();
  742. }
  743. void ZT_Node_status(ZT_Node *node,ZT_NodeStatus *status)
  744. {
  745. try {
  746. reinterpret_cast<ZeroTier::Node *>(node)->status(status);
  747. } catch ( ... ) {}
  748. }
  749. ZT_PeerList *ZT_Node_peers(ZT_Node *node)
  750. {
  751. try {
  752. return reinterpret_cast<ZeroTier::Node *>(node)->peers();
  753. } catch ( ... ) {
  754. return (ZT_PeerList *)0;
  755. }
  756. }
  757. ZT_VirtualNetworkConfig *ZT_Node_networkConfig(ZT_Node *node,uint64_t nwid)
  758. {
  759. try {
  760. return reinterpret_cast<ZeroTier::Node *>(node)->networkConfig(nwid);
  761. } catch ( ... ) {
  762. return (ZT_VirtualNetworkConfig *)0;
  763. }
  764. }
  765. ZT_VirtualNetworkList *ZT_Node_networks(ZT_Node *node)
  766. {
  767. try {
  768. return reinterpret_cast<ZeroTier::Node *>(node)->networks();
  769. } catch ( ... ) {
  770. return (ZT_VirtualNetworkList *)0;
  771. }
  772. }
  773. void ZT_Node_freeQueryResult(ZT_Node *node,void *qr)
  774. {
  775. try {
  776. reinterpret_cast<ZeroTier::Node *>(node)->freeQueryResult(qr);
  777. } catch ( ... ) {}
  778. }
  779. int ZT_Node_addLocalInterfaceAddress(ZT_Node *node,const struct sockaddr_storage *addr)
  780. {
  781. try {
  782. return reinterpret_cast<ZeroTier::Node *>(node)->addLocalInterfaceAddress(addr);
  783. } catch ( ... ) {
  784. return 0;
  785. }
  786. }
  787. void ZT_Node_clearLocalInterfaceAddresses(ZT_Node *node)
  788. {
  789. try {
  790. reinterpret_cast<ZeroTier::Node *>(node)->clearLocalInterfaceAddresses();
  791. } catch ( ... ) {}
  792. }
  793. int ZT_Node_sendUserMessage(ZT_Node *node,void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len)
  794. {
  795. try {
  796. return reinterpret_cast<ZeroTier::Node *>(node)->sendUserMessage(tptr,dest,typeId,data,len);
  797. } catch ( ... ) {
  798. return 0;
  799. }
  800. }
  801. void ZT_Node_setNetconfMaster(ZT_Node *node,void *networkControllerInstance)
  802. {
  803. try {
  804. reinterpret_cast<ZeroTier::Node *>(node)->setNetconfMaster(networkControllerInstance);
  805. } catch ( ... ) {}
  806. }
  807. enum ZT_ResultCode ZT_Node_setPhysicalPathConfiguration(ZT_Node *node,const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig)
  808. {
  809. try {
  810. return reinterpret_cast<ZeroTier::Node *>(node)->setPhysicalPathConfiguration(pathNetwork,pathConfig);
  811. } catch ( ... ) {
  812. return ZT_RESULT_FATAL_ERROR_INTERNAL;
  813. }
  814. }
  815. void ZT_version(int *major,int *minor,int *revision)
  816. {
  817. if (major) *major = ZEROTIER_ONE_VERSION_MAJOR;
  818. if (minor) *minor = ZEROTIER_ONE_VERSION_MINOR;
  819. if (revision) *revision = ZEROTIER_ONE_VERSION_REVISION;
  820. }
  821. } // extern "C"