Node.cpp 28 KB

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