Peer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. bool attemptToContact = false;
  113. if ((!havePath)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()))) {
  114. Mutex::Lock _l(_paths_m);
  115. // Paths are redunant if they duplicate an alive path to the same IP or
  116. // with the same local socket and address family.
  117. bool redundant = false;
  118. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  119. if (_paths[i].p) {
  120. if ( (_paths[i].p->alive(now)) && ( ((_paths[i].p->localSocket() == path->localSocket())&&(_paths[i].p->address().ss_family == path->address().ss_family)) || (_paths[i].p->address().ipsEqual2(path->address())) ) ) {
  121. redundant = true;
  122. break;
  123. }
  124. } else break;
  125. }
  126. if (!redundant) {
  127. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  128. int replacePathQuality = 0;
  129. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  130. if (_paths[i].p) {
  131. const int q = _paths[i].p->quality(now);
  132. if (q > replacePathQuality) {
  133. replacePathQuality = q;
  134. replacePath = i;
  135. if (!_paths[i].p->alive(now)) {
  136. break; // Stop searching, we found an identical dead path, replace the object
  137. }
  138. }
  139. } else {
  140. replacePath = i;
  141. break;
  142. }
  143. }
  144. if (replacePath != ZT_MAX_PEER_NETWORK_PATHS) {
  145. if (verb == Packet::VERB_OK) {
  146. RR->t->peerLearnedNewPath(tPtr,networkId,*this,path,packetId);
  147. _paths[replacePath].lr = now;
  148. _paths[replacePath].p = path;
  149. _paths[replacePath].priority = 1;
  150. } else {
  151. attemptToContact = true;
  152. }
  153. }
  154. }
  155. }
  156. if (attemptToContact) {
  157. attemptToContactAt(tPtr,path->localSocket(),path->address(),now,true);
  158. path->sent(now);
  159. RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
  160. }
  161. }
  162. // If we have a trust relationship periodically push a message enumerating
  163. // all known external addresses for ourselves. If we already have a path this
  164. // is done less frequently.
  165. if (this->trustEstablished(now)) {
  166. const int64_t sinceLastPush = now - _lastDirectPathPushSent;
  167. if (sinceLastPush >= ((hops == 0) ? ZT_DIRECT_PATH_PUSH_INTERVAL_HAVEPATH : ZT_DIRECT_PATH_PUSH_INTERVAL)) {
  168. _lastDirectPathPushSent = now;
  169. std::vector<InetAddress> pathsToPush(RR->node->directPaths());
  170. if (pathsToPush.size() > 0) {
  171. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  172. while (p != pathsToPush.end()) {
  173. Packet *const outp = new Packet(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  174. outp->addSize(2); // leave room for count
  175. unsigned int count = 0;
  176. while ((p != pathsToPush.end())&&((outp->size() + 24) < 1200)) {
  177. uint8_t addressType = 4;
  178. switch(p->ss_family) {
  179. case AF_INET:
  180. break;
  181. case AF_INET6:
  182. addressType = 6;
  183. break;
  184. default: // we currently only push IP addresses
  185. ++p;
  186. continue;
  187. }
  188. outp->append((uint8_t)0); // no flags
  189. outp->append((uint16_t)0); // no extensions
  190. outp->append(addressType);
  191. outp->append((uint8_t)((addressType == 4) ? 6 : 18));
  192. outp->append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  193. outp->append((uint16_t)p->port());
  194. ++count;
  195. ++p;
  196. }
  197. if (count) {
  198. outp->setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  199. outp->compress();
  200. outp->armor(_key,true,aesKeysIfSupported());
  201. path->send(RR,tPtr,outp->data(),outp->size(),now);
  202. }
  203. delete outp;
  204. }
  205. }
  206. }
  207. }
  208. }
  209. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired, int32_t flowId)
  210. {
  211. if (!_bondToPeer) {
  212. Mutex::Lock _l(_paths_m);
  213. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  214. /**
  215. * Send traffic across the highest quality path only. This algorithm will still
  216. * use the old path quality metric from protocol version 9.
  217. */
  218. long bestPathQuality = 2147483647;
  219. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  220. if (_paths[i].p) {
  221. if ((includeExpired)||((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)) {
  222. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  223. if (q <= bestPathQuality) {
  224. bestPathQuality = q;
  225. bestPath = i;
  226. }
  227. }
  228. } else break;
  229. }
  230. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  231. return _paths[bestPath].p;
  232. }
  233. return SharedPtr<Path>();
  234. }
  235. return _bondToPeer->getAppropriatePath(now, flowId);
  236. }
  237. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  238. {
  239. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  240. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  241. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  242. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  243. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  244. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  245. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  246. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  247. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  248. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  249. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  250. myBestV4QualityByScope[i] = 2147483647;
  251. myBestV6QualityByScope[i] = 2147483647;
  252. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  253. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  254. theirBestV4QualityByScope[i] = 2147483647;
  255. theirBestV6QualityByScope[i] = 2147483647;
  256. }
  257. Mutex::Lock _l1(_paths_m);
  258. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  259. if (_paths[i].p) {
  260. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  261. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  262. switch(_paths[i].p->address().ss_family) {
  263. case AF_INET:
  264. if (q <= myBestV4QualityByScope[s]) {
  265. myBestV4QualityByScope[s] = q;
  266. myBestV4ByScope[s] = i;
  267. }
  268. break;
  269. case AF_INET6:
  270. if (q <= myBestV6QualityByScope[s]) {
  271. myBestV6QualityByScope[s] = q;
  272. myBestV6ByScope[s] = i;
  273. }
  274. break;
  275. }
  276. } else break;
  277. }
  278. Mutex::Lock _l2(other->_paths_m);
  279. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  280. if (other->_paths[i].p) {
  281. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  282. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  283. switch(other->_paths[i].p->address().ss_family) {
  284. case AF_INET:
  285. if (q <= theirBestV4QualityByScope[s]) {
  286. theirBestV4QualityByScope[s] = q;
  287. theirBestV4ByScope[s] = i;
  288. }
  289. break;
  290. case AF_INET6:
  291. if (q <= theirBestV6QualityByScope[s]) {
  292. theirBestV6QualityByScope[s] = q;
  293. theirBestV6ByScope[s] = i;
  294. }
  295. break;
  296. }
  297. } else break;
  298. }
  299. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  300. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  301. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  302. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  303. mine = myBestV6ByScope[s];
  304. theirs = theirBestV6ByScope[s];
  305. break;
  306. }
  307. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  308. mine = myBestV4ByScope[s];
  309. theirs = theirBestV4ByScope[s];
  310. break;
  311. }
  312. }
  313. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  314. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  315. const unsigned int completed = alt + 2;
  316. while (alt != completed) {
  317. if ((alt & 1) == 0) {
  318. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  319. outp.append((uint8_t)0);
  320. other->_id.address().appendTo(outp);
  321. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  322. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  323. outp.append((uint8_t)16);
  324. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  325. } else {
  326. outp.append((uint8_t)4);
  327. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  328. }
  329. outp.armor(_key,true,aesKeysIfSupported());
  330. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  331. } else {
  332. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  333. outp.append((uint8_t)0);
  334. _id.address().appendTo(outp);
  335. outp.append((uint16_t)_paths[mine].p->address().port());
  336. if (_paths[mine].p->address().ss_family == AF_INET6) {
  337. outp.append((uint8_t)16);
  338. outp.append(_paths[mine].p->address().rawIpData(),16);
  339. } else {
  340. outp.append((uint8_t)4);
  341. outp.append(_paths[mine].p->address().rawIpData(),4);
  342. }
  343. outp.armor(other->_key,true,aesKeysIfSupported());
  344. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  345. }
  346. ++alt;
  347. }
  348. }
  349. }
  350. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  351. {
  352. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  353. outp.append((unsigned char)ZT_PROTO_VERSION);
  354. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  355. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  356. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  357. outp.append(now);
  358. RR->identity.serialize(outp,false);
  359. atAddress.serialize(outp);
  360. outp.append((uint64_t)RR->topology->planetWorldId());
  361. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  362. const unsigned int startCryptedPortionAt = outp.size();
  363. std::vector<World> moons(RR->topology->moons());
  364. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  365. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  366. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  367. outp.append((uint8_t)m->type());
  368. outp.append((uint64_t)m->id());
  369. outp.append((uint64_t)m->timestamp());
  370. }
  371. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  372. outp.append((uint8_t)World::TYPE_MOON);
  373. outp.append(*m);
  374. outp.append((uint64_t)0);
  375. }
  376. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  377. if (atAddress) {
  378. outp.armor(_key,false,nullptr); // false == don't encrypt full payload, but add MAC
  379. RR->node->expectReplyTo(outp.packetId());
  380. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  381. } else {
  382. RR->node->expectReplyTo(outp.packetId());
  383. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  384. }
  385. }
  386. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
  387. {
  388. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  389. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  390. outp.armor(_key,true,aesKeysIfSupported());
  391. RR->node->expectReplyTo(outp.packetId());
  392. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  393. } else {
  394. sendHELLO(tPtr,localSocket,atAddress,now);
  395. }
  396. }
  397. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  398. {
  399. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  400. _lastTriedMemorizedPath = now;
  401. InetAddress mp;
  402. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  403. attemptToContactAt(tPtr,-1,mp,now,true);
  404. }
  405. }
  406. void Peer::performMultipathStateCheck(void *tPtr, int64_t now)
  407. {
  408. /**
  409. * Check for conditions required for multipath bonding and create a bond
  410. * if allowed.
  411. */
  412. _localMultipathSupported = ((RR->bc->inUse()) && (ZT_PROTO_VERSION > 9));
  413. if (_localMultipathSupported) {
  414. int currAlivePathCount = 0;
  415. int duplicatePathsFound = 0;
  416. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  417. if (_paths[i].p) {
  418. currAlivePathCount++;
  419. for (unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  420. if (_paths[i].p && _paths[j].p && _paths[i].p->address().ipsEqual2(_paths[j].p->address()) && i != j) {
  421. duplicatePathsFound+=1;
  422. break;
  423. }
  424. }
  425. }
  426. }
  427. _uniqueAlivePathCount = (currAlivePathCount - (duplicatePathsFound / 2));
  428. _remoteMultipathSupported = _vProto > 9;
  429. _canUseMultipath = _localMultipathSupported && _remoteMultipathSupported && (_uniqueAlivePathCount > 1);
  430. }
  431. if (_canUseMultipath && !_bondToPeer) {
  432. if (RR->bc) {
  433. _bondToPeer = RR->bc->createTransportTriggeredBond(RR, this);
  434. /**
  435. * Allow new bond to retroactively learn all paths known to this peer
  436. */
  437. if (_bondToPeer) {
  438. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  439. if (_paths[i].p) {
  440. _bondToPeer->nominatePath(_paths[i].p, now);
  441. }
  442. }
  443. }
  444. }
  445. }
  446. }
  447. unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
  448. {
  449. unsigned int sent = 0;
  450. Mutex::Lock _l(_paths_m);
  451. performMultipathStateCheck(tPtr, now);
  452. const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
  453. _lastSentFullHello = now;
  454. // Right now we only keep pinging links that have the maximum priority. The
  455. // priority is used to track cluster redirections, meaning that when a cluster
  456. // redirects us its redirect target links override all other links and we
  457. // let those old links expire.
  458. long maxPriority = 0;
  459. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  460. if (_paths[i].p)
  461. maxPriority = std::max(_paths[i].priority,maxPriority);
  462. else break;
  463. }
  464. unsigned int j = 0;
  465. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  466. if (_paths[i].p) {
  467. // Clean expired and reduced priority paths
  468. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  469. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))
  470. || (_canUseMultipath && _paths[i].p->needsGratuitousHeartbeat(now))) {
  471. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  472. _paths[i].p->sent(now);
  473. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  474. }
  475. if (i != j)
  476. _paths[j] = _paths[i];
  477. ++j;
  478. }
  479. } else break;
  480. }
  481. return sent;
  482. }
  483. void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
  484. {
  485. SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
  486. RR->t->peerRedirected(tPtr,0,*this,np);
  487. attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
  488. {
  489. Mutex::Lock _l(_paths_m);
  490. // New priority is higher than the priority of the originating path (if known)
  491. long newPriority = 1;
  492. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  493. if (_paths[i].p) {
  494. if (_paths[i].p == originatingPath) {
  495. newPriority = _paths[i].priority;
  496. break;
  497. }
  498. } else break;
  499. }
  500. newPriority += 2;
  501. // Erase any paths with lower priority than this one or that are duplicate
  502. // IPs and add this path.
  503. unsigned int j = 0;
  504. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  505. if (_paths[i].p) {
  506. if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
  507. if (i != j)
  508. _paths[j] = _paths[i];
  509. ++j;
  510. }
  511. }
  512. }
  513. if (j < ZT_MAX_PEER_NETWORK_PATHS) {
  514. _paths[j].lr = now;
  515. _paths[j].p = np;
  516. _paths[j].priority = newPriority;
  517. ++j;
  518. while (j < ZT_MAX_PEER_NETWORK_PATHS) {
  519. _paths[j].lr = 0;
  520. _paths[j].p.zero();
  521. _paths[j].priority = 1;
  522. ++j;
  523. }
  524. }
  525. }
  526. }
  527. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  528. {
  529. Mutex::Lock _l(_paths_m);
  530. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  531. if (_paths[i].p) {
  532. if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
  533. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
  534. _paths[i].p->sent(now);
  535. _paths[i].lr = 0; // path will not be used unless it speaks again
  536. }
  537. } else break;
  538. }
  539. }
  540. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  541. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  542. {
  543. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  544. return;
  545. }
  546. _bondToPeer->recordOutgoingPacket(path, packetId, payloadLength, verb, flowId, now);
  547. }
  548. void Peer::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  549. {
  550. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  551. return;
  552. }
  553. _bondToPeer->recordIncomingInvalidPacket(path);
  554. }
  555. void Peer::recordIncomingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  556. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  557. {
  558. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  559. return;
  560. }
  561. _bondToPeer->recordIncomingPacket(path, packetId, payloadLength, verb, flowId, now);
  562. }
  563. } // namespace ZeroTier