Peer.cpp 19 KB

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