Peer.cpp 7.8 KB

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