Peer.cpp 14 KB

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