Peer.cpp 22 KB

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