Peer.cpp 11 KB

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