Peer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "../version.h"
  14. #include "Constants.hpp"
  15. #include "Peer.hpp"
  16. #include "Switch.hpp"
  17. #include "Network.hpp"
  18. #include "SelfAwareness.hpp"
  19. #include "Packet.hpp"
  20. #include "Trace.hpp"
  21. #include "InetAddress.hpp"
  22. #include "RingBuffer.hpp"
  23. #include "Utils.hpp"
  24. namespace ZeroTier {
  25. static unsigned char s_freeRandomByteCounter = 0;
  26. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  27. RR(renv),
  28. _lastReceive(0),
  29. _lastNontrivialReceive(0),
  30. _lastTriedMemorizedPath(0),
  31. _lastDirectPathPushSent(0),
  32. _lastDirectPathPushReceive(0),
  33. _lastEchoRequestReceived(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. _credentialsCutoffCount(0),
  48. _echoRequestCutoffCount(0),
  49. _uniqueAlivePathCount(0),
  50. _localMultipathSupported(false),
  51. _remoteMultipathSupported(false),
  52. _canUseMultipath(false),
  53. _shouldCollectPathStatistics(0),
  54. _lastComputedAggregateMeanLatency(0)
  55. {
  56. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH)) {
  57. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  58. }
  59. }
  60. void Peer::received(
  61. void *tPtr,
  62. const SharedPtr<Path> &path,
  63. const unsigned int hops,
  64. const uint64_t packetId,
  65. const unsigned int payloadLength,
  66. const Packet::Verb verb,
  67. const uint64_t inRePacketId,
  68. const Packet::Verb inReVerb,
  69. const bool trustEstablished,
  70. const uint64_t networkId,
  71. const int32_t flowId)
  72. {
  73. const int64_t now = RR->node->now();
  74. _lastReceive = now;
  75. switch (verb) {
  76. case Packet::VERB_FRAME:
  77. case Packet::VERB_EXT_FRAME:
  78. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  79. case Packet::VERB_NETWORK_CONFIG:
  80. case Packet::VERB_MULTICAST_FRAME:
  81. _lastNontrivialReceive = now;
  82. break;
  83. default:
  84. break;
  85. }
  86. recordIncomingPacket(tPtr, path, packetId, payloadLength, verb, flowId, now);
  87. if (trustEstablished) {
  88. _lastTrustEstablishedPacketReceived = now;
  89. path->trustedPacketReceived(now);
  90. }
  91. if (hops == 0) {
  92. // If this is a direct packet (no hops), update existing paths or learn new ones
  93. bool havePath = false;
  94. {
  95. Mutex::Lock _l(_paths_m);
  96. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  97. if (_paths[i].p) {
  98. if (_paths[i].p == path) {
  99. _paths[i].lr = now;
  100. havePath = true;
  101. break;
  102. }
  103. } else break;
  104. }
  105. }
  106. bool attemptToContact = false;
  107. int replaceIdx = ZT_MAX_PEER_NETWORK_PATHS;
  108. if ((!havePath)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()))) {
  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. // match addr
  113. if ( (_paths[i].p->alive(now)) && ( ((_paths[i].p->localSocket() == path->localSocket())&&(_paths[i].p->address().ss_family == path->address().ss_family)) && (_paths[i].p->address().ipsEqual2(path->address())) ) ) {
  114. // port
  115. if (_paths[i].p->address().port() == path->address().port()) {
  116. replaceIdx = i;
  117. break;
  118. }
  119. }
  120. }
  121. }
  122. if (replaceIdx == ZT_MAX_PEER_NETWORK_PATHS) {
  123. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  124. if (!_paths[i].p) {
  125. replaceIdx = i;
  126. break;
  127. }
  128. }
  129. }
  130. if (replaceIdx != ZT_MAX_PEER_NETWORK_PATHS) {
  131. if (verb == Packet::VERB_OK) {
  132. RR->t->peerLearnedNewPath(tPtr,networkId,*this,path,packetId);
  133. performMultipathStateCheck(now);
  134. if (_bondToPeer) {
  135. _bondToPeer->nominatePath(path, now);
  136. }
  137. _paths[replaceIdx].lr = now;
  138. _paths[replaceIdx].p = path;
  139. _paths[replaceIdx].priority = 1;
  140. } else {
  141. attemptToContact = true;
  142. }
  143. }
  144. }
  145. if (attemptToContact) {
  146. attemptToContactAt(tPtr,path->localSocket(),path->address(),now,true);
  147. path->sent(now);
  148. RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
  149. }
  150. }
  151. // If we have a trust relationship periodically push a message enumerating
  152. // all known external addresses for ourselves. If we already have a path this
  153. // is done less frequently.
  154. if (this->trustEstablished(now)) {
  155. const int64_t sinceLastPush = now - _lastDirectPathPushSent;
  156. if (sinceLastPush >= ((hops == 0) ? ZT_DIRECT_PATH_PUSH_INTERVAL_HAVEPATH : ZT_DIRECT_PATH_PUSH_INTERVAL)) {
  157. _lastDirectPathPushSent = now;
  158. std::vector<InetAddress> pathsToPush(RR->node->directPaths());
  159. if (pathsToPush.size() > 0) {
  160. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  161. while (p != pathsToPush.end()) {
  162. Packet *const outp = new Packet(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  163. outp->addSize(2); // leave room for count
  164. unsigned int count = 0;
  165. while ((p != pathsToPush.end())&&((outp->size() + 24) < 1200)) {
  166. uint8_t addressType = 4;
  167. switch(p->ss_family) {
  168. case AF_INET:
  169. break;
  170. case AF_INET6:
  171. addressType = 6;
  172. break;
  173. default: // we currently only push IP addresses
  174. ++p;
  175. continue;
  176. }
  177. outp->append((uint8_t)0); // no flags
  178. outp->append((uint16_t)0); // no extensions
  179. outp->append(addressType);
  180. outp->append((uint8_t)((addressType == 4) ? 6 : 18));
  181. outp->append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  182. outp->append((uint16_t)p->port());
  183. ++count;
  184. ++p;
  185. }
  186. if (count) {
  187. outp->setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  188. outp->compress();
  189. outp->armor(_key,true);
  190. path->send(RR,tPtr,outp->data(),outp->size(),now);
  191. }
  192. delete outp;
  193. }
  194. }
  195. }
  196. }
  197. }
  198. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired, int32_t flowId)
  199. {
  200. if (!_bondToPeer) {
  201. Mutex::Lock _l(_paths_m);
  202. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  203. /**
  204. * Send traffic across the highest quality path only. This algorithm will still
  205. * use the old path quality metric from protocol version 9.
  206. */
  207. long bestPathQuality = 2147483647;
  208. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  209. if (_paths[i].p) {
  210. if ((includeExpired)||((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)) {
  211. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  212. if (q <= bestPathQuality) {
  213. bestPathQuality = q;
  214. bestPath = i;
  215. }
  216. }
  217. } else break;
  218. }
  219. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  220. return _paths[bestPath].p;
  221. }
  222. return SharedPtr<Path>();
  223. }
  224. return _bondToPeer->getAppropriatePath(now, flowId);
  225. }
  226. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  227. {
  228. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  229. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  230. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  231. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  232. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  233. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  234. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  235. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  236. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  237. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  238. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  239. myBestV4QualityByScope[i] = 2147483647;
  240. myBestV6QualityByScope[i] = 2147483647;
  241. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  242. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  243. theirBestV4QualityByScope[i] = 2147483647;
  244. theirBestV6QualityByScope[i] = 2147483647;
  245. }
  246. Mutex::Lock _l1(_paths_m);
  247. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  248. if (_paths[i].p) {
  249. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  250. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  251. switch(_paths[i].p->address().ss_family) {
  252. case AF_INET:
  253. if (q <= myBestV4QualityByScope[s]) {
  254. myBestV4QualityByScope[s] = q;
  255. myBestV4ByScope[s] = i;
  256. }
  257. break;
  258. case AF_INET6:
  259. if (q <= myBestV6QualityByScope[s]) {
  260. myBestV6QualityByScope[s] = q;
  261. myBestV6ByScope[s] = i;
  262. }
  263. break;
  264. }
  265. } else break;
  266. }
  267. Mutex::Lock _l2(other->_paths_m);
  268. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  269. if (other->_paths[i].p) {
  270. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  271. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  272. switch(other->_paths[i].p->address().ss_family) {
  273. case AF_INET:
  274. if (q <= theirBestV4QualityByScope[s]) {
  275. theirBestV4QualityByScope[s] = q;
  276. theirBestV4ByScope[s] = i;
  277. }
  278. break;
  279. case AF_INET6:
  280. if (q <= theirBestV6QualityByScope[s]) {
  281. theirBestV6QualityByScope[s] = q;
  282. theirBestV6ByScope[s] = i;
  283. }
  284. break;
  285. }
  286. } else break;
  287. }
  288. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  289. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  290. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  291. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  292. mine = myBestV6ByScope[s];
  293. theirs = theirBestV6ByScope[s];
  294. break;
  295. }
  296. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  297. mine = myBestV4ByScope[s];
  298. theirs = theirBestV4ByScope[s];
  299. break;
  300. }
  301. }
  302. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  303. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  304. const unsigned int completed = alt + 2;
  305. while (alt != completed) {
  306. if ((alt & 1) == 0) {
  307. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  308. outp.append((uint8_t)0);
  309. other->_id.address().appendTo(outp);
  310. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  311. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  312. outp.append((uint8_t)16);
  313. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  314. } else {
  315. outp.append((uint8_t)4);
  316. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  317. }
  318. outp.armor(_key,true);
  319. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  320. } else {
  321. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  322. outp.append((uint8_t)0);
  323. _id.address().appendTo(outp);
  324. outp.append((uint16_t)_paths[mine].p->address().port());
  325. if (_paths[mine].p->address().ss_family == AF_INET6) {
  326. outp.append((uint8_t)16);
  327. outp.append(_paths[mine].p->address().rawIpData(),16);
  328. } else {
  329. outp.append((uint8_t)4);
  330. outp.append(_paths[mine].p->address().rawIpData(),4);
  331. }
  332. outp.armor(other->_key,true);
  333. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  334. }
  335. ++alt;
  336. }
  337. }
  338. }
  339. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  340. {
  341. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  342. outp.append((unsigned char)ZT_PROTO_VERSION);
  343. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  344. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  345. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  346. outp.append(now);
  347. RR->identity.serialize(outp,false);
  348. atAddress.serialize(outp);
  349. outp.append((uint64_t)RR->topology->planetWorldId());
  350. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  351. const unsigned int startCryptedPortionAt = outp.size();
  352. std::vector<World> moons(RR->topology->moons());
  353. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  354. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  355. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  356. outp.append((uint8_t)m->type());
  357. outp.append((uint64_t)m->id());
  358. outp.append((uint64_t)m->timestamp());
  359. }
  360. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  361. outp.append((uint8_t)World::TYPE_MOON);
  362. outp.append(*m);
  363. outp.append((uint64_t)0);
  364. }
  365. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  366. RR->node->expectReplyTo(outp.packetId());
  367. if (atAddress) {
  368. outp.armor(_key,false); // false == don't encrypt full payload, but add MAC
  369. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  370. } else {
  371. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  372. }
  373. }
  374. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
  375. {
  376. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  377. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  378. RR->node->expectReplyTo(outp.packetId());
  379. outp.armor(_key,true);
  380. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  381. } else {
  382. sendHELLO(tPtr,localSocket,atAddress,now);
  383. }
  384. }
  385. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  386. {
  387. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  388. _lastTriedMemorizedPath = now;
  389. InetAddress mp;
  390. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  391. attemptToContactAt(tPtr,-1,mp,now,true);
  392. }
  393. }
  394. void Peer::performMultipathStateCheck(int64_t now)
  395. {
  396. /**
  397. * Check for conditions required for multipath bonding and create a bond
  398. * if allowed.
  399. */
  400. _localMultipathSupported = ((RR->bc->inUse()) && (ZT_PROTO_VERSION > 9));
  401. if (_localMultipathSupported) {
  402. int currAlivePathCount = 0;
  403. int duplicatePathsFound = 0;
  404. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  405. if (_paths[i].p) {
  406. currAlivePathCount++;
  407. for (unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  408. if (_paths[i].p && _paths[j].p && _paths[i].p->address().ipsEqual2(_paths[j].p->address()) && i != j) {
  409. duplicatePathsFound+=1;
  410. break;
  411. }
  412. }
  413. }
  414. }
  415. _uniqueAlivePathCount = (currAlivePathCount - (duplicatePathsFound / 2));
  416. _remoteMultipathSupported = _vProto > 9;
  417. _canUseMultipath = _localMultipathSupported && _remoteMultipathSupported && (_uniqueAlivePathCount > 1);
  418. }
  419. if (_canUseMultipath && !_bondToPeer) {
  420. if (RR->bc) {
  421. _bondToPeer = RR->bc->createTransportTriggeredBond(RR, this);
  422. /**
  423. * Allow new bond to retroactively learn all paths known to this peer
  424. */
  425. if (_bondToPeer) {
  426. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  427. if (_paths[i].p) {
  428. _bondToPeer->nominatePath(_paths[i].p, now);
  429. }
  430. }
  431. }
  432. }
  433. }
  434. }
  435. unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
  436. {
  437. unsigned int sent = 0;
  438. Mutex::Lock _l(_paths_m);
  439. performMultipathStateCheck(now);
  440. const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
  441. _lastSentFullHello = now;
  442. // Right now we only keep pinging links that have the maximum priority. The
  443. // priority is used to track cluster redirections, meaning that when a cluster
  444. // redirects us its redirect target links override all other links and we
  445. // let those old links expire.
  446. long maxPriority = 0;
  447. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  448. if (_paths[i].p)
  449. maxPriority = std::max(_paths[i].priority,maxPriority);
  450. else break;
  451. }
  452. unsigned int j = 0;
  453. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  454. if (_paths[i].p) {
  455. // Clean expired and reduced priority paths
  456. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  457. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))
  458. || (_canUseMultipath && _paths[i].p->needsGratuitousHeartbeat(now))) {
  459. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  460. _paths[i].p->sent(now);
  461. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  462. }
  463. if (i != j)
  464. _paths[j] = _paths[i];
  465. ++j;
  466. }
  467. } else break;
  468. }
  469. return sent;
  470. }
  471. void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
  472. {
  473. SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
  474. RR->t->peerRedirected(tPtr,0,*this,np);
  475. attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
  476. {
  477. Mutex::Lock _l(_paths_m);
  478. // New priority is higher than the priority of the originating path (if known)
  479. long newPriority = 1;
  480. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  481. if (_paths[i].p) {
  482. if (_paths[i].p == originatingPath) {
  483. newPriority = _paths[i].priority;
  484. break;
  485. }
  486. } else break;
  487. }
  488. newPriority += 2;
  489. // Erase any paths with lower priority than this one or that are duplicate
  490. // IPs and add this path.
  491. unsigned int j = 0;
  492. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  493. if (_paths[i].p) {
  494. if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
  495. if (i != j)
  496. _paths[j] = _paths[i];
  497. ++j;
  498. }
  499. }
  500. }
  501. if (j < ZT_MAX_PEER_NETWORK_PATHS) {
  502. _paths[j].lr = now;
  503. _paths[j].p = np;
  504. _paths[j].priority = newPriority;
  505. ++j;
  506. while (j < ZT_MAX_PEER_NETWORK_PATHS) {
  507. _paths[j].lr = 0;
  508. _paths[j].p.zero();
  509. _paths[j].priority = 1;
  510. ++j;
  511. }
  512. }
  513. }
  514. }
  515. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  516. {
  517. Mutex::Lock _l(_paths_m);
  518. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  519. if (_paths[i].p) {
  520. if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
  521. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
  522. _paths[i].p->sent(now);
  523. _paths[i].lr = 0; // path will not be used unless it speaks again
  524. }
  525. } else break;
  526. }
  527. }
  528. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  529. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  530. {
  531. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  532. return;
  533. }
  534. _bondToPeer->recordOutgoingPacket(path, packetId, payloadLength, verb, flowId, now);
  535. }
  536. void Peer::recordIncomingInvalidPacket(const SharedPtr<Path>& path)
  537. {
  538. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  539. return;
  540. }
  541. _bondToPeer->recordIncomingInvalidPacket(path);
  542. }
  543. void Peer::recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId,
  544. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now)
  545. {
  546. if (!_shouldCollectPathStatistics || !_bondToPeer) {
  547. return;
  548. }
  549. _bondToPeer->recordIncomingPacket(path, packetId, payloadLength, verb, flowId, now);
  550. }
  551. } // namespace ZeroTier