Peer.cpp 28 KB

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