Node.cpp 29 KB

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