Peer.cpp 22 KB

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