Peer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "../version.h"
  14. #include "Constants.hpp"
  15. #include "Peer.hpp"
  16. #include "Switch.hpp"
  17. #include "Network.hpp"
  18. #include "SelfAwareness.hpp"
  19. #include "Packet.hpp"
  20. #include "Trace.hpp"
  21. #include "InetAddress.hpp"
  22. #include "RingBuffer.hpp"
  23. #include "Utils.hpp"
  24. namespace ZeroTier {
  25. static unsigned char s_freeRandomByteCounter = 0;
  26. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  27. RR(renv),
  28. _lastReceive(0),
  29. _lastNontrivialReceive(0),
  30. _lastTriedMemorizedPath(0),
  31. _lastDirectPathPushSent(0),
  32. _lastDirectPathPushReceive(0),
  33. _lastEchoRequestReceived(0),
  34. _lastCredentialRequestSent(0),
  35. _lastWhoisRequestReceived(0),
  36. _lastCredentialsReceived(0),
  37. _lastTrustEstablishedPacketReceived(0),
  38. _lastSentFullHello(0),
  39. _lastEchoCheck(0),
  40. _freeRandomByte((unsigned char)((uintptr_t)this >> 4) ^ ++s_freeRandomByteCounter),
  41. _vProto(0),
  42. _vMajor(0),
  43. _vMinor(0),
  44. _vRevision(0),
  45. _id(peerIdentity),
  46. _directPathPushCutoffCount(0),
  47. _credentialsCutoffCount(0),
  48. _echoRequestCutoffCount(0),
  49. _uniqueAlivePathCount(0),
  50. _localMultipathSupported(false),
  51. _remoteMultipathSupported(false),
  52. _canUseMultipath(false),
  53. _shouldCollectPathStatistics(0),
  54. _bondingPolicy(0),
  55. _lastComputedAggregateMeanLatency(0)
  56. {
  57. if (!myIdentity.agree(peerIdentity,_key))
  58. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  59. uint8_t ktmp[ZT_SYMMETRIC_KEY_SIZE];
  60. KBKDFHMACSHA384(_key,ZT_KBKDF_LABEL_AES_GMAC_SIV_K0,0,0,ktmp);
  61. _aesKeys[0].init(ktmp);
  62. KBKDFHMACSHA384(_key,ZT_KBKDF_LABEL_AES_GMAC_SIV_K1,0,0,ktmp);
  63. _aesKeys[1].init(ktmp);
  64. Utils::burn(ktmp,ZT_SYMMETRIC_KEY_SIZE);
  65. }
  66. void Peer::received(
  67. void *tPtr,
  68. const SharedPtr<Path> &path,
  69. const unsigned int hops,
  70. const uint64_t packetId,
  71. const unsigned int payloadLength,
  72. const Packet::Verb verb,
  73. const uint64_t inRePacketId,
  74. const Packet::Verb inReVerb,
  75. const bool trustEstablished,
  76. const uint64_t networkId,
  77. const int32_t flowId)
  78. {
  79. const int64_t now = RR->node->now();
  80. _lastReceive = now;
  81. switch (verb) {
  82. case Packet::VERB_FRAME:
  83. case Packet::VERB_EXT_FRAME:
  84. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  85. case Packet::VERB_NETWORK_CONFIG:
  86. case Packet::VERB_MULTICAST_FRAME:
  87. _lastNontrivialReceive = now;
  88. break;
  89. default:
  90. break;
  91. }
  92. recordIncomingPacket(path, packetId, payloadLength, verb, flowId, now);
  93. if (trustEstablished) {
  94. _lastTrustEstablishedPacketReceived = now;
  95. path->trustedPacketReceived(now);
  96. }
  97. if (hops == 0) {
  98. // If this is a direct packet (no hops), update existing paths or learn new ones
  99. bool havePath = false;
  100. {
  101. Mutex::Lock _l(_paths_m);
  102. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  103. if (_paths[i].p) {
  104. if (_paths[i].p == path) {
  105. _paths[i].lr = now;
  106. havePath = true;
  107. break;
  108. }
  109. } else break;
  110. }
  111. }
  112. if ( (!havePath) && RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()) ) {
  113. if (verb == Packet::VERB_OK) {
  114. Mutex::Lock _l(_paths_m);
  115. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  116. long replacePathQuality = 0;
  117. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  118. if (_paths[i].p) {
  119. const long q = _paths[i].p->quality(now);
  120. if (q > replacePathQuality) {
  121. replacePathQuality = q;
  122. replacePath = i;
  123. if ( (!_paths[i].p->alive(now)) || _paths[i].p->address().ipsEqual(path->address()) )
  124. break;
  125. }
  126. } else {
  127. replacePath = i;
  128. break;
  129. }
  130. }
  131. if (replacePath != ZT_MAX_PEER_NETWORK_PATHS) {
  132. RR->t->peerLearnedNewPath(tPtr, networkId, *this, path, packetId);
  133. _paths[replacePath].lr = now;
  134. _paths[replacePath].p = path;
  135. _paths[replacePath].priority = 1;
  136. }
  137. } else {
  138. attemptToContactAt(tPtr,path->localSocket(),path->address(),now,true);
  139. path->sent(now);
  140. RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
  141. }
  142. /*
  143. // Paths are redunant if they duplicate an alive path to the same IP or
  144. // with the same local socket and address family.
  145. bool redundant = false;
  146. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  147. if (_paths[i].p) {
  148. if ( _paths[i].p->alive(now) && (_paths[i].p->localSocket() == path->localSocket()) && _paths[i].p->address().ipsEqual(path->address()) ) {
  149. redundant = true;
  150. break;
  151. }
  152. } else break;
  153. }
  154. if (!redundant) {
  155. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  156. int replacePathQuality = 0;
  157. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  158. if (_paths[i].p) {
  159. const int q = _paths[i].p->quality(now);
  160. if (q > replacePathQuality) {
  161. replacePathQuality = q;
  162. replacePath = i;
  163. if (!_paths[i].p->alive(now)) {
  164. break; // Stop searching, we found an identical dead path, replace the object
  165. }
  166. }
  167. } else {
  168. replacePath = i;
  169. break;
  170. }
  171. }
  172. if (replacePath != ZT_MAX_PEER_NETWORK_PATHS) {
  173. if (verb == Packet::VERB_OK) {
  174. RR->t->peerLearnedNewPath(tPtr,networkId,*this,path,packetId);
  175. _paths[replacePath].lr = now;
  176. _paths[replacePath].p = path;
  177. _paths[replacePath].priority = 1;
  178. } else {
  179. attemptToContact = true;
  180. }
  181. }
  182. }
  183. */
  184. }
  185. }
  186. // If we have a trust relationship periodically push a message enumerating
  187. // all known external addresses for ourselves. If we already have a path this
  188. // is done less frequently.
  189. if (this->trustEstablished(now)) {
  190. const int64_t sinceLastPush = now - _lastDirectPathPushSent;
  191. if (sinceLastPush >= ((hops == 0) ? ZT_DIRECT_PATH_PUSH_INTERVAL_HAVEPATH : ZT_DIRECT_PATH_PUSH_INTERVAL)) {
  192. _lastDirectPathPushSent = now;
  193. std::vector<InetAddress> pathsToPush(RR->node->directPaths());
  194. if (!pathsToPush.empty()) {
  195. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  196. while (p != pathsToPush.end()) {
  197. Packet *const outp = new Packet(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  198. outp->addSize(2); // leave room for count
  199. unsigned int count = 0;
  200. while ((p != pathsToPush.end())&&((outp->size() + 24) < 1200)) {
  201. uint8_t addressType = 4;
  202. switch(p->ss_family) {
  203. case AF_INET:
  204. break;
  205. case AF_INET6:
  206. addressType = 6;
  207. break;
  208. default: // we currently only push IP addresses
  209. ++p;
  210. continue;
  211. }
  212. outp->append((uint8_t)0); // no flags
  213. outp->append((uint16_t)0); // no extensions
  214. outp->append(addressType);
  215. outp->append((uint8_t)((addressType == 4) ? 6 : 18));
  216. outp->append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  217. outp->append((uint16_t)p->port());
  218. ++count;
  219. ++p;
  220. }
  221. if (count) {
  222. outp->setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  223. outp->compress();
  224. outp->armor(_key,true,aesKeysIfSupported());
  225. path->send(RR,tPtr,outp->data(),outp->size(),now);
  226. }
  227. delete outp;
  228. }
  229. }
  230. }
  231. }
  232. }
  233. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired, int32_t flowId)
  234. {
  235. if (!_bondToPeer) {
  236. Mutex::Lock _l(_paths_m);
  237. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  238. /**
  239. * Send traffic across the highest quality path only. This algorithm will still
  240. * use the old path quality metric from protocol version 9.
  241. */
  242. long bestPathQuality = 2147483647;
  243. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  244. if (_paths[i].p) {
  245. if ((includeExpired)||((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)) {
  246. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  247. if (q <= bestPathQuality) {
  248. bestPathQuality = q;
  249. bestPath = i;
  250. }
  251. }
  252. } else break;
  253. }
  254. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  255. return _paths[bestPath].p;
  256. }
  257. return SharedPtr<Path>();
  258. }
  259. return _bondToPeer->getAppropriatePath(now, flowId);
  260. }
  261. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  262. {
  263. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  264. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  265. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  266. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  267. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  268. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  269. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  270. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  271. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  272. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  273. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  274. myBestV4QualityByScope[i] = 2147483647;
  275. myBestV6QualityByScope[i] = 2147483647;
  276. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  277. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  278. theirBestV4QualityByScope[i] = 2147483647;
  279. theirBestV6QualityByScope[i] = 2147483647;
  280. }
  281. Mutex::Lock _l1(_paths_m);
  282. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  283. if (_paths[i].p) {
  284. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  285. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  286. switch(_paths[i].p->address().ss_family) {
  287. case AF_INET:
  288. if (q <= myBestV4QualityByScope[s]) {
  289. myBestV4QualityByScope[s] = q;
  290. myBestV4ByScope[s] = i;
  291. }
  292. break;
  293. case AF_INET6:
  294. if (q <= myBestV6QualityByScope[s]) {
  295. myBestV6QualityByScope[s] = q;
  296. myBestV6ByScope[s] = i;
  297. }
  298. break;
  299. }
  300. } else break;
  301. }
  302. Mutex::Lock _l2(other->_paths_m);
  303. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  304. if (other->_paths[i].p) {
  305. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  306. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  307. switch(other->_paths[i].p->address().ss_family) {
  308. case AF_INET:
  309. if (q <= theirBestV4QualityByScope[s]) {
  310. theirBestV4QualityByScope[s] = q;
  311. theirBestV4ByScope[s] = i;
  312. }
  313. break;
  314. case AF_INET6:
  315. if (q <= theirBestV6QualityByScope[s]) {
  316. theirBestV6QualityByScope[s] = q;
  317. theirBestV6ByScope[s] = i;
  318. }
  319. break;
  320. }
  321. } else break;
  322. }
  323. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  324. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  325. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  326. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  327. mine = myBestV6ByScope[s];
  328. theirs = theirBestV6ByScope[s];
  329. break;
  330. }
  331. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  332. mine = myBestV4ByScope[s];
  333. theirs = theirBestV4ByScope[s];
  334. break;
  335. }
  336. }
  337. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  338. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  339. const unsigned int completed = alt + 2;
  340. while (alt != completed) {
  341. if ((alt & 1) == 0) {
  342. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  343. outp.append((uint8_t)0);
  344. other->_id.address().appendTo(outp);
  345. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  346. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  347. outp.append((uint8_t)16);
  348. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  349. } else {
  350. outp.append((uint8_t)4);
  351. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  352. }
  353. outp.armor(_key,true,aesKeysIfSupported());
  354. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  355. } else {
  356. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  357. outp.append((uint8_t)0);
  358. _id.address().appendTo(outp);
  359. outp.append((uint16_t)_paths[mine].p->address().port());
  360. if (_paths[mine].p->address().ss_family == AF_INET6) {
  361. outp.append((uint8_t)16);
  362. outp.append(_paths[mine].p->address().rawIpData(),16);
  363. } else {
  364. outp.append((uint8_t)4);
  365. outp.append(_paths[mine].p->address().rawIpData(),4);
  366. }
  367. outp.armor(other->_key,true,aesKeysIfSupported());
  368. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  369. }
  370. ++alt;
  371. }
  372. }
  373. }
  374. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  375. {
  376. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  377. outp.append((unsigned char)ZT_PROTO_VERSION);
  378. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  379. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  380. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  381. outp.append(now);
  382. RR->identity.serialize(outp,false);
  383. atAddress.serialize(outp);
  384. outp.append((uint64_t)RR->topology->planetWorldId());
  385. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  386. const unsigned int startCryptedPortionAt = outp.size();
  387. std::vector<World> moons(RR->topology->moons());
  388. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  389. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  390. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  391. outp.append((uint8_t)m->type());
  392. outp.append((uint64_t)m->id());
  393. outp.append((uint64_t)m->timestamp());
  394. }
  395. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  396. outp.append((uint8_t)World::TYPE_MOON);
  397. outp.append(*m);
  398. outp.append((uint64_t)0);
  399. }
  400. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  401. if (atAddress) {
  402. outp.armor(_key,false,nullptr); // false == don't encrypt full payload, but add MAC
  403. RR->node->expectReplyTo(outp.packetId());
  404. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  405. } else {
  406. RR->node->expectReplyTo(outp.packetId());
  407. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  408. }
  409. }
  410. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
  411. {
  412. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  413. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  414. outp.armor(_key,true,aesKeysIfSupported());
  415. RR->node->expectReplyTo(outp.packetId());
  416. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  417. } else {
  418. sendHELLO(tPtr,localSocket,atAddress,now);
  419. }
  420. }
  421. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  422. {
  423. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  424. _lastTriedMemorizedPath = now;
  425. InetAddress mp;
  426. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  427. attemptToContactAt(tPtr,-1,mp,now,true);
  428. }
  429. }
  430. void Peer::performMultipathStateCheck(void *tPtr, int64_t now)
  431. {
  432. /**
  433. * Check for conditions required for multipath bonding and create a bond
  434. * if allowed.
  435. */
  436. _localMultipathSupported = ((RR->bc->inUse()) && (ZT_PROTO_VERSION > 9));
  437. if (_localMultipathSupported) {
  438. int currAlivePathCount = 0;
  439. int duplicatePathsFound = 0;
  440. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  441. if (_paths[i].p) {
  442. currAlivePathCount++;
  443. for (unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  444. if (_paths[i].p && _paths[j].p && _paths[i].p->address().ipsEqual2(_paths[j].p->address()) && i != j) {
  445. duplicatePathsFound+=1;
  446. break;
  447. }
  448. }
  449. }
  450. }
  451. _uniqueAlivePathCount = (currAlivePathCount - (duplicatePathsFound / 2));
  452. _remoteMultipathSupported = _vProto > 9;
  453. _canUseMultipath = _localMultipathSupported && _remoteMultipathSupported && (_uniqueAlivePathCount > 1);
  454. }
  455. if (_canUseMultipath && !_bondToPeer) {
  456. if (RR->bc) {
  457. _bondToPeer = RR->bc->createTransportTriggeredBond(RR, this);
  458. /**
  459. * Allow new bond to retroactively learn all paths known to this peer
  460. */
  461. if (_bondToPeer) {
  462. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  463. if (_paths[i].p) {
  464. _bondToPeer->nominatePath(_paths[i].p, now);
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }
  471. unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
  472. {
  473. unsigned int sent = 0;
  474. Mutex::Lock _l(_paths_m);
  475. performMultipathStateCheck(tPtr, now);
  476. const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
  477. _lastSentFullHello = now;
  478. // Right now we only keep pinging links that have the maximum priority. The
  479. // priority is used to track cluster redirections, meaning that when a cluster
  480. // redirects us its redirect target links override all other links and we
  481. // let those old links expire.
  482. long maxPriority = 0;
  483. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  484. if (_paths[i].p)
  485. maxPriority = std::max(_paths[i].priority,maxPriority);
  486. else break;
  487. }
  488. unsigned int j = 0;
  489. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  490. if (_paths[i].p) {
  491. // Clean expired and reduced priority paths
  492. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  493. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))
  494. || (_canUseMultipath && _paths[i].p->needsGratuitousHeartbeat(now))) {
  495. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  496. _paths[i].p->sent(now);
  497. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  498. }
  499. if (i != j)
  500. _paths[j] = _paths[i];
  501. ++j;
  502. }
  503. } else break;
  504. }
  505. return sent;
  506. }
  507. void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
  508. {
  509. SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
  510. RR->t->peerRedirected(tPtr,0,*this,np);
  511. attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
  512. {
  513. Mutex::Lock _l(_paths_m);
  514. // New priority is higher than the priority of the originating path (if known)
  515. long newPriority = 1;
  516. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  517. if (_paths[i].p) {
  518. if (_paths[i].p == originatingPath) {
  519. newPriority = _paths[i].priority;
  520. break;
  521. }
  522. } else break;
  523. }
  524. newPriority += 2;
  525. // Erase any paths with lower priority than this one or that are duplicate
  526. // IPs and add this path.
  527. unsigned int j = 0;
  528. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  529. if (_paths[i].p) {
  530. if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
  531. if (i != j)
  532. _paths[j] = _paths[i];
  533. ++j;
  534. }
  535. }
  536. }
  537. if (j < ZT_MAX_PEER_NETWORK_PATHS) {
  538. _paths[j].lr = now;
  539. _paths[j].p = np;
  540. _paths[j].priority = newPriority;
  541. ++j;
  542. while (j < ZT_MAX_PEER_NETWORK_PATHS) {
  543. _paths[j].lr = 0;
  544. _paths[j].p.zero();
  545. _paths[j].priority = 1;
  546. ++j;
  547. }
  548. }
  549. }
  550. }
  551. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  552. {
  553. Mutex::Lock _l(_paths_m);
  554. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  555. if (_paths[i].p) {
  556. if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
  557. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
  558. _paths[i].p->sent(now);
  559. _paths[i].lr = 0; // path will not be used unless it speaks again
  560. }
  561. } else break;
  562. }
  563. }
  564. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  565. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  566. {
  567. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  568. return;
  569. }
  570. _bondToPeer->recordOutgoingPacket(path, packetId, payloadLength, verb, flowId, now);
  571. }
  572. void Peer::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  573. {
  574. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  575. return;
  576. }
  577. _bondToPeer->recordIncomingInvalidPacket(path);
  578. }
  579. void Peer::recordIncomingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  580. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  581. {
  582. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  583. return;
  584. }
  585. _bondToPeer->recordIncomingPacket(path, packetId, payloadLength, verb, flowId, now);
  586. }
  587. } // namespace ZeroTier