Peer.cpp 14 KB

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