Peer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. std::vector<InetAddress> ma = RR->sa->whoami();
  209. pathsToPush.insert(pathsToPush.end(), ma.begin(), ma.end());
  210. if (!pathsToPush.empty()) {
  211. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  212. while (p != pathsToPush.end()) {
  213. Packet *const outp = new Packet(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  214. outp->addSize(2); // leave room for count
  215. unsigned int count = 0;
  216. while ((p != pathsToPush.end())&&((outp->size() + 24) < 1200)) {
  217. uint8_t addressType = 4;
  218. switch(p->ss_family) {
  219. case AF_INET:
  220. break;
  221. case AF_INET6:
  222. addressType = 6;
  223. break;
  224. default: // we currently only push IP addresses
  225. ++p;
  226. continue;
  227. }
  228. outp->append((uint8_t)0); // no flags
  229. outp->append((uint16_t)0); // no extensions
  230. outp->append(addressType);
  231. outp->append((uint8_t)((addressType == 4) ? 6 : 18));
  232. outp->append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  233. outp->append((uint16_t)p->port());
  234. ++count;
  235. ++p;
  236. }
  237. if (count) {
  238. outp->setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  239. outp->compress();
  240. outp->armor(_key,true,aesKeysIfSupported());
  241. path->send(RR,tPtr,outp->data(),outp->size(),now);
  242. }
  243. delete outp;
  244. }
  245. }
  246. }
  247. }
  248. }
  249. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired, int32_t flowId)
  250. {
  251. Mutex::Lock _l(_paths_m);
  252. Mutex::Lock _lb(_bond_m);
  253. if (!_bond) {
  254. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  255. /**
  256. * Send traffic across the highest quality path only. This algorithm will still
  257. * use the old path quality metric from protocol version 9.
  258. */
  259. long bestPathQuality = 2147483647;
  260. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  261. if (_paths[i].p) {
  262. if ((includeExpired)||((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)) {
  263. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  264. if (q <= bestPathQuality) {
  265. bestPathQuality = q;
  266. bestPath = i;
  267. }
  268. }
  269. } else break;
  270. }
  271. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  272. return _paths[bestPath].p;
  273. }
  274. return SharedPtr<Path>();
  275. }
  276. return _bond->getAppropriatePath(now, flowId);
  277. }
  278. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  279. {
  280. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  281. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  282. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  283. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  284. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  285. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  286. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  287. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  288. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  289. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  290. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  291. myBestV4QualityByScope[i] = 2147483647;
  292. myBestV6QualityByScope[i] = 2147483647;
  293. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  294. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  295. theirBestV4QualityByScope[i] = 2147483647;
  296. theirBestV6QualityByScope[i] = 2147483647;
  297. }
  298. Mutex::Lock _l1(_paths_m);
  299. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  300. if (_paths[i].p) {
  301. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  302. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  303. switch(_paths[i].p->address().ss_family) {
  304. case AF_INET:
  305. if (q <= myBestV4QualityByScope[s]) {
  306. myBestV4QualityByScope[s] = q;
  307. myBestV4ByScope[s] = i;
  308. }
  309. break;
  310. case AF_INET6:
  311. if (q <= myBestV6QualityByScope[s]) {
  312. myBestV6QualityByScope[s] = q;
  313. myBestV6ByScope[s] = i;
  314. }
  315. break;
  316. }
  317. } else break;
  318. }
  319. Mutex::Lock _l2(other->_paths_m);
  320. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  321. if (other->_paths[i].p) {
  322. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  323. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  324. switch(other->_paths[i].p->address().ss_family) {
  325. case AF_INET:
  326. if (q <= theirBestV4QualityByScope[s]) {
  327. theirBestV4QualityByScope[s] = q;
  328. theirBestV4ByScope[s] = i;
  329. }
  330. break;
  331. case AF_INET6:
  332. if (q <= theirBestV6QualityByScope[s]) {
  333. theirBestV6QualityByScope[s] = q;
  334. theirBestV6ByScope[s] = i;
  335. }
  336. break;
  337. }
  338. } else break;
  339. }
  340. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  341. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  342. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  343. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  344. mine = myBestV6ByScope[s];
  345. theirs = theirBestV6ByScope[s];
  346. break;
  347. }
  348. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  349. mine = myBestV4ByScope[s];
  350. theirs = theirBestV4ByScope[s];
  351. break;
  352. }
  353. }
  354. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  355. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  356. const unsigned int completed = alt + 2;
  357. while (alt != completed) {
  358. if ((alt & 1) == 0) {
  359. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  360. outp.append((uint8_t)0);
  361. other->_id.address().appendTo(outp);
  362. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  363. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  364. outp.append((uint8_t)16);
  365. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  366. } else {
  367. outp.append((uint8_t)4);
  368. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  369. }
  370. outp.armor(_key,true,aesKeysIfSupported());
  371. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  372. } else {
  373. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  374. outp.append((uint8_t)0);
  375. _id.address().appendTo(outp);
  376. outp.append((uint16_t)_paths[mine].p->address().port());
  377. if (_paths[mine].p->address().ss_family == AF_INET6) {
  378. outp.append((uint8_t)16);
  379. outp.append(_paths[mine].p->address().rawIpData(),16);
  380. } else {
  381. outp.append((uint8_t)4);
  382. outp.append(_paths[mine].p->address().rawIpData(),4);
  383. }
  384. outp.armor(other->_key,true,other->aesKeysIfSupported());
  385. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  386. }
  387. ++alt;
  388. }
  389. }
  390. }
  391. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  392. {
  393. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  394. outp.append((unsigned char)ZT_PROTO_VERSION);
  395. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  396. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  397. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  398. outp.append(now);
  399. RR->identity.serialize(outp,false);
  400. atAddress.serialize(outp);
  401. outp.append((uint64_t)RR->topology->planetWorldId());
  402. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  403. const unsigned int startCryptedPortionAt = outp.size();
  404. std::vector<World> moons(RR->topology->moons());
  405. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  406. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  407. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  408. outp.append((uint8_t)m->type());
  409. outp.append((uint64_t)m->id());
  410. outp.append((uint64_t)m->timestamp());
  411. }
  412. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  413. outp.append((uint8_t)World::TYPE_MOON);
  414. outp.append(*m);
  415. outp.append((uint64_t)0);
  416. }
  417. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  418. if (atAddress) {
  419. outp.armor(_key,false,nullptr); // false == don't encrypt full payload, but add MAC
  420. RR->node->expectReplyTo(outp.packetId());
  421. RR->node->putPacket(tPtr,-1,atAddress,outp.data(),outp.size());
  422. } else {
  423. RR->node->expectReplyTo(outp.packetId());
  424. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  425. }
  426. }
  427. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
  428. {
  429. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  430. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  431. outp.armor(_key,true,aesKeysIfSupported());
  432. RR->node->expectReplyTo(outp.packetId());
  433. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  434. } else {
  435. sendHELLO(tPtr,localSocket,atAddress,now);
  436. }
  437. }
  438. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  439. {
  440. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  441. _lastTriedMemorizedPath = now;
  442. InetAddress mp;
  443. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  444. attemptToContactAt(tPtr,-1,mp,now,true);
  445. }
  446. }
  447. void Peer::performMultipathStateCheck(void *tPtr, int64_t now)
  448. {
  449. Mutex::Lock _l(_bond_m);
  450. if (_bond) {
  451. // Once enabled the Bond object persists, no need to update state
  452. return;
  453. }
  454. /**
  455. * Check for conditions required for multipath bonding and create a bond
  456. * if allowed.
  457. */
  458. int numAlivePaths = 0;
  459. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  460. if (_paths[i].p && _paths[i].p->alive(now)) {
  461. numAlivePaths++;
  462. }
  463. }
  464. _localMultipathSupported = ((numAlivePaths >= 1) && (RR->bc->inUse()) && (ZT_PROTO_VERSION > 9));
  465. if (_localMultipathSupported && !_bond) {
  466. if (RR->bc) {
  467. _bond = RR->bc->createTransportTriggeredBond(RR, this);
  468. /**
  469. * Allow new bond to retroactively learn all paths known to this peer
  470. */
  471. if (_bond) {
  472. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  473. if (_paths[i].p) {
  474. _bond->nominatePathToBond(_paths[i].p, now);
  475. }
  476. }
  477. }
  478. }
  479. }
  480. }
  481. unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
  482. {
  483. unsigned int sent = 0;
  484. Mutex::Lock _l(_paths_m);
  485. performMultipathStateCheck(tPtr, now);
  486. const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
  487. _lastSentFullHello = now;
  488. // Right now we only keep pinging links that have the maximum priority. The
  489. // priority is used to track cluster redirections, meaning that when a cluster
  490. // redirects us its redirect target links override all other links and we
  491. // let those old links expire.
  492. long maxPriority = 0;
  493. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  494. if (_paths[i].p)
  495. maxPriority = std::max(_paths[i].priority,maxPriority);
  496. else break;
  497. }
  498. unsigned int j = 0;
  499. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  500. if (_paths[i].p) {
  501. // Clean expired and reduced priority paths
  502. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  503. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))) {
  504. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  505. _paths[i].p->sent(now);
  506. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  507. }
  508. if (i != j)
  509. _paths[j] = _paths[i];
  510. ++j;
  511. }
  512. } else break;
  513. }
  514. return sent;
  515. }
  516. void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
  517. {
  518. SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
  519. RR->t->peerRedirected(tPtr,0,*this,np);
  520. attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
  521. {
  522. Mutex::Lock _l(_paths_m);
  523. // New priority is higher than the priority of the originating path (if known)
  524. long newPriority = 1;
  525. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  526. if (_paths[i].p) {
  527. if (_paths[i].p == originatingPath) {
  528. newPriority = _paths[i].priority;
  529. break;
  530. }
  531. } else break;
  532. }
  533. newPriority += 2;
  534. // Erase any paths with lower priority than this one or that are duplicate
  535. // IPs and add this path.
  536. unsigned int j = 0;
  537. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  538. if (_paths[i].p) {
  539. if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
  540. if (i != j)
  541. _paths[j] = _paths[i];
  542. ++j;
  543. }
  544. }
  545. }
  546. if (j < ZT_MAX_PEER_NETWORK_PATHS) {
  547. _paths[j].lr = now;
  548. _paths[j].p = np;
  549. _paths[j].priority = newPriority;
  550. ++j;
  551. while (j < ZT_MAX_PEER_NETWORK_PATHS) {
  552. _paths[j].lr = 0;
  553. _paths[j].p.zero();
  554. _paths[j].priority = 1;
  555. ++j;
  556. }
  557. }
  558. }
  559. }
  560. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  561. {
  562. Mutex::Lock _l(_paths_m);
  563. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  564. if (_paths[i].p) {
  565. if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
  566. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
  567. _paths[i].p->sent(now);
  568. _paths[i].lr = 0; // path will not be used unless it speaks again
  569. }
  570. } else break;
  571. }
  572. }
  573. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  574. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  575. {
  576. if (_localMultipathSupported && _bond) {
  577. _bond->recordOutgoingPacket(path, packetId, payloadLength, verb, flowId, now);
  578. }
  579. }
  580. void Peer::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  581. {
  582. if (_localMultipathSupported && _bond) {
  583. _bond->recordIncomingInvalidPacket(path);
  584. }
  585. }
  586. void Peer::recordIncomingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  587. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  588. {
  589. if (_localMultipathSupported && _bond) {
  590. _bond->recordIncomingPacket(path, packetId, payloadLength, verb, flowId, now);
  591. }
  592. }
  593. } // namespace ZeroTier