Peer.cpp 8.0 KB

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