Peer.cpp 20 KB

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