Peer.cpp 13 KB

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