Node.cpp 29 KB

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