Peer.cpp 15 KB

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