SelfAwareness.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <set>
  22. #include <vector>
  23. #include "Constants.hpp"
  24. #include "SelfAwareness.hpp"
  25. #include "RuntimeEnvironment.hpp"
  26. #include "Node.hpp"
  27. #include "Topology.hpp"
  28. #include "Packet.hpp"
  29. #include "Peer.hpp"
  30. #include "Switch.hpp"
  31. // Entry timeout -- make it fairly long since this is just to prevent stale buildup
  32. #define ZT_SELFAWARENESS_ENTRY_TIMEOUT 3600000
  33. namespace ZeroTier {
  34. class _ResetWithinScope
  35. {
  36. public:
  37. _ResetWithinScope(uint64_t now,InetAddress::IpScope scope) :
  38. _now(now),
  39. _scope(scope) {}
  40. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  41. {
  42. if (p->resetWithinScope(_scope,_now))
  43. peersReset.push_back(p);
  44. }
  45. std::vector< SharedPtr<Peer> > peersReset;
  46. private:
  47. uint64_t _now;
  48. InetAddress::IpScope _scope;
  49. };
  50. SelfAwareness::SelfAwareness(const RuntimeEnvironment *renv) :
  51. RR(renv),
  52. _phy(32)
  53. {
  54. }
  55. SelfAwareness::~SelfAwareness()
  56. {
  57. }
  58. void SelfAwareness::iam(const Address &reporter,const InetAddress &receivedOnLocalAddress,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now)
  59. {
  60. const InetAddress::IpScope scope = myPhysicalAddress.ipScope();
  61. if ((scope != reporterPhysicalAddress.ipScope())||(scope == InetAddress::IP_SCOPE_NONE)||(scope == InetAddress::IP_SCOPE_LOOPBACK)||(scope == InetAddress::IP_SCOPE_MULTICAST))
  62. return;
  63. Mutex::Lock _l(_phy_m);
  64. PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,receivedOnLocalAddress,reporterPhysicalAddress,scope)];
  65. if ( (trusted) && ((now - entry.ts) < ZT_SELFAWARENESS_ENTRY_TIMEOUT) && (!entry.mySurface.ipsEqual(myPhysicalAddress)) ) {
  66. // Changes to external surface reported by trusted peers causes path reset in this scope
  67. entry.mySurface = myPhysicalAddress;
  68. entry.ts = now;
  69. TRACE("physical address %s for scope %u as seen from %s(%s) differs from %s, resetting paths in scope",myPhysicalAddress.toString().c_str(),(unsigned int)scope,reporter.toString().c_str(),reporterPhysicalAddress.toString().c_str(),entry.mySurface.toString().c_str());
  70. // Erase all entries in this scope that were not reported from this remote address to prevent 'thrashing'
  71. // due to multiple reports of endpoint change.
  72. // Don't use 'entry' after this since hash table gets modified.
  73. {
  74. Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
  75. PhySurfaceKey *k = (PhySurfaceKey *)0;
  76. PhySurfaceEntry *e = (PhySurfaceEntry *)0;
  77. while (i.next(k,e)) {
  78. if ((k->reporterPhysicalAddress != reporterPhysicalAddress)&&(k->scope == scope))
  79. _phy.erase(*k);
  80. }
  81. }
  82. // Reset all paths within this scope
  83. _ResetWithinScope rset(now,(InetAddress::IpScope)scope);
  84. RR->topology->eachPeer<_ResetWithinScope &>(rset);
  85. // Send a NOP to all peers for whom we forgot a path. This will cause direct
  86. // links to be re-established if possible, possibly using a root server or some
  87. // other relay.
  88. for(std::vector< SharedPtr<Peer> >::const_iterator p(rset.peersReset.begin());p!=rset.peersReset.end();++p) {
  89. if ((*p)->activelyTransferringFrames(now)) {
  90. Packet outp((*p)->address(),RR->identity.address(),Packet::VERB_NOP);
  91. RR->sw->send(outp,true,0);
  92. }
  93. }
  94. } else {
  95. // Otherwise just update DB to use to determine external surface info
  96. entry.mySurface = myPhysicalAddress;
  97. entry.ts = now;
  98. }
  99. }
  100. void SelfAwareness::clean(uint64_t now)
  101. {
  102. Mutex::Lock _l(_phy_m);
  103. Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
  104. PhySurfaceKey *k = (PhySurfaceKey *)0;
  105. PhySurfaceEntry *e = (PhySurfaceEntry *)0;
  106. while (i.next(k,e)) {
  107. if ((now - e->ts) >= ZT_SELFAWARENESS_ENTRY_TIMEOUT)
  108. _phy.erase(*k);
  109. }
  110. }
  111. std::vector<InetAddress> SelfAwareness::getSymmetricNatPredictions()
  112. {
  113. /* This is based on ideas and strategies found here:
  114. * https://tools.ietf.org/html/draft-takeda-symmetric-nat-traversal-00
  115. *
  116. * In short: a great many symmetric NATs allocate ports sequentially.
  117. * This is common on enterprise and carrier grade NATs as well as consumer
  118. * devices. This code generates a list of "you might try this" addresses by
  119. * extrapolating likely port assignments from currently known external
  120. * global IPv4 surfaces. These can then be included in a PUSH_DIRECT_PATHS
  121. * message to another peer, causing it to possibly try these addresses and
  122. * bust our local symmetric NAT. It works often enough to be worth the
  123. * extra bit of code and does no harm in cases where it fails. */
  124. // Gather unique surfaces indexed by local received-on address and flag
  125. // us as behind a symmetric NAT if there is more than one.
  126. std::map< InetAddress,std::set<InetAddress> > surfaces;
  127. bool symmetric = false;
  128. {
  129. Mutex::Lock _l(_phy_m);
  130. Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
  131. PhySurfaceKey *k = (PhySurfaceKey *)0;
  132. PhySurfaceEntry *e = (PhySurfaceEntry *)0;
  133. while (i.next(k,e)) {
  134. if ((e->mySurface.ss_family == AF_INET)&&(e->mySurface.ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  135. std::set<InetAddress> &s = surfaces[k->receivedOnLocalAddress];
  136. s.insert(e->mySurface);
  137. symmetric = symmetric||(s.size() > 1);
  138. }
  139. }
  140. }
  141. // If we appear to be symmetrically NATed, generate and return extrapolations
  142. // of those surfaces. Since PUSH_DIRECT_PATHS is sent multiple times, we
  143. // probabilistically generate extrapolations of anywhere from +1 to +5 to
  144. // increase the odds that it will work "eventually".
  145. if (symmetric) {
  146. std::vector<InetAddress> r;
  147. for(std::map< InetAddress,std::set<InetAddress> >::iterator si(surfaces.begin());si!=surfaces.end();++si) {
  148. for(std::set<InetAddress>::iterator i(si->second.begin());i!=si->second.end();++i) {
  149. InetAddress ipp(*i);
  150. unsigned int p = ipp.port() + 1 + ((unsigned int)RR->node->prng() & 3);
  151. if (p >= 65535)
  152. p -= 64510; // NATs seldom use ports <=1024 so wrap to 1025
  153. ipp.setPort(p);
  154. if ((si->second.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) {
  155. r.push_back(ipp);
  156. }
  157. }
  158. }
  159. return r;
  160. }
  161. return std::vector<InetAddress>();
  162. }
  163. } // namespace ZeroTier