Peer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include "../version.h"
  27. #include "Constants.hpp"
  28. #include "Peer.hpp"
  29. #include "Node.hpp"
  30. #include "Switch.hpp"
  31. #include "Network.hpp"
  32. #include "SelfAwareness.hpp"
  33. #include "Packet.hpp"
  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. _vProto(0),
  50. _vMajor(0),
  51. _vMinor(0),
  52. _vRevision(0),
  53. _id(peerIdentity),
  54. _latency(0),
  55. _directPathPushCutoffCount(0),
  56. _credentialsCutoffCount(0)
  57. {
  58. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  59. throw std::runtime_error("new peer identity key agreement failed");
  60. }
  61. void Peer::received(
  62. void *tPtr,
  63. const SharedPtr<Path> &path,
  64. const unsigned int hops,
  65. const uint64_t packetId,
  66. const Packet::Verb verb,
  67. const uint64_t inRePacketId,
  68. const Packet::Verb inReVerb,
  69. const bool trustEstablished)
  70. {
  71. const uint64_t now = RR->node->now();
  72. #ifdef ZT_ENABLE_CLUSTER
  73. bool isClusterSuboptimalPath = false;
  74. if ((RR->cluster)&&(hops == 0)) {
  75. // Note: findBetterEndpoint() is first since we still want to check
  76. // for a better endpoint even if we don't actually send a redirect.
  77. InetAddress redirectTo;
  78. 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)) ) {
  79. if (_vProto >= 5) {
  80. // For newer peers we can send a more idiomatic verb: PUSH_DIRECT_PATHS.
  81. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  82. outp.append((uint16_t)1); // count == 1
  83. outp.append((uint8_t)ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT); // flags: cluster redirect
  84. outp.append((uint16_t)0); // no extensions
  85. if (redirectTo.ss_family == AF_INET) {
  86. outp.append((uint8_t)4);
  87. outp.append((uint8_t)6);
  88. outp.append(redirectTo.rawIpData(),4);
  89. } else {
  90. outp.append((uint8_t)6);
  91. outp.append((uint8_t)18);
  92. outp.append(redirectTo.rawIpData(),16);
  93. }
  94. outp.append((uint16_t)redirectTo.port());
  95. outp.armor(_key,true,path->nextOutgoingCounter());
  96. path->send(RR,tPtr,outp.data(),outp.size(),now);
  97. } else {
  98. // For older peers we use RENDEZVOUS to coax them into contacting us elsewhere.
  99. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  100. outp.append((uint8_t)0); // no flags
  101. RR->identity.address().appendTo(outp);
  102. outp.append((uint16_t)redirectTo.port());
  103. if (redirectTo.ss_family == AF_INET) {
  104. outp.append((uint8_t)4);
  105. outp.append(redirectTo.rawIpData(),4);
  106. } else {
  107. outp.append((uint8_t)16);
  108. outp.append(redirectTo.rawIpData(),16);
  109. }
  110. outp.armor(_key,true,path->nextOutgoingCounter());
  111. path->send(RR,tPtr,outp.data(),outp.size(),now);
  112. }
  113. isClusterSuboptimalPath = true;
  114. }
  115. }
  116. #endif
  117. _lastReceive = now;
  118. switch (verb) {
  119. case Packet::VERB_FRAME:
  120. case Packet::VERB_EXT_FRAME:
  121. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  122. case Packet::VERB_NETWORK_CONFIG:
  123. case Packet::VERB_MULTICAST_FRAME:
  124. _lastNontrivialReceive = now;
  125. break;
  126. default: break;
  127. }
  128. if (trustEstablished) {
  129. _lastTrustEstablishedPacketReceived = now;
  130. path->trustedPacketReceived(now);
  131. }
  132. if (_vProto >= 9)
  133. path->updateLinkQuality((unsigned int)(packetId & 7));
  134. if (hops == 0) {
  135. bool pathAlreadyKnown = false;
  136. {
  137. Mutex::Lock _l(_paths_m);
  138. if ((path->address().ss_family == AF_INET)&&(_v4Path.p)) {
  139. const struct sockaddr_in *const r = reinterpret_cast<const struct sockaddr_in *>(&(path->address()));
  140. const struct sockaddr_in *const l = reinterpret_cast<const struct sockaddr_in *>(&(_v4Path.p->address()));
  141. const struct sockaddr_in *const rl = reinterpret_cast<const struct sockaddr_in *>(&(path->localAddress()));
  142. const struct sockaddr_in *const ll = reinterpret_cast<const struct sockaddr_in *>(&(_v4Path.p->localAddress()));
  143. if ((r->sin_addr.s_addr == l->sin_addr.s_addr)&&(r->sin_port == l->sin_port)&&(rl->sin_addr.s_addr == ll->sin_addr.s_addr)&&(rl->sin_port == ll->sin_port)) {
  144. _v4Path.lr = now;
  145. #ifdef ZT_ENABLE_CLUSTER
  146. _v4Path.localClusterSuboptimal = isClusterSuboptimalPath;
  147. #endif
  148. pathAlreadyKnown = true;
  149. }
  150. } else if ((path->address().ss_family == AF_INET6)&&(_v6Path.p)) {
  151. const struct sockaddr_in6 *const r = reinterpret_cast<const struct sockaddr_in6 *>(&(path->address()));
  152. const struct sockaddr_in6 *const l = reinterpret_cast<const struct sockaddr_in6 *>(&(_v6Path.p->address()));
  153. const struct sockaddr_in6 *const rl = reinterpret_cast<const struct sockaddr_in6 *>(&(path->localAddress()));
  154. const struct sockaddr_in6 *const ll = reinterpret_cast<const struct sockaddr_in6 *>(&(_v6Path.p->localAddress()));
  155. if ((!memcmp(r->sin6_addr.s6_addr,l->sin6_addr.s6_addr,16))&&(r->sin6_port == l->sin6_port)&&(!memcmp(rl->sin6_addr.s6_addr,ll->sin6_addr.s6_addr,16))&&(rl->sin6_port == ll->sin6_port)) {
  156. _v6Path.lr = now;
  157. #ifdef ZT_ENABLE_CLUSTER
  158. _v6Path.localClusterSuboptimal = isClusterSuboptimalPath;
  159. #endif
  160. pathAlreadyKnown = true;
  161. }
  162. }
  163. }
  164. if ( (!pathAlreadyKnown) && (RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localAddress(),path->address())) ) {
  165. Mutex::Lock _l(_paths_m);
  166. _PeerPath *potentialNewPeerPath = (_PeerPath *)0;
  167. if (path->address().ss_family == AF_INET) {
  168. if ( (!_v4Path.p) || (!_v4Path.p->alive(now)) || ((_v4Path.p->address() != _v4ClusterPreferred)&&(path->preferenceRank() >= _v4Path.p->preferenceRank())) ) {
  169. potentialNewPeerPath = &_v4Path;
  170. }
  171. } else if (path->address().ss_family == AF_INET6) {
  172. if ( (!_v6Path.p) || (!_v6Path.p->alive(now)) || ((_v6Path.p->address() != _v6ClusterPreferred)&&(path->preferenceRank() >= _v6Path.p->preferenceRank())) ) {
  173. potentialNewPeerPath = &_v6Path;
  174. }
  175. }
  176. if (potentialNewPeerPath) {
  177. if (verb == Packet::VERB_OK) {
  178. potentialNewPeerPath->lr = now;
  179. potentialNewPeerPath->p = path;
  180. #ifdef ZT_ENABLE_CLUSTER
  181. potentialNewPeerPath->localClusterSuboptimal = isClusterSuboptimalPath;
  182. if (RR->cluster)
  183. RR->cluster->broadcastHavePeer(_id);
  184. #endif
  185. } else {
  186. TRACE("got %s via unknown path %s(%s), confirming...",Packet::verbString(verb),_id.address().toString().c_str(),path->address().toString().c_str());
  187. attemptToContactAt(tPtr,path->localAddress(),path->address(),now,true,path->nextOutgoingCounter());
  188. path->sent(now);
  189. }
  190. }
  191. }
  192. } else if (this->trustEstablished(now)) {
  193. // Send PUSH_DIRECT_PATHS if hops>0 (relayed) and we have a trust relationship (common network membership)
  194. #ifdef ZT_ENABLE_CLUSTER
  195. // Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
  196. const bool haveCluster = (RR->cluster);
  197. #else
  198. const bool haveCluster = false;
  199. #endif
  200. if ( ((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL) && (!haveCluster) ) {
  201. _lastDirectPathPushSent = now;
  202. std::vector<InetAddress> pathsToPush;
  203. std::vector<InetAddress> dps(RR->node->directPaths());
  204. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  205. pathsToPush.push_back(*i);
  206. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  207. for(unsigned long i=0,added=0;i<sym.size();++i) {
  208. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  209. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  210. pathsToPush.push_back(tmp);
  211. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  212. break;
  213. }
  214. }
  215. if (pathsToPush.size() > 0) {
  216. #ifdef ZT_TRACE
  217. std::string ps;
  218. for(std::vector<InetAddress>::const_iterator p(pathsToPush.begin());p!=pathsToPush.end();++p) {
  219. if (ps.length() > 0)
  220. ps.push_back(',');
  221. ps.append(p->toString());
  222. }
  223. TRACE("pushing %u direct paths to %s: %s",(unsigned int)pathsToPush.size(),_id.address().toString().c_str(),ps.c_str());
  224. #endif
  225. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  226. while (p != pathsToPush.end()) {
  227. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  228. outp.addSize(2); // leave room for count
  229. unsigned int count = 0;
  230. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  231. uint8_t addressType = 4;
  232. switch(p->ss_family) {
  233. case AF_INET:
  234. break;
  235. case AF_INET6:
  236. addressType = 6;
  237. break;
  238. default: // we currently only push IP addresses
  239. ++p;
  240. continue;
  241. }
  242. outp.append((uint8_t)0); // no flags
  243. outp.append((uint16_t)0); // no extensions
  244. outp.append(addressType);
  245. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  246. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  247. outp.append((uint16_t)p->port());
  248. ++count;
  249. ++p;
  250. }
  251. if (count) {
  252. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  253. outp.armor(_key,true,path->nextOutgoingCounter());
  254. path->send(RR,tPtr,outp.data(),outp.size(),now);
  255. }
  256. }
  257. }
  258. }
  259. }
  260. }
  261. bool Peer::sendDirect(void *tPtr,const void *data,unsigned int len,uint64_t now,bool force)
  262. {
  263. Mutex::Lock _l(_paths_m);
  264. uint64_t v6lr = 0;
  265. if ( ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v6Path.p) )
  266. v6lr = _v6Path.p->lastIn();
  267. uint64_t v4lr = 0;
  268. if ( ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v4Path.p) )
  269. v4lr = _v4Path.p->lastIn();
  270. if ( (v6lr > v4lr) && ((now - v6lr) < ZT_PATH_ALIVE_TIMEOUT) ) {
  271. return _v6Path.p->send(RR,tPtr,data,len,now);
  272. } else if ((now - v4lr) < ZT_PATH_ALIVE_TIMEOUT) {
  273. return _v4Path.p->send(RR,tPtr,data,len,now);
  274. } else if (force) {
  275. if (v6lr > v4lr) {
  276. return _v6Path.p->send(RR,tPtr,data,len,now);
  277. } else if (v4lr) {
  278. return _v4Path.p->send(RR,tPtr,data,len,now);
  279. }
  280. }
  281. return false;
  282. }
  283. SharedPtr<Path> Peer::getBestPath(uint64_t now,bool includeExpired)
  284. {
  285. Mutex::Lock _l(_paths_m);
  286. uint64_t v6lr = 0;
  287. if ( ( includeExpired || ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) ) && (_v6Path.p) )
  288. v6lr = _v6Path.p->lastIn();
  289. uint64_t v4lr = 0;
  290. if ( ( includeExpired || ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) ) && (_v4Path.p) )
  291. v4lr = _v4Path.p->lastIn();
  292. if (v6lr > v4lr) {
  293. return _v6Path.p;
  294. } else if (v4lr) {
  295. return _v4Path.p;
  296. }
  297. return SharedPtr<Path>();
  298. }
  299. void Peer::sendHELLO(void *tPtr,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int counter)
  300. {
  301. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  302. outp.append((unsigned char)ZT_PROTO_VERSION);
  303. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  304. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  305. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  306. outp.append(now);
  307. RR->identity.serialize(outp,false);
  308. atAddress.serialize(outp);
  309. outp.append((uint64_t)RR->topology->planetWorldId());
  310. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  311. const unsigned int startCryptedPortionAt = outp.size();
  312. std::vector<World> moons(RR->topology->moons());
  313. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  314. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  315. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  316. outp.append((uint8_t)m->type());
  317. outp.append((uint64_t)m->id());
  318. outp.append((uint64_t)m->timestamp());
  319. }
  320. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  321. outp.append((uint8_t)World::TYPE_MOON);
  322. outp.append(*m);
  323. outp.append((uint64_t)0);
  324. }
  325. const unsigned int corSizeAt = outp.size();
  326. outp.addSize(2);
  327. RR->topology->appendCertificateOfRepresentation(outp);
  328. outp.setAt(corSizeAt,(uint16_t)(outp.size() - (corSizeAt + 2)));
  329. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  330. RR->node->expectReplyTo(outp.packetId());
  331. if (atAddress) {
  332. outp.armor(_key,false,counter); // false == don't encrypt full payload, but add MAC
  333. RR->node->putPacket(tPtr,localAddr,atAddress,outp.data(),outp.size());
  334. } else {
  335. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  336. }
  337. }
  338. void Peer::attemptToContactAt(void *tPtr,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,bool sendFullHello,unsigned int counter)
  339. {
  340. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  341. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  342. RR->node->expectReplyTo(outp.packetId());
  343. outp.armor(_key,true,counter);
  344. RR->node->putPacket(tPtr,localAddr,atAddress,outp.data(),outp.size());
  345. } else {
  346. sendHELLO(tPtr,localAddr,atAddress,now,counter);
  347. }
  348. }
  349. void Peer::tryMemorizedPath(void *tPtr,uint64_t now)
  350. {
  351. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  352. _lastTriedMemorizedPath = now;
  353. InetAddress mp;
  354. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  355. attemptToContactAt(tPtr,InetAddress(),mp,now,true,0);
  356. }
  357. }
  358. bool Peer::doPingAndKeepalive(void *tPtr,uint64_t now,int inetAddressFamily)
  359. {
  360. Mutex::Lock _l(_paths_m);
  361. if (inetAddressFamily < 0) {
  362. uint64_t v6lr = 0;
  363. if ( ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v6Path.p) )
  364. v6lr = _v6Path.p->lastIn();
  365. uint64_t v4lr = 0;
  366. if ( ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v4Path.p) )
  367. v4lr = _v4Path.p->lastIn();
  368. if (v6lr > v4lr) {
  369. if ( ((now - _v6Path.lr) >= ZT_PEER_PING_PERIOD) || (_v6Path.p->needsHeartbeat(now)) ) {
  370. attemptToContactAt(tPtr,_v6Path.p->localAddress(),_v6Path.p->address(),now,false,_v6Path.p->nextOutgoingCounter());
  371. _v6Path.p->sent(now);
  372. return true;
  373. }
  374. } else if (v4lr) {
  375. if ( ((now - _v4Path.lr) >= ZT_PEER_PING_PERIOD) || (_v4Path.p->needsHeartbeat(now)) ) {
  376. attemptToContactAt(tPtr,_v4Path.p->localAddress(),_v4Path.p->address(),now,false,_v4Path.p->nextOutgoingCounter());
  377. _v4Path.p->sent(now);
  378. return true;
  379. }
  380. }
  381. } else {
  382. if ( (inetAddressFamily == AF_INET) && ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) ) {
  383. if ( ((now - _v4Path.lr) >= ZT_PEER_PING_PERIOD) || (_v4Path.p->needsHeartbeat(now)) ) {
  384. attemptToContactAt(tPtr,_v4Path.p->localAddress(),_v4Path.p->address(),now,false,_v4Path.p->nextOutgoingCounter());
  385. _v4Path.p->sent(now);
  386. return true;
  387. }
  388. } else if ( (inetAddressFamily == AF_INET6) && ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) ) {
  389. if ( ((now - _v6Path.lr) >= ZT_PEER_PING_PERIOD) || (_v6Path.p->needsHeartbeat(now)) ) {
  390. attemptToContactAt(tPtr,_v6Path.p->localAddress(),_v6Path.p->address(),now,false,_v6Path.p->nextOutgoingCounter());
  391. _v6Path.p->sent(now);
  392. return true;
  393. }
  394. }
  395. }
  396. return false;
  397. }
  398. } // namespace ZeroTier