Peer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. #ifndef AF_MAX
  28. #if AF_INET > AF_INET6
  29. #define AF_MAX AF_INET
  30. #else
  31. #define AF_MAX AF_INET6
  32. #endif
  33. #endif
  34. namespace ZeroTier {
  35. // Used to send varying values for NAT keepalive
  36. static uint32_t _natKeepaliveBuf = 0;
  37. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  38. _lastUsed(0),
  39. _lastReceive(0),
  40. _lastUnicastFrame(0),
  41. _lastMulticastFrame(0),
  42. _lastAnnouncedTo(0),
  43. _lastDirectPathPushSent(0),
  44. _lastDirectPathPushReceive(0),
  45. RR(renv),
  46. _remoteClusterOptimal4(0),
  47. _vProto(0),
  48. _vMajor(0),
  49. _vMinor(0),
  50. _vRevision(0),
  51. _id(peerIdentity),
  52. _numPaths(0),
  53. _latency(0),
  54. _directPathPushCutoffCount(0)
  55. {
  56. memset(_remoteClusterOptimal6,0,sizeof(_remoteClusterOptimal6));
  57. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  58. throw std::runtime_error("new peer identity key agreement failed");
  59. }
  60. void Peer::received(
  61. const SharedPtr<Path> &path,
  62. unsigned int hops,
  63. uint64_t packetId,
  64. Packet::Verb verb,
  65. uint64_t inRePacketId,
  66. Packet::Verb inReVerb,
  67. const bool trustEstablished)
  68. {
  69. const uint64_t now = RR->node->now();
  70. #ifdef ZT_ENABLE_CLUSTER
  71. bool suboptimalPath = false;
  72. if ((RR->cluster)&&(hops == 0)) {
  73. // Note: findBetterEndpoint() is first since we still want to check
  74. // for a better endpoint even if we don't actually send a redirect.
  75. InetAddress redirectTo;
  76. 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)) ) {
  77. if (_vProto >= 5) {
  78. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  79. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  80. outp.append((uint16_t)1); // count == 1
  81. outp.append((uint8_t)ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT); // flags: cluster redirect
  82. outp.append((uint16_t)0); // no extensions
  83. if (redirectTo.ss_family == AF_INET) {
  84. outp.append((uint8_t)4);
  85. outp.append((uint8_t)6);
  86. outp.append(redirectTo.rawIpData(),4);
  87. } else {
  88. outp.append((uint8_t)6);
  89. outp.append((uint8_t)18);
  90. outp.append(redirectTo.rawIpData(),16);
  91. }
  92. outp.append((uint16_t)redirectTo.port());
  93. outp.armor(_key,true);
  94. path->send(RR,outp.data(),outp.size(),now);
  95. } else {
  96. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  97. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  98. outp.append((uint8_t)0); // no flags
  99. RR->identity.address().appendTo(outp);
  100. outp.append((uint16_t)redirectTo.port());
  101. if (redirectTo.ss_family == AF_INET) {
  102. outp.append((uint8_t)4);
  103. outp.append(redirectTo.rawIpData(),4);
  104. } else {
  105. outp.append((uint8_t)16);
  106. outp.append(redirectTo.rawIpData(),16);
  107. }
  108. outp.armor(_key,true);
  109. path->send(RR,outp.data(),outp.size(),now);
  110. }
  111. suboptimalPath = true;
  112. }
  113. }
  114. #endif
  115. _lastReceive = now;
  116. if ((verb == Packet::VERB_FRAME)||(verb == Packet::VERB_EXT_FRAME))
  117. _lastUnicastFrame = now;
  118. else if (verb == Packet::VERB_MULTICAST_FRAME)
  119. _lastMulticastFrame = now;
  120. if (hops == 0) {
  121. bool pathIsConfirmed = false;
  122. {
  123. Mutex::Lock _l(_paths_m);
  124. for(unsigned int p=0;p<_numPaths;++p) {
  125. if (_paths[p].path->address() == path->address()) {
  126. _paths[p].lastReceive = now;
  127. _paths[p].path = path; // local address may have changed!
  128. #ifdef ZT_ENABLE_CLUSTER
  129. _paths[p].localClusterSuboptimal = suboptimalPath;
  130. #endif
  131. pathIsConfirmed = true;
  132. break;
  133. }
  134. }
  135. }
  136. if ( (!pathIsConfirmed) && (RR->node->shouldUsePathForZeroTierTraffic(path->localAddress(),path->address())) ) {
  137. if (verb == Packet::VERB_OK) {
  138. Mutex::Lock _l(_paths_m);
  139. // Since this is a new path, figure out where to put it (possibly replacing an old/dead one)
  140. unsigned int slot;
  141. if (_numPaths < ZT_MAX_PEER_NETWORK_PATHS) {
  142. slot = _numPaths++;
  143. } else {
  144. // First try to replace the worst within the same address family, if possible
  145. int worstSlot = -1;
  146. uint64_t worstScore = 0xffffffffffffffffULL;
  147. for(unsigned int p=0;p<_numPaths;++p) {
  148. if (_paths[p].path->address().ss_family == path->address().ss_family) {
  149. const uint64_t s = _pathScore(p,now);
  150. if (s < worstScore) {
  151. worstScore = s;
  152. worstSlot = (int)p;
  153. }
  154. }
  155. }
  156. if (worstSlot >= 0) {
  157. slot = (unsigned int)worstSlot;
  158. } else {
  159. // If we can't find one with the same family, replace the worst of any family
  160. slot = ZT_MAX_PEER_NETWORK_PATHS - 1;
  161. for(unsigned int p=0;p<_numPaths;++p) {
  162. const uint64_t s = _pathScore(p,now);
  163. if (s < worstScore) {
  164. worstScore = s;
  165. slot = p;
  166. }
  167. }
  168. }
  169. }
  170. _paths[slot].lastReceive = now;
  171. _paths[slot].path = path;
  172. #ifdef ZT_ENABLE_CLUSTER
  173. _paths[slot].localClusterSuboptimal = suboptimalPath;
  174. if (RR->cluster)
  175. RR->cluster->broadcastHavePeer(_id);
  176. #endif
  177. } else {
  178. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),path->address().toString().c_str());
  179. attemptToContactAt(path->localAddress(),path->address(),now);
  180. path->sent(now);
  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) && ((now - _paths[p].lastReceive) <= ZT_PEER_PATH_EXPIRATION) && (_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 ( ((now - _paths[p].lastReceive) <= ZT_PEER_PATH_EXPIRATION) && (_paths[p].path->alive(now)||(forceEvenIfDead)) ) {
  210. const uint64_t s = _pathScore(p,now);
  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,bool includeExpired)
  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. if ( ((now - _paths[p].lastReceive) <= ZT_PEER_PATH_EXPIRATION) || (includeExpired) ) {
  230. const uint64_t s = _pathScore(p,now);
  231. if (s >= best) {
  232. best = s;
  233. bestp = (int)p;
  234. }
  235. }
  236. }
  237. if (bestp >= 0) {
  238. return _paths[bestp].path;
  239. } else {
  240. return SharedPtr<Path>();
  241. }
  242. }
  243. void Peer::sendHELLO(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now)
  244. {
  245. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  246. outp.append((unsigned char)ZT_PROTO_VERSION);
  247. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  248. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  249. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  250. outp.append(now);
  251. RR->identity.serialize(outp,false);
  252. atAddress.serialize(outp);
  253. outp.append((uint64_t)RR->topology->worldId());
  254. outp.append((uint64_t)RR->topology->worldTimestamp());
  255. outp.armor(_key,false); // HELLO is sent in the clear
  256. RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size());
  257. }
  258. void Peer::attemptToContactAt(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now)
  259. {
  260. if ( (_vProto >= 5) && ( !((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0)) ) ) {
  261. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  262. outp.armor(_key,true);
  263. RR->node->putPacket(localAddr,atAddress,outp.data(),outp.size());
  264. } else {
  265. sendHELLO(localAddr,atAddress,now);
  266. }
  267. }
  268. bool Peer::doPingAndKeepalive(uint64_t now,int inetAddressFamily)
  269. {
  270. Mutex::Lock _l(_paths_m);
  271. int bestp = -1;
  272. uint64_t best = 0ULL;
  273. for(unsigned int p=0;p<_numPaths;++p) {
  274. if ( ((now - _paths[p].lastReceive) <= ZT_PEER_PATH_EXPIRATION) && ((inetAddressFamily < 0)||((int)_paths[p].path->address().ss_family == inetAddressFamily)) ) {
  275. const uint64_t s = _pathScore(p,now);
  276. if (s >= best) {
  277. best = s;
  278. bestp = (int)p;
  279. }
  280. }
  281. }
  282. if (bestp >= 0) {
  283. if ((now - _paths[bestp].lastReceive) >= ZT_PEER_PING_PERIOD) {
  284. attemptToContactAt(_paths[bestp].path->localAddress(),_paths[bestp].path->address(),now);
  285. _paths[bestp].path->sent(now);
  286. } else if (_paths[bestp].path->needsHeartbeat(now)) {
  287. _natKeepaliveBuf += (uint32_t)((now * 0x9e3779b1) >> 1); // tumble this around to send constantly varying (meaningless) payloads
  288. _paths[bestp].path->send(RR,&_natKeepaliveBuf,sizeof(_natKeepaliveBuf),now);
  289. }
  290. return true;
  291. } else {
  292. return false;
  293. }
  294. }
  295. bool Peer::hasActiveDirectPath(uint64_t now) const
  296. {
  297. Mutex::Lock _l(_paths_m);
  298. for(unsigned int p=0;p<_numPaths;++p) {
  299. if (((now - _paths[p].lastReceive) <= ZT_PEER_PATH_EXPIRATION)&&(_paths[p].path->alive(now)))
  300. return true;
  301. }
  302. return false;
  303. }
  304. bool Peer::resetWithinScope(InetAddress::IpScope scope,int inetAddressFamily,uint64_t now)
  305. {
  306. Mutex::Lock _l(_paths_m);
  307. bool resetSomething = false;
  308. for(unsigned int p=0;p<_numPaths;++p) {
  309. if ( (_paths[p].path->address().ss_family == inetAddressFamily) && (_paths[p].path->address().ipScope() == scope) ) {
  310. attemptToContactAt(_paths[p].path->localAddress(),_paths[p].path->address(),now);
  311. _paths[p].path->sent(now);
  312. _paths[p].lastReceive >>= 2; // de-prioritize heavily vs. other paths, will get reset if we get OK(HELLO) or other traffic
  313. resetSomething = true;
  314. }
  315. }
  316. return resetSomething;
  317. }
  318. void Peer::getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  319. {
  320. Mutex::Lock _l(_paths_m);
  321. int bestp4 = -1,bestp6 = -1;
  322. uint64_t best4 = 0ULL,best6 = 0ULL;
  323. for(unsigned int p=0;p<_numPaths;++p) {
  324. if ( ((now - _paths[p].lastReceive) <= ZT_PEER_PATH_EXPIRATION) && (_paths[p].path->alive(now)) ) {
  325. if (_paths[p].path->address().ss_family == AF_INET) {
  326. const uint64_t s = _pathScore(p,now);
  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,now);
  333. if (s >= best6) {
  334. best6 = s;
  335. bestp6 = (int)p;
  336. }
  337. }
  338. }
  339. }
  340. if (bestp4 >= 0)
  341. v4 = _paths[bestp4].path->address();
  342. if (bestp6 >= 0)
  343. v6 = _paths[bestp6].path->address();
  344. }
  345. bool Peer::_pushDirectPaths(const SharedPtr<Path> &path,uint64_t now)
  346. {
  347. #ifdef ZT_ENABLE_CLUSTER
  348. // Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
  349. if (RR->cluster)
  350. return false;
  351. #endif
  352. if ((now - _lastDirectPathPushSent) < ZT_DIRECT_PATH_PUSH_INTERVAL)
  353. return false;
  354. else _lastDirectPathPushSent = now;
  355. std::vector<InetAddress> pathsToPush;
  356. std::vector<InetAddress> dps(RR->node->directPaths());
  357. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  358. pathsToPush.push_back(*i);
  359. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  360. for(unsigned long i=0,added=0;i<sym.size();++i) {
  361. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  362. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  363. pathsToPush.push_back(tmp);
  364. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  365. break;
  366. }
  367. }
  368. if (pathsToPush.empty())
  369. return false;
  370. #ifdef ZT_TRACE
  371. {
  372. std::string ps;
  373. for(std::vector<InetAddress>::const_iterator p(pathsToPush.begin());p!=pathsToPush.end();++p) {
  374. if (ps.length() > 0)
  375. ps.push_back(',');
  376. ps.append(p->toString());
  377. }
  378. TRACE("pushing %u direct paths to %s: %s",(unsigned int)pathsToPush.size(),_id.address().toString().c_str(),ps.c_str());
  379. }
  380. #endif
  381. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  382. while (p != pathsToPush.end()) {
  383. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  384. outp.addSize(2); // leave room for count
  385. unsigned int count = 0;
  386. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  387. uint8_t addressType = 4;
  388. switch(p->ss_family) {
  389. case AF_INET:
  390. break;
  391. case AF_INET6:
  392. addressType = 6;
  393. break;
  394. default: // we currently only push IP addresses
  395. ++p;
  396. continue;
  397. }
  398. outp.append((uint8_t)0); // no flags
  399. outp.append((uint16_t)0); // no extensions
  400. outp.append(addressType);
  401. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  402. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  403. outp.append((uint16_t)p->port());
  404. ++count;
  405. ++p;
  406. }
  407. if (count) {
  408. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  409. outp.armor(_key,true);
  410. path->send(RR,outp.data(),outp.size(),now);
  411. }
  412. }
  413. return true;
  414. }
  415. } // namespace ZeroTier