Peer.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 "AntiRecursion.hpp"
  30. #include <algorithm>
  31. namespace ZeroTier {
  32. Peer::Peer() :
  33. _lastUsed(0),
  34. _lastReceive(0),
  35. _lastUnicastFrame(0),
  36. _lastMulticastFrame(0),
  37. _lastAnnouncedTo(0),
  38. _vMajor(0),
  39. _vMinor(0),
  40. _vRevision(0),
  41. _latency(0) {}
  42. Peer::Peer(const Identity &myIdentity,const Identity &peerIdentity)
  43. throw(std::runtime_error) :
  44. _id(peerIdentity),
  45. _lastUsed(0),
  46. _lastReceive(0),
  47. _lastUnicastFrame(0),
  48. _lastMulticastFrame(0),
  49. _lastAnnouncedTo(0),
  50. _vMajor(0),
  51. _vMinor(0),
  52. _vRevision(0),
  53. _latency(0)
  54. {
  55. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  56. throw std::runtime_error("new peer identity key agreement failed");
  57. }
  58. void Peer::receive(
  59. const RuntimeEnvironment *_r,
  60. const SharedPtr<Socket> &fromSock,
  61. const InetAddress &remoteAddr,
  62. unsigned int hops,
  63. uint64_t packetId,
  64. Packet::Verb verb,
  65. uint64_t inRePacketId,
  66. Packet::Verb inReVerb,
  67. uint64_t now)
  68. {
  69. // Update system-wide last packet receive time
  70. *((const_cast<uint64_t *>(&(_r->timeOfLastPacketReceived)))) = now;
  71. // Global last receive time regardless of path
  72. _lastReceive = now;
  73. // Learn paths from direct packets (hops == 0)
  74. if (!hops) {
  75. {
  76. Mutex::Lock _l(_lock);
  77. bool havePath = false;
  78. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  79. if ((p->address() == remoteAddr)&&(p->tcp() == fromSock->tcp())) {
  80. p->received(now);
  81. havePath = true;
  82. break;
  83. }
  84. }
  85. if (!havePath) {
  86. Path::Type pt = Path::PATH_TYPE_UDP;
  87. switch(fromSock->type()) {
  88. case Socket::ZT_SOCKET_TYPE_TCP_IN:
  89. pt = Path::PATH_TYPE_TCP_IN;
  90. break;
  91. case Socket::ZT_SOCKET_TYPE_TCP_OUT:
  92. pt = Path::PATH_TYPE_TCP_OUT;
  93. break;
  94. default:
  95. break;
  96. }
  97. _paths.push_back(Path(remoteAddr,pt,false));
  98. _paths.back().received(now);
  99. }
  100. }
  101. // Announce multicast LIKEs to peers to whom we have a direct link
  102. // Lock can't be locked here or it'll recurse and deadlock.
  103. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  104. _lastAnnouncedTo = now;
  105. _r->sw->announceMulticastGroups(SharedPtr<Peer>(this));
  106. }
  107. }
  108. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  109. _lastUnicastFrame = now;
  110. else if (verb == Packet::VERB_MULTICAST_FRAME)
  111. _lastMulticastFrame = now;
  112. }
  113. Path::Type Peer::send(const RuntimeEnvironment *_r,const void *data,unsigned int len,uint64_t now)
  114. {
  115. Mutex::Lock _l(_lock);
  116. /* For sending ordinary packets, paths are divided into two categories:
  117. * "normal" and "TCP out." Normal includes UDP and incoming TCP. We want
  118. * to treat outbound TCP differently since if we use it it may end up
  119. * overriding UDP and UDP performs much better. We only want to initiate
  120. * TCP if it looks like UDP isn't available. */
  121. Path *bestNormalPath = (Path *)0;
  122. Path *bestTcpOutPath = (Path *)0;
  123. uint64_t bestNormalPathLastReceived = 0;
  124. uint64_t bestTcpOutPathLastReceived = 0;
  125. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  126. uint64_t lr = p->lastReceived();
  127. if (p->type() == Path::PATH_TYPE_TCP_OUT) {
  128. if (lr >= bestTcpOutPathLastReceived) {
  129. bestTcpOutPathLastReceived = lr;
  130. bestTcpOutPath = &(*p);
  131. }
  132. } else {
  133. if (lr >= bestNormalPathLastReceived) {
  134. bestNormalPathLastReceived = lr;
  135. bestNormalPath = &(*p);
  136. }
  137. }
  138. }
  139. Path *bestPath = (Path *)0;
  140. if (bestTcpOutPath) { // we have a TCP out path
  141. if (bestNormalPath) { // we have both paths, decide which to use
  142. if (_r->tcpTunnelingEnabled) { // TCP tunneling is enabled, so use normal path only if it looks alive
  143. if ((bestNormalPathLastReceived > _r->timeOfLastResynchronize)&&((now - bestNormalPathLastReceived) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
  144. bestPath = bestNormalPath;
  145. else bestPath = bestTcpOutPath;
  146. } else { // TCP tunneling is disabled, use normal path
  147. bestPath = bestNormalPath;
  148. }
  149. } else { // we only have a TCP_OUT path, so use it regardless
  150. bestPath = bestTcpOutPath;
  151. }
  152. } else { // we only have a normal path (or none at all, that case is caught below)
  153. bestPath = bestNormalPath;
  154. }
  155. if (!bestPath)
  156. return Path::PATH_TYPE_NULL;
  157. _r->antiRec->logOutgoingZT(data,len);
  158. if (_r->sm->send(bestPath->address(),bestPath->tcp(),bestPath->type() == Path::PATH_TYPE_TCP_OUT,data,len)) {
  159. bestPath->sent(now);
  160. return bestPath->type();
  161. }
  162. return Path::PATH_TYPE_NULL;
  163. }
  164. bool Peer::sendFirewallOpener(const RuntimeEnvironment *_r,uint64_t now)
  165. {
  166. bool sent = false;
  167. Mutex::Lock _l(_lock);
  168. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  169. if (p->type() == Path::PATH_TYPE_UDP) {
  170. for(unsigned int h=1;h<=ZT_FIREWALL_OPENER_HOPS;++h)
  171. sent |= _r->sm->sendFirewallOpener(p->address(),h);
  172. }
  173. }
  174. return sent;
  175. }
  176. bool Peer::sendPing(const RuntimeEnvironment *_r,uint64_t now)
  177. {
  178. bool sent = false;
  179. SharedPtr<Peer> self(this);
  180. Mutex::Lock _l(_lock);
  181. /* Ping (and thus open) outbound TCP connections if we have no other options
  182. * or if the TCP tunneling master switch is enabled and pings have been
  183. * unanswered for ZT_TCP_TUNNEL_FAILOVER_TIMEOUT ms over normal channels. */
  184. uint64_t lastNormalPingSent = 0;
  185. uint64_t lastNormalReceive = 0;
  186. bool haveNormal = false;
  187. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  188. if (p->type() != Path::PATH_TYPE_TCP_OUT) {
  189. lastNormalPingSent = std::max(lastNormalPingSent,p->lastPing());
  190. lastNormalReceive = std::max(lastNormalReceive,p->lastReceived());
  191. haveNormal = true;
  192. }
  193. }
  194. const bool useTcpOut = ( (!haveNormal) || ( (_r->tcpTunnelingEnabled) && (lastNormalPingSent > _r->timeOfLastResynchronize) && (lastNormalPingSent > lastNormalReceive) && ((lastNormalPingSent - lastNormalReceive) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT) ) );
  195. TRACE("PING %s (useTcpOut==%d)",_id.address().toString().c_str(),(int)useTcpOut);
  196. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  197. if ((useTcpOut)||(p->type() != Path::PATH_TYPE_TCP_OUT)) {
  198. p->pinged(now); // attempts to ping are logged whether they look successful or not
  199. if (_r->sw->sendHELLO(self,*p)) {
  200. p->sent(now);
  201. sent = true;
  202. }
  203. }
  204. }
  205. return sent;
  206. }
  207. void Peer::clean(uint64_t now)
  208. {
  209. Mutex::Lock _l(_lock);
  210. unsigned long i = 0,o = 0,l = (unsigned long)_paths.size();
  211. while (i != l) {
  212. if (_paths[i].active(now)) // active includes fixed
  213. _paths[o++] = _paths[i];
  214. ++i;
  215. }
  216. _paths.resize(o);
  217. }
  218. void Peer::getBestActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  219. {
  220. uint64_t bestV4 = 0,bestV6 = 0;
  221. Mutex::Lock _l(_lock);
  222. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  223. if ((p->type() == Path::PATH_TYPE_UDP)&&(p->active(now))) {
  224. uint64_t lr = p->lastReceived();
  225. if (lr) {
  226. if (p->address().isV4()) {
  227. if (lr >= bestV4) {
  228. bestV4 = lr;
  229. v4 = p->address();
  230. }
  231. } else if (p->address().isV6()) {
  232. if (lr >= bestV6) {
  233. bestV6 = lr;
  234. v6 = p->address();
  235. }
  236. }
  237. }
  238. }
  239. }
  240. }
  241. } // namespace ZeroTier