Peer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. #include "Trace.hpp"
  35. #include "InetAddress.hpp"
  36. namespace ZeroTier {
  37. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  38. RR(renv),
  39. _lastReceive(0),
  40. _lastNontrivialReceive(0),
  41. _lastTriedMemorizedPath(0),
  42. _lastDirectPathPushSent(0),
  43. _lastDirectPathPushReceive(0),
  44. _lastCredentialRequestSent(0),
  45. _lastWhoisRequestReceived(0),
  46. _lastEchoRequestReceived(0),
  47. _lastComRequestReceived(0),
  48. _lastComRequestSent(0),
  49. _lastCredentialsReceived(0),
  50. _lastTrustEstablishedPacketReceived(0),
  51. _vProto(0),
  52. _vMajor(0),
  53. _vMinor(0),
  54. _vRevision(0),
  55. _id(peerIdentity),
  56. _latency(0),
  57. _directPathPushCutoffCount(0),
  58. _credentialsCutoffCount(0)
  59. {
  60. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  61. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  62. }
  63. void Peer::received(
  64. void *tPtr,
  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. const uint64_t networkId)
  73. {
  74. const int64_t now = RR->node->now();
  75. /*
  76. #ifdef ZT_ENABLE_CLUSTER
  77. bool isClusterSuboptimalPath = 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,path->nextOutgoingCounter());
  100. path->send(RR,tPtr,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,path->nextOutgoingCounter());
  115. path->send(RR,tPtr,outp.data(),outp.size(),now);
  116. }
  117. isClusterSuboptimalPath = true;
  118. }
  119. }
  120. #endif
  121. */
  122. _lastReceive = now;
  123. switch (verb) {
  124. case Packet::VERB_FRAME:
  125. case Packet::VERB_EXT_FRAME:
  126. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  127. case Packet::VERB_NETWORK_CONFIG:
  128. case Packet::VERB_MULTICAST_FRAME:
  129. _lastNontrivialReceive = now;
  130. break;
  131. default: break;
  132. }
  133. if (trustEstablished) {
  134. _lastTrustEstablishedPacketReceived = now;
  135. path->trustedPacketReceived(now);
  136. }
  137. if (_vProto >= 9)
  138. path->updateLinkQuality((unsigned int)(packetId & 7));
  139. if (hops == 0) {
  140. // If this is a direct packet (no hops), update existing paths or learn new ones
  141. bool pathAlreadyKnown = false;
  142. {
  143. Mutex::Lock _l(_paths_m);
  144. if ((path->address().ss_family == AF_INET)&&(_v4Path.p)) {
  145. const struct sockaddr_in *const r = reinterpret_cast<const struct sockaddr_in *>(&(path->address()));
  146. const struct sockaddr_in *const l = reinterpret_cast<const struct sockaddr_in *>(&(_v4Path.p->address()));
  147. if ((r->sin_addr.s_addr == l->sin_addr.s_addr)&&(r->sin_port == l->sin_port)&&(path->localSocket() == _v4Path.p->localSocket())) {
  148. _v4Path.lr = now;
  149. pathAlreadyKnown = true;
  150. }
  151. } else if ((path->address().ss_family == AF_INET6)&&(_v6Path.p)) {
  152. const struct sockaddr_in6 *const r = reinterpret_cast<const struct sockaddr_in6 *>(&(path->address()));
  153. const struct sockaddr_in6 *const l = reinterpret_cast<const struct sockaddr_in6 *>(&(_v6Path.p->address()));
  154. if ((!memcmp(r->sin6_addr.s6_addr,l->sin6_addr.s6_addr,16))&&(r->sin6_port == l->sin6_port)&&(path->localSocket() == _v6Path.p->localSocket())) {
  155. _v6Path.lr = now;
  156. pathAlreadyKnown = true;
  157. }
  158. }
  159. }
  160. if ( (!pathAlreadyKnown) && (RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address())) ) {
  161. Mutex::Lock _l(_paths_m);
  162. _PeerPath *replacablePath = (_PeerPath *)0;
  163. if (path->address().ss_family == AF_INET) {
  164. if ( ( (!_v4Path.p) || (!_v4Path.p->alive(now)) || (path->preferenceRank() >= _v4Path.p->preferenceRank()) ) && ( (now - _v4Path.sticky) > ZT_PEER_PATH_EXPIRATION ) ) {
  165. replacablePath = &_v4Path;
  166. }
  167. } else if (path->address().ss_family == AF_INET6) {
  168. if ( ( (!_v6Path.p) || (!_v6Path.p->alive(now)) || (path->preferenceRank() >= _v6Path.p->preferenceRank()) ) && ( (now - _v6Path.sticky) > ZT_PEER_PATH_EXPIRATION ) ) {
  169. replacablePath = &_v6Path;
  170. }
  171. }
  172. if (replacablePath) {
  173. if (verb == Packet::VERB_OK) {
  174. RR->t->peerLearnedNewPath(tPtr,networkId,*this,replacablePath->p,path,packetId);
  175. replacablePath->lr = now;
  176. replacablePath->p = path;
  177. } else {
  178. RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
  179. attemptToContactAt(tPtr,path->localSocket(),path->address(),now,true,path->nextOutgoingCounter());
  180. path->sent(now);
  181. }
  182. }
  183. }
  184. }
  185. // If we are being relayed or if we're using a global address, send PUSH_DIRECT_PATHS.
  186. // In the global address case we push only configured direct paths to accomplish
  187. // fall-forward to local backplane networks over e.g. LAN or Amazon VPC.
  188. if ( ((hops > 0)||(path->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) && (this->trustEstablished(now)) ) {
  189. if ((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  190. _lastDirectPathPushSent = now;
  191. std::vector<InetAddress> pathsToPush;
  192. std::vector<InetAddress> dps(RR->node->directPaths());
  193. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  194. pathsToPush.push_back(*i);
  195. if (hops > 0) {
  196. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  197. for(unsigned long i=0,added=0;i<sym.size();++i) {
  198. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  199. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  200. pathsToPush.push_back(tmp);
  201. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  202. break;
  203. }
  204. }
  205. }
  206. if (pathsToPush.size() > 0) {
  207. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  208. while (p != pathsToPush.end()) {
  209. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  210. outp.addSize(2); // leave room for count
  211. unsigned int count = 0;
  212. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  213. uint8_t addressType = 4;
  214. switch(p->ss_family) {
  215. case AF_INET:
  216. break;
  217. case AF_INET6:
  218. addressType = 6;
  219. break;
  220. default: // we currently only push IP addresses
  221. ++p;
  222. continue;
  223. }
  224. outp.append((uint8_t)0); // no flags
  225. outp.append((uint16_t)0); // no extensions
  226. outp.append(addressType);
  227. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  228. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  229. outp.append((uint16_t)p->port());
  230. ++count;
  231. ++p;
  232. }
  233. if (count) {
  234. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  235. outp.armor(_key,true,path->nextOutgoingCounter());
  236. path->send(RR,tPtr,outp.data(),outp.size(),now);
  237. }
  238. }
  239. }
  240. }
  241. }
  242. }
  243. bool Peer::sendDirect(void *tPtr,const void *data,unsigned int len,int64_t now,bool force)
  244. {
  245. Mutex::Lock _l(_paths_m);
  246. int64_t v6lr = 0;
  247. if ( ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v6Path.p) )
  248. v6lr = _v6Path.p->lastIn();
  249. int64_t v4lr = 0;
  250. if ( ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v4Path.p) )
  251. v4lr = _v4Path.p->lastIn();
  252. if ( (v6lr > v4lr) && ((now - v6lr) < ZT_PATH_ALIVE_TIMEOUT) ) {
  253. return _v6Path.p->send(RR,tPtr,data,len,now);
  254. } else if ((now - v4lr) < ZT_PATH_ALIVE_TIMEOUT) {
  255. return _v4Path.p->send(RR,tPtr,data,len,now);
  256. } else if (force) {
  257. if (v6lr > v4lr) {
  258. return _v6Path.p->send(RR,tPtr,data,len,now);
  259. } else if (v4lr) {
  260. return _v4Path.p->send(RR,tPtr,data,len,now);
  261. }
  262. }
  263. return false;
  264. }
  265. SharedPtr<Path> Peer::getBestPath(int64_t now,bool includeExpired)
  266. {
  267. Mutex::Lock _l(_paths_m);
  268. int64_t v6lr = 0;
  269. if ((includeExpired || ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION)) && (_v6Path.p)) {
  270. v6lr = _v6Path.p->lastIn();
  271. }
  272. int64_t v4lr = 0;
  273. if ((includeExpired || ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION)) && (_v4Path.p)) {
  274. v4lr = _v4Path.p->lastIn();
  275. }
  276. if (v6lr > v4lr) {
  277. return _v6Path.p;
  278. } else if (v4lr) {
  279. return _v4Path.p;
  280. }
  281. return SharedPtr<Path>();
  282. }
  283. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,unsigned int counter)
  284. {
  285. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  286. outp.append((unsigned char)ZT_PROTO_VERSION);
  287. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  288. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  289. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  290. outp.append(now);
  291. RR->identity.serialize(outp,false);
  292. atAddress.serialize(outp);
  293. outp.append((uint64_t)RR->topology->planetWorldId());
  294. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  295. const unsigned int startCryptedPortionAt = outp.size();
  296. std::vector<World> moons(RR->topology->moons());
  297. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  298. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  299. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  300. outp.append((uint8_t)m->type());
  301. outp.append((uint64_t)m->id());
  302. outp.append((uint64_t)m->timestamp());
  303. }
  304. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  305. outp.append((uint8_t)World::TYPE_MOON);
  306. outp.append(*m);
  307. outp.append((uint64_t)0);
  308. }
  309. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  310. RR->node->expectReplyTo(outp.packetId());
  311. if (atAddress) {
  312. outp.armor(_key,false,counter); // false == don't encrypt full payload, but add MAC
  313. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  314. } else {
  315. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  316. }
  317. }
  318. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello,unsigned int counter)
  319. {
  320. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  321. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  322. RR->node->expectReplyTo(outp.packetId());
  323. outp.armor(_key,true,counter);
  324. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  325. } else {
  326. sendHELLO(tPtr,localSocket,atAddress,now,counter);
  327. }
  328. }
  329. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  330. {
  331. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  332. _lastTriedMemorizedPath = now;
  333. InetAddress mp;
  334. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  335. attemptToContactAt(tPtr,-1,mp,now,true,0);
  336. }
  337. }
  338. bool Peer::doPingAndKeepalive(void *tPtr,int64_t now,int inetAddressFamily)
  339. {
  340. Mutex::Lock _l(_paths_m);
  341. if (inetAddressFamily < 0) {
  342. int64_t v6lr = 0;
  343. if ( ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v6Path.p) )
  344. v6lr = _v6Path.p->lastIn();
  345. int64_t v4lr = 0;
  346. if ( ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) && (_v4Path.p) )
  347. v4lr = _v4Path.p->lastIn();
  348. if (v6lr > v4lr) {
  349. if ( ((now - _v6Path.lr) >= ZT_PEER_PING_PERIOD) || (_v6Path.p->needsHeartbeat(now)) ) {
  350. attemptToContactAt(tPtr,_v6Path.p->localSocket(),_v6Path.p->address(),now,false,_v6Path.p->nextOutgoingCounter());
  351. _v6Path.p->sent(now);
  352. return true;
  353. }
  354. } else if (v4lr) {
  355. if ( ((now - _v4Path.lr) >= ZT_PEER_PING_PERIOD) || (_v4Path.p->needsHeartbeat(now)) ) {
  356. attemptToContactAt(tPtr,_v4Path.p->localSocket(),_v4Path.p->address(),now,false,_v4Path.p->nextOutgoingCounter());
  357. _v4Path.p->sent(now);
  358. return true;
  359. }
  360. }
  361. } else {
  362. if ( (inetAddressFamily == AF_INET) && ((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION) ) {
  363. if ( ((now - _v4Path.lr) >= ZT_PEER_PING_PERIOD) || (_v4Path.p->needsHeartbeat(now)) ) {
  364. attemptToContactAt(tPtr,_v4Path.p->localSocket(),_v4Path.p->address(),now,false,_v4Path.p->nextOutgoingCounter());
  365. _v4Path.p->sent(now);
  366. return true;
  367. }
  368. } else if ( (inetAddressFamily == AF_INET6) && ((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION) ) {
  369. if ( ((now - _v6Path.lr) >= ZT_PEER_PING_PERIOD) || (_v6Path.p->needsHeartbeat(now)) ) {
  370. attemptToContactAt(tPtr,_v6Path.p->localSocket(),_v6Path.p->address(),now,false,_v6Path.p->nextOutgoingCounter());
  371. _v6Path.p->sent(now);
  372. return true;
  373. }
  374. }
  375. }
  376. return false;
  377. }
  378. void Peer::redirect(void *tPtr,const int64_t localSocket,const InetAddress &remoteAddress,const int64_t now)
  379. {
  380. if ((remoteAddress.ss_family != AF_INET)&&(remoteAddress.ss_family != AF_INET6)) // sanity check
  381. return;
  382. SharedPtr<Path> op;
  383. SharedPtr<Path> np(RR->topology->getPath(localSocket,remoteAddress));
  384. np->received(now);
  385. attemptToContactAt(tPtr,localSocket,remoteAddress,now,true,np->nextOutgoingCounter());
  386. {
  387. Mutex::Lock _l(_paths_m);
  388. if (remoteAddress.ss_family == AF_INET) {
  389. op = _v4Path.p;
  390. _v4Path.lr = now;
  391. _v4Path.sticky = now;
  392. _v4Path.p = np;
  393. } else if (remoteAddress.ss_family == AF_INET6) {
  394. op = _v6Path.p;
  395. _v6Path.lr = now;
  396. _v6Path.sticky = now;
  397. _v6Path.p = np;
  398. }
  399. }
  400. RR->t->peerRedirected(tPtr,0,*this,op,np);
  401. }
  402. } // namespace ZeroTier