Peer.cpp 20 KB

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