Peer.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. TODO: the former may go
  108. // obsolete with time as network controllers take over this role.
  109. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  110. _lastAnnouncedTo = now;
  111. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  112. std::vector< SharedPtr<Network> > networks(RR->nc->networks());
  113. for(std::vector< SharedPtr<Network> >::iterator n(networks.begin());n!=networks.end();++n) {
  114. if ( ((*n)->isAllowed(_id.address())) || ((*n)->controller() == _id.address()) || (RR->topology->isSupernode(_id.address())) ) {
  115. std::set<MulticastGroup> mgs((*n)->multicastGroups());
  116. for(std::set<MulticastGroup>::iterator mg(mgs.begin());mg!=mgs.end();++mg) {
  117. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  118. outp.armor(_key,true);
  119. fromSock->send(remoteAddr,outp.data(),outp.size());
  120. outp.reset(_id.address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  121. }
  122. // network ID, MAC, ADI
  123. outp.append((uint64_t)(*n)->id());
  124. mg->mac().appendTo(outp);
  125. outp.append((uint32_t)mg->adi());
  126. }
  127. }
  128. }
  129. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  130. outp.armor(_key,true);
  131. fromSock->send(remoteAddr,outp.data(),outp.size());
  132. }
  133. }
  134. }
  135. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  136. _lastUnicastFrame = now;
  137. else if (verb == Packet::VERB_MULTICAST_FRAME)
  138. _lastMulticastFrame = now;
  139. }
  140. Path::Type Peer::send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now)
  141. {
  142. Mutex::Lock _l(_lock);
  143. /* For sending ordinary packets, paths are divided into two categories:
  144. * "normal" and "TCP out." Normal includes UDP and incoming TCP. We want
  145. * to treat outbound TCP differently since if we use it it may end up
  146. * overriding UDP and UDP performs much better. We only want to initiate
  147. * TCP if it looks like UDP isn't available. */
  148. Path *bestNormalPath = (Path *)0;
  149. Path *bestTcpOutPath = (Path *)0;
  150. uint64_t bestNormalPathLastReceived = 0;
  151. uint64_t bestTcpOutPathLastReceived = 0;
  152. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  153. uint64_t lr = p->lastReceived();
  154. if (p->type() == Path::PATH_TYPE_TCP_OUT) {
  155. if (lr >= bestTcpOutPathLastReceived) {
  156. bestTcpOutPathLastReceived = lr;
  157. bestTcpOutPath = &(*p);
  158. }
  159. } else {
  160. if (lr >= bestNormalPathLastReceived) {
  161. bestNormalPathLastReceived = lr;
  162. bestNormalPath = &(*p);
  163. }
  164. }
  165. }
  166. Path *bestPath = (Path *)0;
  167. if (bestTcpOutPath) { // we have a TCP out path
  168. if (bestNormalPath) { // we have both paths, decide which to use
  169. if (RR->tcpTunnelingEnabled) { // TCP tunneling is enabled, so use normal path only if it looks alive
  170. if ((bestNormalPathLastReceived > RR->timeOfLastResynchronize)&&((now - bestNormalPathLastReceived) < ZT_PEER_PATH_ACTIVITY_TIMEOUT))
  171. bestPath = bestNormalPath;
  172. else bestPath = bestTcpOutPath;
  173. } else { // TCP tunneling is disabled, use normal path
  174. bestPath = bestNormalPath;
  175. }
  176. } else { // we only have a TCP_OUT path, so use it regardless
  177. bestPath = bestTcpOutPath;
  178. }
  179. } else { // we only have a normal path (or none at all, that case is caught below)
  180. bestPath = bestNormalPath;
  181. }
  182. if (!bestPath)
  183. return Path::PATH_TYPE_NULL;
  184. RR->antiRec->logOutgoingZT(data,len);
  185. if (RR->sm->send(bestPath->address(),bestPath->tcp(),bestPath->type() == Path::PATH_TYPE_TCP_OUT,data,len)) {
  186. bestPath->sent(now);
  187. return bestPath->type();
  188. }
  189. return Path::PATH_TYPE_NULL;
  190. }
  191. bool Peer::sendPing(const RuntimeEnvironment *RR,uint64_t now)
  192. {
  193. bool sent = false;
  194. SharedPtr<Peer> self(this);
  195. Mutex::Lock _l(_lock);
  196. /* Ping (and thus open) outbound TCP connections if we have no other options
  197. * or if the TCP tunneling master switch is enabled and pings have been
  198. * unanswered for ZT_TCP_TUNNEL_FAILOVER_TIMEOUT ms over normal channels. */
  199. uint64_t lastNormalPingSent = 0;
  200. uint64_t lastNormalReceive = 0;
  201. bool haveNormal = false;
  202. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  203. if (p->type() != Path::PATH_TYPE_TCP_OUT) {
  204. lastNormalPingSent = std::max(lastNormalPingSent,p->lastPing());
  205. lastNormalReceive = std::max(lastNormalReceive,p->lastReceived());
  206. haveNormal = true;
  207. }
  208. }
  209. const bool useTcpOut = ( (!haveNormal) || ( (RR->tcpTunnelingEnabled) && (lastNormalPingSent > RR->timeOfLastResynchronize) && (lastNormalPingSent > lastNormalReceive) && ((lastNormalPingSent - lastNormalReceive) >= ZT_TCP_TUNNEL_FAILOVER_TIMEOUT) ) );
  210. TRACE("PING %s (useTcpOut==%d)",_id.address().toString().c_str(),(int)useTcpOut);
  211. for(std::vector<Path>::iterator p(_paths.begin());p!=_paths.end();++p) {
  212. if ((useTcpOut)||(p->type() != Path::PATH_TYPE_TCP_OUT)) {
  213. p->pinged(now); // attempts to ping are logged whether they look successful or not
  214. if (RR->sw->sendHELLO(self,*p)) {
  215. p->sent(now);
  216. sent = true;
  217. }
  218. }
  219. }
  220. return sent;
  221. }
  222. void Peer::clean(uint64_t now)
  223. {
  224. Mutex::Lock _l(_lock);
  225. unsigned long i = 0,o = 0,l = (unsigned long)_paths.size();
  226. while (i != l) {
  227. if (_paths[i].active(now)) // active includes fixed
  228. _paths[o++] = _paths[i];
  229. ++i;
  230. }
  231. _paths.resize(o);
  232. }
  233. void Peer::getBestActiveUdpPathAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  234. {
  235. uint64_t bestV4 = 0,bestV6 = 0;
  236. Mutex::Lock _l(_lock);
  237. for(std::vector<Path>::const_iterator p(_paths.begin());p!=_paths.end();++p) {
  238. if ((p->type() == Path::PATH_TYPE_UDP)&&(p->active(now))) {
  239. uint64_t lr = p->lastReceived();
  240. if (lr) {
  241. if (p->address().isV4()) {
  242. if (lr >= bestV4) {
  243. bestV4 = lr;
  244. v4 = p->address();
  245. }
  246. } else if (p->address().isV6()) {
  247. if (lr >= bestV6) {
  248. bestV6 = lr;
  249. v6 = p->address();
  250. }
  251. }
  252. }
  253. }
  254. }
  255. }
  256. } // namespace ZeroTier