Peer.cpp 20 KB

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