Peer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. namespace ZeroTier {
  28. // Used to send varying values for NAT keepalive
  29. static uint32_t _natKeepaliveBuf = 0;
  30. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  31. RR(renv),
  32. _lastUsed(0),
  33. _lastReceive(0),
  34. _lastUnicastFrame(0),
  35. _lastMulticastFrame(0),
  36. _lastAnnouncedTo(0),
  37. _lastDirectPathPushSent(0),
  38. _lastDirectPathPushReceive(0),
  39. _vProto(0),
  40. _vMajor(0),
  41. _vMinor(0),
  42. _vRevision(0),
  43. _id(peerIdentity),
  44. _numPaths(0),
  45. _latency(0),
  46. _directPathPushCutoffCount(0)
  47. {
  48. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  49. throw std::runtime_error("new peer identity key agreement failed");
  50. }
  51. void Peer::received(
  52. const SharedPtr<Path> &path,
  53. unsigned int hops,
  54. uint64_t packetId,
  55. Packet::Verb verb,
  56. uint64_t inRePacketId,
  57. Packet::Verb inReVerb,
  58. const bool trustEstablished)
  59. {
  60. const uint64_t now = RR->node->now();
  61. #ifdef ZT_ENABLE_CLUSTER
  62. bool suboptimalPath = false;
  63. if ((RR->cluster)&&(hops == 0)) {
  64. // Note: findBetterEndpoint() is first since we still want to check
  65. // for a better endpoint even if we don't actually send a redirect.
  66. InetAddress redirectTo;
  67. 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(),path->address(),false)) ) {
  68. if (_vProto >= 5) {
  69. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  70. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  71. outp.append((uint16_t)1); // count == 1
  72. outp.append((uint8_t)ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT); // flags: cluster redirect
  73. outp.append((uint16_t)0); // no extensions
  74. if (redirectTo.ss_family == AF_INET) {
  75. outp.append((uint8_t)4);
  76. outp.append((uint8_t)6);
  77. outp.append(redirectTo.rawIpData(),4);
  78. } else {
  79. outp.append((uint8_t)6);
  80. outp.append((uint8_t)18);
  81. outp.append(redirectTo.rawIpData(),16);
  82. }
  83. outp.append((uint16_t)redirectTo.port());
  84. outp.armor(_key,true);
  85. path->send(RR,outp.data(),outp.size(),now);
  86. } else {
  87. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  88. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  89. outp.append((uint8_t)0); // no flags
  90. RR->identity.address().appendTo(outp);
  91. outp.append((uint16_t)redirectTo.port());
  92. if (redirectTo.ss_family == AF_INET) {
  93. outp.append((uint8_t)4);
  94. outp.append(redirectTo.rawIpData(),4);
  95. } else {
  96. outp.append((uint8_t)16);
  97. outp.append(redirectTo.rawIpData(),16);
  98. }
  99. outp.armor(_key,true);
  100. path->send(RR,outp.data(),outp.size(),now);
  101. }
  102. suboptimalPath = true;
  103. }
  104. }
  105. #endif
  106. _lastReceive = now;
  107. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  108. _lastUnicastFrame = now;
  109. else if (verb == Packet::VERB_MULTICAST_FRAME)
  110. _lastMulticastFrame = now;
  111. if (hops == 0) {
  112. bool pathIsConfirmed = false;
  113. {
  114. Mutex::Lock _l(_paths_m);
  115. for(unsigned int p=0;p<_numPaths;++p) {
  116. if (_paths[p].path->address() == path->address()) {
  117. _paths[p].lastReceive = now;
  118. _paths[p].path = path; // local address may have changed!
  119. #ifdef ZT_ENABLE_CLUSTER
  120. _paths[p].clusterWeights = (unsigned int)(!suboptimalPath);
  121. #endif
  122. pathIsConfirmed = true;
  123. break;
  124. }
  125. }
  126. }
  127. if ( (!pathIsConfirmed) && (RR->node->shouldUsePathForZeroTierTraffic(path->localAddress(),path->address())) ) {
  128. if (verb == Packet::VERB_OK) {
  129. Mutex::Lock _l(_paths_m);
  130. unsigned int slot;
  131. if (_numPaths < ZT_MAX_PEER_NETWORK_PATHS) {
  132. slot = _numPaths++;
  133. } else {
  134. // First try to replace the worst within the same address family, if possible
  135. int worstSlot = -1;
  136. uint64_t worstScore = 0xffffffffffffffffULL;
  137. for(unsigned int p=0;p<_numPaths;++p) {
  138. if (_paths[p].path->address().ss_family == path->address().ss_family) {
  139. const uint64_t s = _pathScore(p);
  140. if (s < worstScore) {
  141. worstScore = s;
  142. worstSlot = (int)p;
  143. }
  144. }
  145. }
  146. if (worstSlot >= 0) {
  147. slot = (unsigned int)worstSlot;
  148. } else {
  149. slot = ZT_MAX_PEER_NETWORK_PATHS - 1;
  150. for(unsigned int p=0;p<_numPaths;++p) {
  151. const uint64_t s = _pathScore(p);
  152. if (s < worstScore) {
  153. worstScore = s;
  154. slot = p;
  155. }
  156. }
  157. }
  158. }
  159. _paths[slot].lastReceive = now;
  160. _paths[slot].path = path;
  161. #ifdef ZT_ENABLE_CLUSTER
  162. _paths[slot].clusterWeights = (unsigned int)(!suboptimalPath);
  163. if (RR->cluster)
  164. RR->cluster->broadcastHavePeer(_id);
  165. #else
  166. _paths[slot].clusterWeights = 1;
  167. #endif
  168. } else {
  169. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),path->address().toString().c_str());
  170. if ( (_vProto >= 5) && ( !((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0)) ) ) {
  171. // Newer than 1.1.0 can use ECHO, which is smaller
  172. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  173. outp.armor(_key,true);
  174. path->send(RR,outp.data(),outp.size(),now);
  175. } else {
  176. // For backward compatibility we send HELLO to ancient nodes
  177. sendHELLO(path->localAddress(),path->address(),now);
  178. }
  179. }
  180. }
  181. } else if (trustEstablished) {
  182. // Send PUSH_DIRECT_PATHS if hops>0 (relayed) and we have a trust relationship (common network membership)
  183. _pushDirectPaths(path,now);
  184. }
  185. if ((now - _lastAnnouncedTo) >= ((ZT_MULTICAST_LIKE_EXPIRE / 2) - 1000)) {
  186. _lastAnnouncedTo = now;
  187. const std::vector< SharedPtr<Network> > networks(RR->node->allNetworks());
  188. for(std::vector< SharedPtr<Network> >::const_iterator n(networks.begin());n!=networks.end();++n)
  189. (*n)->tryAnnounceMulticastGroupsTo(SharedPtr<Peer>(this));
  190. }
  191. }
  192. bool Peer::hasActivePathTo(uint64_t now,const InetAddress &addr) const
  193. {
  194. Mutex::Lock _l(_paths_m);
  195. for(unsigned int p=0;p<_numPaths;++p) {
  196. if ( (_paths[p].path->address() == addr) && (_paths[p].path->alive(now)) )
  197. return true;
  198. }
  199. return false;
  200. }
  201. void Peer::setClusterOptimal(const InetAddress &addr)
  202. {
  203. Mutex::Lock _l(_paths_m);
  204. int opt = -1;
  205. for(unsigned int p=0;p<_numPaths;++p) {
  206. if (_paths[p].path->address() == addr) {
  207. opt = (int)p;
  208. break;
  209. }
  210. }
  211. if (opt >= 0) { // only change anything if we have the optimal path
  212. for(unsigned int p=0;p<_numPaths;++p) {
  213. if (_paths[p].path->address().ss_family == addr.ss_family)
  214. _paths[p].clusterWeights = ((int)p == opt) ? 2 : 0;
  215. }
  216. }
  217. }
  218. bool Peer::sendDirect(const void *data,unsigned int len,uint64_t now,bool forceEvenIfDead)
  219. {
  220. Mutex::Lock _l(_paths_m);
  221. int bestp = -1;
  222. uint64_t best = 0ULL;
  223. for(unsigned int p=0;p<_numPaths;++p) {
  224. if (_paths[p].path->alive(now)||(forceEvenIfDead)) {
  225. const uint64_t s = _pathScore(p);
  226. if (s >= best) {
  227. best = s;
  228. bestp = (int)p;
  229. }
  230. }
  231. }
  232. if (bestp >= 0) {
  233. return _paths[bestp].path->send(RR,data,len,now);
  234. } else {
  235. return false;
  236. }
  237. }
  238. SharedPtr<Path> Peer::getBestPath(uint64_t now)
  239. {
  240. Mutex::Lock _l(_paths_m);
  241. int bestp = -1;
  242. uint64_t best = 0ULL;
  243. for(unsigned int p=0;p<_numPaths;++p) {
  244. const uint64_t s = _pathScore(p);
  245. if (s >= best) {
  246. best = s;
  247. bestp = (int)p;
  248. }
  249. }
  250. if (bestp >= 0) {
  251. return _paths[bestp].path;
  252. } else {
  253. return SharedPtr<Path>();
  254. }
  255. }
  256. void Peer::sendHELLO(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now)
  257. {
  258. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  259. outp.append((unsigned char)ZT_PROTO_VERSION);
  260. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  261. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  262. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  263. outp.append(now);
  264. RR->identity.serialize(outp,false);
  265. atAddress.serialize(outp);
  266. outp.append((uint64_t)RR->topology->worldId());
  267. outp.append((uint64_t)RR->topology->worldTimestamp());
  268. outp.armor(_key,false); // HELLO is sent in the clear
  269. RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size());
  270. }
  271. bool Peer::doPingAndKeepalive(uint64_t now,int inetAddressFamily)
  272. {
  273. Mutex::Lock _l(_paths_m);
  274. int bestp = -1;
  275. uint64_t best = 0ULL;
  276. for(unsigned int p=0;p<_numPaths;++p) {
  277. if ((inetAddressFamily < 0)||((int)_paths[p].path->address().ss_family == inetAddressFamily)) {
  278. const uint64_t s = _pathScore(p);
  279. if (s >= best) {
  280. best = s;
  281. bestp = (int)p;
  282. }
  283. }
  284. }
  285. if (bestp >= 0) {
  286. if ((now - _paths[bestp].lastReceive) >= ZT_PEER_PING_PERIOD) {
  287. sendHELLO(_paths[bestp].path->localAddress(),_paths[bestp].path->address(),now);
  288. } else if (_paths[bestp].path->needsHeartbeat(now)) {
  289. _natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads
  290. _paths[bestp].path->send(RR,&_natKeepaliveBuf,sizeof(_natKeepaliveBuf),now);
  291. }
  292. return true;
  293. } else {
  294. return false;
  295. }
  296. }
  297. bool Peer::hasActiveDirectPath(uint64_t now) const
  298. {
  299. Mutex::Lock _l(_paths_m);
  300. for(unsigned int p=0;p<_numPaths;++p) {
  301. if (_paths[p].path->alive(now))
  302. return true;
  303. }
  304. return false;
  305. }
  306. bool Peer::resetWithinScope(InetAddress::IpScope scope,uint64_t now)
  307. {
  308. Mutex::Lock _l(_paths_m);
  309. unsigned int np = _numPaths;
  310. unsigned int x = 0;
  311. unsigned int y = 0;
  312. while (x < np) {
  313. if (_paths[x].path->address().ipScope() == scope) {
  314. // Resetting a path means sending a HELLO and then forgetting it. If we
  315. // get OK(HELLO) then it will be re-learned.
  316. sendHELLO(_paths[x].path->localAddress(),_paths[x].path->address(),now);
  317. } else {
  318. if (x != y) {
  319. _paths[y].lastReceive = _paths[x].lastReceive;
  320. _paths[y].path = _paths[x].path;
  321. _paths[y].clusterWeights = _paths[x].clusterWeights;
  322. }
  323. ++y;
  324. }
  325. ++x;
  326. }
  327. _numPaths = y;
  328. return (y < np);
  329. }
  330. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  331. {
  332. Mutex::Lock _l(_paths_m);
  333. int bestp4 = -1,bestp6 = -1;
  334. uint64_t best4 = 0ULL,best6 = 0ULL;
  335. for(unsigned int p=0;p<_numPaths;++p) {
  336. if (_paths[p].path->address().ss_family == AF_INET) {
  337. const uint64_t s = _pathScore(p);
  338. if (s >= best4) {
  339. best4 = s;
  340. bestp4 = (int)p;
  341. }
  342. } else if (_paths[p].path->address().ss_family == AF_INET6) {
  343. const uint64_t s = _pathScore(p);
  344. if (s >= best6) {
  345. best6 = s;
  346. bestp6 = (int)p;
  347. }
  348. }
  349. }
  350. if (bestp4 >= 0)
  351. v4 = _paths[bestp4].path->address();
  352. if (bestp6 >= 0)
  353. v6 = _paths[bestp6].path->address();
  354. }
  355. void Peer::clean(uint64_t now)
  356. {
  357. Mutex::Lock _l(_paths_m);
  358. unsigned int np = _numPaths;
  359. unsigned int x = 0;
  360. unsigned int y = 0;
  361. while (x < np) {
  362. if ((now - _paths[x].lastReceive) <= ZT_PEER_PATH_EXPIRATION) {
  363. if (y != x) {
  364. _paths[y].lastReceive = _paths[x].lastReceive;
  365. _paths[y].path = _paths[x].path;
  366. _paths[y].clusterWeights = _paths[x].clusterWeights;
  367. }
  368. ++y;
  369. }
  370. ++x;
  371. }
  372. _numPaths = y;
  373. }
  374. bool Peer::_pushDirectPaths(const SharedPtr<Path> &path,uint64_t now)
  375. {
  376. #ifdef ZT_ENABLE_CLUSTER
  377. // Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
  378. if (RR->cluster)
  379. return false;
  380. #endif
  381. if ((now - _lastDirectPathPushSent) < ZT_DIRECT_PATH_PUSH_INTERVAL)
  382. return false;
  383. else _lastDirectPathPushSent = now;
  384. std::vector<InetAddress> pathsToPush;
  385. std::vector<InetAddress> dps(RR->node->directPaths());
  386. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  387. pathsToPush.push_back(*i);
  388. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  389. for(unsigned long i=0,added=0;i<sym.size();++i) {
  390. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  391. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  392. pathsToPush.push_back(tmp);
  393. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  394. break;
  395. }
  396. }
  397. if (pathsToPush.empty())
  398. return false;
  399. #ifdef ZT_TRACE
  400. {
  401. std::string ps;
  402. for(std::vector<InetAddress>::const_iterator p(pathsToPush.begin());p!=pathsToPush.end();++p) {
  403. if (ps.length() > 0)
  404. ps.push_back(',');
  405. ps.append(p->toString());
  406. }
  407. TRACE("pushing %u direct paths to %s: %s",(unsigned int)pathsToPush.size(),_id.address().toString().c_str(),ps.c_str());
  408. }
  409. #endif
  410. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  411. while (p != pathsToPush.end()) {
  412. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  413. outp.addSize(2); // leave room for count
  414. unsigned int count = 0;
  415. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  416. uint8_t addressType = 4;
  417. switch(p->ss_family) {
  418. case AF_INET:
  419. break;
  420. case AF_INET6:
  421. addressType = 6;
  422. break;
  423. default: // we currently only push IP addresses
  424. ++p;
  425. continue;
  426. }
  427. outp.append((uint8_t)0); // no flags
  428. outp.append((uint16_t)0); // no extensions
  429. outp.append(addressType);
  430. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  431. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  432. outp.append((uint16_t)p->port());
  433. ++count;
  434. ++p;
  435. }
  436. if (count) {
  437. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  438. outp.armor(_key,true);
  439. path->send(RR,outp.data(),outp.size(),now);
  440. }
  441. }
  442. return true;
  443. }
  444. } // namespace ZeroTier