Peer.cpp 8.9 KB

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