Peer.cpp 19 KB

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