Peer.cpp 20 KB

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