Peer.cpp 16 KB

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