Peer.cpp 22 KB

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