Peer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include "../version.h"
  19. #include "Constants.hpp"
  20. #include "Peer.hpp"
  21. #include "Node.hpp"
  22. #include "Switch.hpp"
  23. #include "Network.hpp"
  24. #include "SelfAwareness.hpp"
  25. #include "Cluster.hpp"
  26. #include "Packet.hpp"
  27. #include <algorithm>
  28. #define ZT_PEER_PATH_SORT_INTERVAL 5000
  29. namespace ZeroTier {
  30. // Used to send varying values for NAT keepalive
  31. static uint32_t _natKeepaliveBuf = 0;
  32. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  33. RR(renv),
  34. _lastUsed(0),
  35. _lastReceive(0),
  36. _lastUnicastFrame(0),
  37. _lastMulticastFrame(0),
  38. _lastAnnouncedTo(0),
  39. _lastDirectPathPushSent(0),
  40. _lastDirectPathPushReceive(0),
  41. _lastPathSort(0),
  42. _vProto(0),
  43. _vMajor(0),
  44. _vMinor(0),
  45. _vRevision(0),
  46. _id(peerIdentity),
  47. _numPaths(0),
  48. _latency(0),
  49. _directPathPushCutoffCount(0)
  50. {
  51. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  52. throw std::runtime_error("new peer identity key agreement failed");
  53. }
  54. void Peer::received(
  55. const InetAddress &localAddr,
  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. const bool trustEstablished)
  63. {
  64. #ifdef ZT_ENABLE_CLUSTER
  65. bool suboptimalPath = false;
  66. if ((RR->cluster)&&(hops == 0)) {
  67. // Note: findBetterEndpoint() is first since we still want to check
  68. // for a better endpoint even if we don't actually send a redirect.
  69. InetAddress redirectTo;
  70. if ( (verb != Packet::VERB_OK) && (verb != Packet::VERB_ERROR) && (verb != Packet::VERB_RENDEZVOUS) && (verb != Packet::VERB_PUSH_DIRECT_PATHS) && (RR->cluster->findBetterEndpoint(redirectTo,_id.address(),remoteAddr,false)) ) {
  71. if (_vProto >= 5) {
  72. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  73. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  74. outp.append((uint16_t)1); // count == 1
  75. outp.append((uint8_t)ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT); // flags: cluster redirect
  76. outp.append((uint16_t)0); // no extensions
  77. if (redirectTo.ss_family == AF_INET) {
  78. outp.append((uint8_t)4);
  79. outp.append((uint8_t)6);
  80. outp.append(redirectTo.rawIpData(),4);
  81. } else {
  82. outp.append((uint8_t)6);
  83. outp.append((uint8_t)18);
  84. outp.append(redirectTo.rawIpData(),16);
  85. }
  86. outp.append((uint16_t)redirectTo.port());
  87. outp.armor(_key,true);
  88. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  89. } else {
  90. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  91. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  92. outp.append((uint8_t)0); // no flags
  93. RR->identity.address().appendTo(outp);
  94. outp.append((uint16_t)redirectTo.port());
  95. if (redirectTo.ss_family == AF_INET) {
  96. outp.append((uint8_t)4);
  97. outp.append(redirectTo.rawIpData(),4);
  98. } else {
  99. outp.append((uint8_t)16);
  100. outp.append(redirectTo.rawIpData(),16);
  101. }
  102. outp.armor(_key,true);
  103. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  104. }
  105. suboptimalPath = true;
  106. }
  107. }
  108. #endif
  109. const uint64_t now = RR->node->now();
  110. _lastReceive = now;
  111. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  112. _lastUnicastFrame = now;
  113. else if (verb == Packet::VERB_MULTICAST_FRAME)
  114. _lastMulticastFrame = now;
  115. if (hops == 0) {
  116. bool pathIsConfirmed = false;
  117. unsigned int np = _numPaths;
  118. for(unsigned int p=0;p<np;++p) {
  119. if ((_paths[p].address() == remoteAddr)&&(_paths[p].localAddress() == localAddr)) {
  120. _paths[p].received(now);
  121. #ifdef ZT_ENABLE_CLUSTER
  122. _paths[p].setClusterSuboptimal(suboptimalPath);
  123. #endif
  124. pathIsConfirmed = true;
  125. break;
  126. }
  127. }
  128. if ((!pathIsConfirmed)&&(RR->node->shouldUsePathForZeroTierTraffic(localAddr,remoteAddr))) {
  129. if (verb == Packet::VERB_OK) {
  130. Path *slot = (Path *)0;
  131. if (np < ZT_MAX_PEER_NETWORK_PATHS) {
  132. slot = &(_paths[np++]);
  133. } else {
  134. uint64_t slotWorstScore = 0xffffffffffffffffULL;
  135. for(unsigned int p=0;p<ZT_MAX_PEER_NETWORK_PATHS;++p) {
  136. if (!_paths[p].active(now)) {
  137. slot = &(_paths[p]);
  138. break;
  139. } else {
  140. const uint64_t score = _paths[p].score();
  141. if (score <= slotWorstScore) {
  142. slotWorstScore = score;
  143. slot = &(_paths[p]);
  144. }
  145. }
  146. }
  147. }
  148. if (slot) {
  149. *slot = Path(localAddr,remoteAddr);
  150. slot->received(now);
  151. #ifdef ZT_ENABLE_CLUSTER
  152. slot->setClusterSuboptimal(suboptimalPath);
  153. #endif
  154. _numPaths = np;
  155. }
  156. #ifdef ZT_ENABLE_CLUSTER
  157. if (RR->cluster)
  158. RR->cluster->broadcastHavePeer(_id);
  159. #endif
  160. } else {
  161. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),remoteAddr.toString().c_str());
  162. if ( (_vProto >= 5) && ( !((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0)) ) ) {
  163. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  164. outp.armor(_key,true);
  165. RR->node->putPacket(localAddr,remoteAddr,outp.data(),outp.size());
  166. } else {
  167. sendHELLO(localAddr,remoteAddr,now);
  168. }
  169. }
  170. }
  171. } else if (trustEstablished) {
  172. _pushDirectPaths(localAddr,remoteAddr,now);
  173. }
  174. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  175. _lastAnnouncedTo = now;
  176. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  177. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n)
  178. (*n)->tryAnnounceMulticastGroupsTo(SharedPtr<Peer>(this));
  179. }
  180. }
  181. void Peer::sendHELLO(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int ttl)
  182. {
  183. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  184. outp.append((unsigned char)ZT_PROTO_VERSION);
  185. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  186. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  187. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  188. outp.append(now);
  189. RR->identity.serialize(outp,false);
  190. atAddress.serialize(outp);
  191. outp.append((uint64_t)RR->topology->worldId());
  192. outp.append((uint64_t)RR->topology->worldTimestamp());
  193. outp.armor(_key,false); // HELLO is sent in the clear
  194. RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size(),ttl);
  195. }
  196. bool Peer::doPingAndKeepalive(uint64_t now,int inetAddressFamily)
  197. {
  198. Path *p = (Path *)0;
  199. if (inetAddressFamily != 0) {
  200. p = _getBestPath(now,inetAddressFamily);
  201. } else {
  202. p = _getBestPath(now);
  203. }
  204. if (p) {
  205. if ((now - p->lastReceived()) >= ZT_PEER_DIRECT_PING_DELAY) {
  206. //TRACE("PING %s(%s) after %llums/%llums send/receive inactivity",_id.address().toString().c_str(),p->address().toString().c_str(),now - p->lastSend(),now - p->lastReceived());
  207. sendHELLO(p->localAddress(),p->address(),now);
  208. p->sent(now);
  209. p->pinged(now);
  210. } else if ((now - std::max(p->lastSend(),p->lastKeepalive())) >= ZT_NAT_KEEPALIVE_DELAY) {
  211. //TRACE("NAT keepalive %s(%s) after %llums/%llums send/receive inactivity",_id.address().toString().c_str(),p->address().toString().c_str(),now - p->lastSend(),now - p->lastReceived());
  212. _natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads
  213. RR->node->putPacket(p->localAddress(),p->address(),&_natKeepaliveBuf,sizeof(_natKeepaliveBuf));
  214. p->sentKeepalive(now);
  215. }
  216. return true;
  217. }
  218. return false;
  219. }
  220. bool Peer::resetWithinScope(InetAddress::IpScope scope,uint64_t now)
  221. {
  222. unsigned int np = _numPaths;
  223. unsigned int x = 0;
  224. unsigned int y = 0;
  225. while (x < np) {
  226. if (_paths[x].address().ipScope() == scope) {
  227. // Resetting a path means sending a HELLO and then forgetting it. If we
  228. // get OK(HELLO) then it will be re-learned.
  229. sendHELLO(_paths[x].localAddress(),_paths[x].address(),now);
  230. } else {
  231. _paths[y++] = _paths[x];
  232. }
  233. ++x;
  234. }
  235. _numPaths = y;
  236. return (y < np);
  237. }
  238. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  239. {
  240. uint64_t bestV4 = 0,bestV6 = 0;
  241. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  242. if (_paths[p].active(now)) {
  243. uint64_t lr = _paths[p].lastReceived();
  244. if (lr) {
  245. if (_paths[p].address().isV4()) {
  246. if (lr >= bestV4) {
  247. bestV4 = lr;
  248. v4 = _paths[p].address();
  249. }
  250. } else if (_paths[p].address().isV6()) {
  251. if (lr >= bestV6) {
  252. bestV6 = lr;
  253. v6 = _paths[p].address();
  254. }
  255. }
  256. }
  257. }
  258. }
  259. }
  260. void Peer::clean(uint64_t now)
  261. {
  262. unsigned int np = _numPaths;
  263. unsigned int x = 0;
  264. unsigned int y = 0;
  265. while (x < np) {
  266. if (_paths[x].active(now))
  267. _paths[y++] = _paths[x];
  268. ++x;
  269. }
  270. _numPaths = y;
  271. }
  272. void Peer::_doDeadPathDetection(Path &p,const uint64_t now)
  273. {
  274. /* Dead path detection: if we have sent something to this peer and have not
  275. * yet received a reply, double check this path. The majority of outbound
  276. * packets including Ethernet frames do generate some kind of reply either
  277. * immediately or at some point in the near future. This will occasionally
  278. * (every NO_ANSWER_TIMEOUT ms) check paths unnecessarily if traffic that
  279. * does not generate a response is being sent such as multicast announcements
  280. * or frames belonging to unidirectional UDP protocols, but the cost is very
  281. * tiny and the benefit in reliability is very large. This takes care of many
  282. * failure modes including crap NATs that forget links and spurious changes
  283. * to physical network topology that cannot be otherwise detected.
  284. *
  285. * Each time we do this we increment a probation counter in the path. This
  286. * counter is reset on any packet receive over this path. If it reaches the
  287. * MAX_PROBATION threshold the path is considred dead. */
  288. if (
  289. (p.lastSend() > p.lastReceived()) &&
  290. ((p.lastSend() - p.lastReceived()) >= ZT_PEER_DEAD_PATH_DETECTION_NO_ANSWER_TIMEOUT) &&
  291. ((now - p.lastPing()) >= ZT_PEER_DEAD_PATH_DETECTION_NO_ANSWER_TIMEOUT) &&
  292. (!p.isClusterSuboptimal()) &&
  293. (!RR->topology->amRoot())
  294. ) {
  295. TRACE("%s(%s) does not seem to be answering in a timely manner, checking if dead (probation == %u)",_id.address().toString().c_str(),p.address().toString().c_str(),p.probation());
  296. if ( (_vProto >= 5) && ( !((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0)) ) ) {
  297. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  298. outp.armor(_key,true);
  299. p.send(RR,outp.data(),outp.size(),now);
  300. p.pinged(now);
  301. } else {
  302. sendHELLO(p.localAddress(),p.address(),now);
  303. p.sent(now);
  304. p.pinged(now);
  305. }
  306. p.increaseProbation();
  307. }
  308. }
  309. Path *Peer::_getBestPath(const uint64_t now)
  310. {
  311. Path *bestPath = (Path *)0;
  312. uint64_t bestPathScore = 0;
  313. for(unsigned int i=0;i<_numPaths;++i) {
  314. const uint64_t score = _paths[i].score();
  315. if ((score >= bestPathScore)&&(_paths[i].active(now))) {
  316. bestPathScore = score;
  317. bestPath = &(_paths[i]);
  318. }
  319. }
  320. if (bestPath)
  321. _doDeadPathDetection(*bestPath,now);
  322. return bestPath;
  323. }
  324. Path *Peer::_getBestPath(const uint64_t now,int inetAddressFamily)
  325. {
  326. Path *bestPath = (Path *)0;
  327. uint64_t bestPathScore = 0;
  328. for(unsigned int i=0;i<_numPaths;++i) {
  329. const uint64_t score = _paths[i].score();
  330. if (((int)_paths[i].address().ss_family == inetAddressFamily)&&(score >= bestPathScore)&&(_paths[i].active(now))) {
  331. bestPathScore = score;
  332. bestPath = &(_paths[i]);
  333. }
  334. }
  335. if (bestPath)
  336. _doDeadPathDetection(*bestPath,now);
  337. return bestPath;
  338. }
  339. bool Peer::_pushDirectPaths(const InetAddress &localAddr,const InetAddress &toAddress,uint64_t now)
  340. {
  341. #ifdef ZT_ENABLE_CLUSTER
  342. // Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
  343. if (RR->cluster)
  344. return false;
  345. #endif
  346. if ((now - _lastDirectPathPushSent) < ZT_DIRECT_PATH_PUSH_INTERVAL)
  347. return false;
  348. else _lastDirectPathPushSent = now;
  349. std::vector<InetAddress> pathsToPush;
  350. std::vector<InetAddress> dps(RR->node->directPaths());
  351. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  352. pathsToPush.push_back(*i);
  353. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  354. for(unsigned long i=0,added=0;i<sym.size();++i) {
  355. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  356. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  357. pathsToPush.push_back(tmp);
  358. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  359. break;
  360. }
  361. }
  362. if (pathsToPush.empty())
  363. return false;
  364. #ifdef ZT_TRACE
  365. {
  366. std::string ps;
  367. for(std::vector<InetAddress>::const_iterator p(pathsToPush.begin());p!=pathsToPush.end();++p) {
  368. if (ps.length() > 0)
  369. ps.push_back(',');
  370. ps.append(p->toString());
  371. }
  372. TRACE("pushing %u direct paths to %s: %s",(unsigned int)pathsToPush.size(),_id.address().toString().c_str(),ps.c_str());
  373. }
  374. #endif
  375. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  376. while (p != pathsToPush.end()) {
  377. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  378. outp.addSize(2); // leave room for count
  379. unsigned int count = 0;
  380. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  381. uint8_t addressType = 4;
  382. switch(p->ss_family) {
  383. case AF_INET:
  384. break;
  385. case AF_INET6:
  386. addressType = 6;
  387. break;
  388. default: // we currently only push IP addresses
  389. ++p;
  390. continue;
  391. }
  392. outp.append((uint8_t)0); // no flags
  393. outp.append((uint16_t)0); // no extensions
  394. outp.append(addressType);
  395. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  396. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  397. outp.append((uint16_t)p->port());
  398. ++count;
  399. ++p;
  400. }
  401. if (count) {
  402. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  403. outp.armor(_key,true);
  404. RR->node->putPacket(localAddr,toAddress,outp.data(),outp.size(),0);
  405. }
  406. }
  407. return true;
  408. }
  409. } // namespace ZeroTier