Peer.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "Peer.hpp"
  28. #include "Switch.hpp"
  29. #include <algorithm>
  30. namespace ZeroTier {
  31. Peer::Peer() :
  32. _lastUsed(0),
  33. _lastUnicastFrame(0),
  34. _lastMulticastFrame(0),
  35. _lastAnnouncedTo(0),
  36. _vMajor(0),
  37. _vMinor(0),
  38. _vRevision(0),
  39. _latency(0) {}
  40. Peer::Peer(const Identity &myIdentity,const Identity &peerIdentity)
  41. throw(std::runtime_error) :
  42. _id(peerIdentity),
  43. _lastUsed(0),
  44. _lastUnicastFrame(0),
  45. _lastMulticastFrame(0),
  46. _lastAnnouncedTo(0),
  47. _vMajor(0),
  48. _vMinor(0),
  49. _vRevision(0),
  50. _latency(0)
  51. {
  52. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  53. throw std::runtime_error("new peer identity key agreement failed");
  54. }
  55. void Peer::receive(
  56. const RuntimeEnvironment *_r,
  57. const SharedPtr<Socket> &fromSock,
  58. const InetAddress &remoteAddr,
  59. unsigned int hops,
  60. uint64_t packetId,
  61. Packet::Verb verb,
  62. uint64_t inRePacketId,
  63. Packet::Verb inReVerb,
  64. uint64_t now)
  65. {
  66. // Update system-wide last packet receive time
  67. *((const_cast<uint64_t *>(&(_r->timeOfLastPacketReceived)))) = now;
  68. // Learn paths from direct packets (hops == 0)
  69. if (!hops) {
  70. {
  71. Mutex::Lock _l(_lock);
  72. bool havePath = false;
  73. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  74. if ((p->address() == remoteAddr)&&(p->tcp() == fromSock->tcp())) {
  75. p->received(now);
  76. havePath = true;
  77. break;
  78. }
  79. }
  80. if (!havePath) {
  81. Path::Type pt = Path::PATH_TYPE_UDP;
  82. switch(fromSock->type()) {
  83. case Socket::ZT_SOCKET_TYPE_TCP_IN:
  84. pt = Path::PATH_TYPE_TCP_IN;
  85. break;
  86. case Socket::ZT_SOCKET_TYPE_TCP_OUT:
  87. pt = Path::PATH_TYPE_TCP_OUT;
  88. break;
  89. default:
  90. break;
  91. }
  92. _paths.push_back(Path(remoteAddr,pt,false));
  93. _paths.back().received(now);
  94. }
  95. }
  96. // Announce multicast LIKEs to peers to whom we have a direct link
  97. // Lock can't be locked here or it'll recurse and deadlock.
  98. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  99. _lastAnnouncedTo = now;
  100. _r->sw->announceMulticastGroups(SharedPtr<Peer>(this));
  101. }
  102. }
  103. if (verb == Packet::VERB_FRAME)
  104. _lastUnicastFrame = now;
  105. else if (verb == Packet::VERB_MULTICAST_FRAME)
  106. _lastMulticastFrame = now;
  107. }
  108. bool Peer::send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now)
  109. {
  110. Mutex::Lock _l(_lock);
  111. Path *bestNormalPath = (Path *)0;
  112. Path *bestTcpOutPath = (Path *)0;
  113. uint64_t bestNormalPathLastReceived = 0;
  114. uint64_t bestTcpOutPathLastReceived = 0;
  115. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  116. uint64_t lr = p->lastReceived();
  117. if (p->type() == Path::PATH_TYPE_TCP_OUT) { // TCP_OUT paths initiate TCP connections
  118. if (lr >= bestTcpOutPathLastReceived) {
  119. bestTcpOutPathLastReceived = lr;
  120. bestTcpOutPath = &(*p);
  121. }
  122. } else { // paths other than TCP_OUT are considered "normal"
  123. if (lr >= bestNormalPathLastReceived) {
  124. bestNormalPathLastReceived = lr;
  125. bestNormalPath = &(*p);
  126. }
  127. }
  128. }
  129. Path *bestPath = (Path *)0;
  130. if (!_r->tcpTunnelingEnabled) { // TCP tunneling master switch is off, use normal path
  131. bestPath = bestNormalPath;
  132. } else if (bestNormalPath) { // we have a normal path, so use if it looks active
  133. if ((bestNormalPathLastReceived > _r->timeOfLastResynchronize)&&((now - bestNormalPathLastReceived) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
  134. bestPath = bestNormalPath;
  135. else bestPath = bestTcpOutPath;
  136. } else { // no normal path available
  137. bestPath = bestTcpOutPath;
  138. }
  139. if (!bestPath)
  140. return false;
  141. if (_r->sm->send(bestPath->address(),bestPath->tcp(),bestPath->type() == Path::PATH_TYPE_TCP_OUT,data,len)) {
  142. bestPath->sent(now);
  143. return true;
  144. }
  145. return false;
  146. }
  147. bool Peer::sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now)
  148. {
  149. bool sent = false;
  150. Mutex::Lock _l(_lock);
  151. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  152. if (!p->tcp())
  153. sent |= _r->sm->sendFirewallOpener(p->address(),ZT_FIREWALL_OPENER_HOPS);
  154. }
  155. return sent;
  156. }
  157. bool Peer::sendPing(const RuntimeEnvironment *_r,uint64_t now)
  158. {
  159. bool sent = false;
  160. SharedPtr<Peer> self(this);
  161. Mutex::Lock _l(_lock);
  162. uint64_t lastUdpPingSent = 0;
  163. uint64_t lastUdpReceive = 0;
  164. bool haveUdp = false;
  165. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  166. if (p->type() == Path::PATH_TYPE_UDP) {
  167. lastUdpPingSent = std::max(lastUdpPingSent,p->lastPing());
  168. lastUdpReceive = std::max(lastUdpReceive,p->lastReceived());
  169. haveUdp = true;
  170. }
  171. }
  172. bool useTcpOut = ( (!haveUdp) || ( (_r->tcpTunnelingEnabled) && (lastUdpPingSent > lastUdpReceive) && ((now - lastUdpReceive) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT) ) );
  173. TRACE("PING %s (useTcpOut==%d)",_id.address().toString().c_str(),(int)useTcpOut);
  174. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  175. if ((useTcpOut)||(p->type() != Path::PATH_TYPE_TCP_OUT)) {
  176. p->pinged(now); // we log pings sent even if the send "fails", since what we want to track is when we last tried to ping
  177. if (_r->sw->sendHELLO(self,*p)) {
  178. p->sent(now);
  179. sent = true;
  180. }
  181. }
  182. }
  183. return sent;
  184. }
  185. void Peer::clean(uint64_t now)
  186. {
  187. Mutex::Lock _l(_lock);
  188. unsigned long i = 0,o = 0,l = (unsigned long)_paths.size();
  189. while (i != l) {
  190. if (_paths[i].active(now))
  191. _paths[o++] = _paths[i];
  192. ++i;
  193. }
  194. _paths.resize(o);
  195. }
  196. void Peer::getBestActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  197. {
  198. uint64_t bestV4 = 0,bestV6 = 0;
  199. Mutex::Lock _l(_lock);
  200. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  201. if ((p->type() == Path::PATH_TYPE_UDP)&&(p->active(now))) {
  202. uint64_t lr = p->lastReceived();
  203. if (lr) {
  204. if (p->address().isV4()) {
  205. if (lr >= bestV4) {
  206. bestV4 = lr;
  207. v4 = p->address();
  208. }
  209. } else if (p->address().isV6()) {
  210. if (lr >= bestV6) {
  211. bestV6 = lr;
  212. v6 = p->address();
  213. }
  214. }
  215. }
  216. }
  217. }
  218. }
  219. } // namespace ZeroTier