Peer.cpp 20 KB

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