Peer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. }
  54. uint8_t ktmp[ZT_SYMMETRIC_KEY_SIZE];
  55. KBKDFHMACSHA384(_key,ZT_KBKDF_LABEL_AES_GMAC_SIV_K0,0,0,ktmp);
  56. _aesKeys[0].init(ktmp);
  57. KBKDFHMACSHA384(_key,ZT_KBKDF_LABEL_AES_GMAC_SIV_K1,0,0,ktmp);
  58. _aesKeys[1].init(ktmp);
  59. Utils::burn(ktmp,ZT_SYMMETRIC_KEY_SIZE);
  60. }
  61. void Peer::received(
  62. void *tPtr,
  63. const SharedPtr<Path> &path,
  64. const unsigned int hops,
  65. const uint64_t packetId,
  66. const unsigned int payloadLength,
  67. const Packet::Verb verb,
  68. const uint64_t inRePacketId,
  69. const Packet::Verb inReVerb,
  70. const bool trustEstablished,
  71. const uint64_t networkId,
  72. const int32_t flowId)
  73. {
  74. const int64_t now = RR->node->now();
  75. _lastReceive = now;
  76. switch (verb) {
  77. case Packet::VERB_FRAME:
  78. case Packet::VERB_EXT_FRAME:
  79. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  80. case Packet::VERB_NETWORK_CONFIG:
  81. case Packet::VERB_MULTICAST_FRAME:
  82. _lastNontrivialReceive = now;
  83. break;
  84. default:
  85. break;
  86. }
  87. recordIncomingPacket(path, packetId, payloadLength, verb, flowId, now);
  88. if (trustEstablished) {
  89. _lastTrustEstablishedPacketReceived = now;
  90. path->trustedPacketReceived(now);
  91. }
  92. if (hops == 0) {
  93. // If this is a direct packet (no hops), update existing paths or learn new ones
  94. bool havePath = false;
  95. {
  96. Mutex::Lock _l(_paths_m);
  97. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  98. if (_paths[i].p) {
  99. if (_paths[i].p == path) {
  100. _paths[i].lr = now;
  101. havePath = true;
  102. break;
  103. }
  104. // If same address on same interface then don't learn unless existing path isn't alive (prevents learning loop)
  105. if (_paths[i].p->address().ipsEqual(path->address()) && _paths[i].p->localSocket() == path->localSocket()) {
  106. if (_paths[i].p->alive(now) && !_bond) {
  107. havePath = true;
  108. break;
  109. }
  110. }
  111. } else {
  112. break;
  113. }
  114. }
  115. }
  116. if ( (!havePath) && RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()) ) {
  117. if (verb == Packet::VERB_OK) {
  118. Mutex::Lock _l(_paths_m);
  119. unsigned int oldestPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
  120. unsigned int oldestPathAge = 0;
  121. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  122. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  123. if (_paths[i].p) {
  124. // Keep track of oldest path as a last resort option
  125. unsigned int currAge = _paths[i].p->age(now);
  126. if (currAge > oldestPathAge) {
  127. oldestPathAge = currAge;
  128. oldestPathIdx = i;
  129. }
  130. if (_paths[i].p->address().ipsEqual(path->address())) {
  131. if (_paths[i].p->localSocket() == path->localSocket()) {
  132. if (!_paths[i].p->alive(now)) {
  133. replacePath = i;
  134. break;
  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 {
  253. break;
  254. }
  255. }
  256. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  257. return _paths[bestPath].p;
  258. }
  259. return SharedPtr<Path>();
  260. }
  261. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  262. {
  263. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  264. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  265. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  266. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  267. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  268. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  269. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  270. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  271. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  272. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  273. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  274. myBestV4QualityByScope[i] = 2147483647;
  275. myBestV6QualityByScope[i] = 2147483647;
  276. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  277. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  278. theirBestV4QualityByScope[i] = 2147483647;
  279. theirBestV6QualityByScope[i] = 2147483647;
  280. }
  281. Mutex::Lock _l1(_paths_m);
  282. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  283. if (_paths[i].p) {
  284. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  285. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  286. switch(_paths[i].p->address().ss_family) {
  287. case AF_INET:
  288. if (q <= myBestV4QualityByScope[s]) {
  289. myBestV4QualityByScope[s] = q;
  290. myBestV4ByScope[s] = i;
  291. }
  292. break;
  293. case AF_INET6:
  294. if (q <= myBestV6QualityByScope[s]) {
  295. myBestV6QualityByScope[s] = q;
  296. myBestV6ByScope[s] = i;
  297. }
  298. break;
  299. }
  300. } else {
  301. break;
  302. }
  303. }
  304. Mutex::Lock _l2(other->_paths_m);
  305. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  306. if (other->_paths[i].p) {
  307. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  308. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  309. switch(other->_paths[i].p->address().ss_family) {
  310. case AF_INET:
  311. if (q <= theirBestV4QualityByScope[s]) {
  312. theirBestV4QualityByScope[s] = q;
  313. theirBestV4ByScope[s] = i;
  314. }
  315. break;
  316. case AF_INET6:
  317. if (q <= theirBestV6QualityByScope[s]) {
  318. theirBestV6QualityByScope[s] = q;
  319. theirBestV6ByScope[s] = i;
  320. }
  321. break;
  322. }
  323. } else {
  324. break;
  325. }
  326. }
  327. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  328. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  329. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  330. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  331. mine = myBestV6ByScope[s];
  332. theirs = theirBestV6ByScope[s];
  333. break;
  334. }
  335. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  336. mine = myBestV4ByScope[s];
  337. theirs = theirBestV4ByScope[s];
  338. break;
  339. }
  340. }
  341. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  342. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  343. const unsigned int completed = alt + 2;
  344. while (alt != completed) {
  345. if ((alt & 1) == 0) {
  346. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  347. outp.append((uint8_t)0);
  348. other->_id.address().appendTo(outp);
  349. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  350. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  351. outp.append((uint8_t)16);
  352. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  353. } else {
  354. outp.append((uint8_t)4);
  355. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  356. }
  357. outp.armor(_key,true,aesKeysIfSupported());
  358. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  359. } else {
  360. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  361. outp.append((uint8_t)0);
  362. _id.address().appendTo(outp);
  363. outp.append((uint16_t)_paths[mine].p->address().port());
  364. if (_paths[mine].p->address().ss_family == AF_INET6) {
  365. outp.append((uint8_t)16);
  366. outp.append(_paths[mine].p->address().rawIpData(),16);
  367. } else {
  368. outp.append((uint8_t)4);
  369. outp.append(_paths[mine].p->address().rawIpData(),4);
  370. }
  371. outp.armor(other->_key,true,other->aesKeysIfSupported());
  372. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  373. }
  374. ++alt;
  375. }
  376. }
  377. }
  378. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  379. {
  380. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  381. outp.append((unsigned char)ZT_PROTO_VERSION);
  382. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  383. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  384. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  385. outp.append(now);
  386. RR->identity.serialize(outp,false);
  387. atAddress.serialize(outp);
  388. outp.append((uint64_t)RR->topology->planetWorldId());
  389. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  390. const unsigned int startCryptedPortionAt = outp.size();
  391. std::vector<World> moons(RR->topology->moons());
  392. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  393. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  394. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  395. outp.append((uint8_t)m->type());
  396. outp.append((uint64_t)m->id());
  397. outp.append((uint64_t)m->timestamp());
  398. }
  399. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  400. outp.append((uint8_t)World::TYPE_MOON);
  401. outp.append(*m);
  402. outp.append((uint64_t)0);
  403. }
  404. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  405. if (atAddress) {
  406. outp.armor(_key,false,nullptr); // false == don't encrypt full payload, but add MAC
  407. RR->node->expectReplyTo(outp.packetId());
  408. RR->node->putPacket(tPtr,RR->node->lowBandwidthModeEnabled() ? localSocket : -1,atAddress,outp.data(),outp.size());
  409. } else {
  410. RR->node->expectReplyTo(outp.packetId());
  411. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  412. }
  413. }
  414. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
  415. {
  416. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  417. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  418. outp.armor(_key,true,aesKeysIfSupported());
  419. RR->node->expectReplyTo(outp.packetId());
  420. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  421. } else {
  422. sendHELLO(tPtr,localSocket,atAddress,now);
  423. }
  424. }
  425. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  426. {
  427. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  428. _lastTriedMemorizedPath = now;
  429. InetAddress mp;
  430. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp)) {
  431. attemptToContactAt(tPtr,-1,mp,now,true);
  432. }
  433. }
  434. }
  435. void Peer::performMultipathStateCheck(void *tPtr, int64_t now)
  436. {
  437. Mutex::Lock _l(_bond_m);
  438. if (_bond) {
  439. // Once enabled the Bond object persists, no need to update state
  440. return;
  441. }
  442. /**
  443. * Check for conditions required for multipath bonding and create a bond
  444. * if allowed.
  445. */
  446. int numAlivePaths = 0;
  447. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  448. if (_paths[i].p && _paths[i].p->alive(now)) {
  449. numAlivePaths++;
  450. }
  451. }
  452. _localMultipathSupported = ((numAlivePaths >= 1) && (RR->bc->inUse()) && (ZT_PROTO_VERSION > 9));
  453. if (_localMultipathSupported && !_bond) {
  454. if (RR->bc) {
  455. _bond = RR->bc->createBond(RR, this);
  456. /**
  457. * Allow new bond to retroactively learn all paths known to this peer
  458. */
  459. if (_bond) {
  460. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  461. if (_paths[i].p) {
  462. _bond->nominatePathToBond(_paths[i].p, now);
  463. }
  464. }
  465. }
  466. }
  467. }
  468. }
  469. unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
  470. {
  471. unsigned int sent = 0;
  472. Mutex::Lock _l(_paths_m);
  473. performMultipathStateCheck(tPtr, now);
  474. const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
  475. if (sendFullHello) {
  476. _lastSentFullHello = now;
  477. }
  478. // Right now we only keep pinging links that have the maximum priority. The
  479. // priority is used to track cluster redirections, meaning that when a cluster
  480. // redirects us its redirect target links override all other links and we
  481. // let those old links expire.
  482. long maxPriority = 0;
  483. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  484. if (_paths[i].p) {
  485. maxPriority = std::max(_paths[i].priority,maxPriority);
  486. } else {
  487. break;
  488. }
  489. }
  490. bool deletionOccurred = false;
  491. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  492. if (_paths[i].p) {
  493. // Clean expired and reduced priority paths
  494. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  495. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))) {
  496. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  497. _paths[i].p->sent(now);
  498. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  499. }
  500. } else {
  501. _paths[i] = _PeerPath();
  502. deletionOccurred = true;
  503. }
  504. }
  505. if (!_paths[i].p || deletionOccurred) {
  506. for(unsigned int j=i;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  507. if (_paths[j].p && i != j) {
  508. _paths[i] = _paths[j];
  509. _paths[j] = _PeerPath();
  510. break;
  511. }
  512. }
  513. deletionOccurred = false;
  514. }
  515. }
  516. return sent;
  517. }
  518. void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
  519. {
  520. SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
  521. RR->t->peerRedirected(tPtr,0,*this,np);
  522. attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
  523. {
  524. Mutex::Lock _l(_paths_m);
  525. // New priority is higher than the priority of the originating path (if known)
  526. long newPriority = 1;
  527. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  528. if (_paths[i].p) {
  529. if (_paths[i].p == originatingPath) {
  530. newPriority = _paths[i].priority;
  531. break;
  532. }
  533. } else {
  534. break;
  535. }
  536. }
  537. newPriority += 2;
  538. // Erase any paths with lower priority than this one or that are duplicate
  539. // IPs and add this path.
  540. unsigned int j = 0;
  541. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  542. if (_paths[i].p) {
  543. if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
  544. if (i != j) {
  545. _paths[j] = _paths[i];
  546. }
  547. ++j;
  548. }
  549. }
  550. }
  551. if (j < ZT_MAX_PEER_NETWORK_PATHS) {
  552. _paths[j].lr = now;
  553. _paths[j].p = np;
  554. _paths[j].priority = newPriority;
  555. ++j;
  556. while (j < ZT_MAX_PEER_NETWORK_PATHS) {
  557. _paths[j].lr = 0;
  558. _paths[j].p.zero();
  559. _paths[j].priority = 1;
  560. ++j;
  561. }
  562. }
  563. }
  564. }
  565. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  566. {
  567. Mutex::Lock _l(_paths_m);
  568. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  569. if (_paths[i].p) {
  570. if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
  571. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
  572. _paths[i].p->sent(now);
  573. _paths[i].lr = 0; // path will not be used unless it speaks again
  574. }
  575. } else {
  576. break;
  577. }
  578. }
  579. }
  580. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  581. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  582. {
  583. if (_localMultipathSupported && _bond) {
  584. _bond->recordOutgoingPacket(path, packetId, payloadLength, verb, flowId, now);
  585. }
  586. }
  587. void Peer::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  588. {
  589. if (_localMultipathSupported && _bond) {
  590. _bond->recordIncomingInvalidPacket(path);
  591. }
  592. }
  593. void Peer::recordIncomingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  594. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  595. {
  596. if (_localMultipathSupported && _bond) {
  597. _bond->recordIncomingPacket(path, packetId, payloadLength, verb, flowId, now);
  598. }
  599. }
  600. } // namespace ZeroTier