Peer.cpp 20 KB

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