Peer.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. /*
  2. * Copyright (c)2019 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: 2023-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 "Constants.hpp"
  14. #include "Peer.hpp"
  15. #include "Node.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. #include "ScopedPtr.hpp"
  25. namespace ZeroTier {
  26. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  27. RR(renv),
  28. _lastReceive(0),
  29. _lastDirectPathPushSent(0),
  30. _lastDirectPathPushReceive(0),
  31. _lastCredentialRequestSent(0),
  32. _lastWhoisRequestReceived(0),
  33. _lastEchoRequestReceived(0),
  34. _lastCredentialsReceived(0),
  35. _lastACKWindowReset(0),
  36. _lastQoSWindowReset(0),
  37. _lastMultipathCompatibilityCheck(0),
  38. _lastTriedStaticPath(0),
  39. _uniqueAlivePathCount(0),
  40. _localMultipathSupported(false),
  41. _remoteMultipathSupported(false),
  42. _canUseMultipath(false),
  43. _freeRandomByte((uint8_t)Utils::random()),
  44. _vProto(0),
  45. _vMajor(0),
  46. _vMinor(0),
  47. _vRevision(0),
  48. _id(peerIdentity),
  49. _directPathPushCutoffCount(0),
  50. _credentialsCutoffCount(0),
  51. _linkIsBalanced(false),
  52. _linkIsRedundant(false),
  53. _remotePeerMultipathEnabled(false),
  54. _lastAggregateStatsReport(0),
  55. _lastAggregateAllocation(0)
  56. {
  57. if (!myIdentity.agree(peerIdentity,_key))
  58. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  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 uint64_t networkId)
  70. {
  71. const int64_t now = RR->node->now();
  72. _lastReceive = now;
  73. {
  74. Mutex::Lock _l(_paths_m);
  75. recordIncomingPacket(tPtr, path, packetId, payloadLength, verb, now);
  76. if (_canUseMultipath) {
  77. if (path->needsToSendQoS(now)) {
  78. sendQOS_MEASUREMENT(tPtr, path, path->localSocket(), path->address(), now);
  79. }
  80. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  81. if (_paths[i]) {
  82. _paths[i]->processBackgroundPathMeasurements(now);
  83. }
  84. }
  85. }
  86. }
  87. if (hops == 0) {
  88. // If this is a direct packet (no hops), update existing paths or learn new ones
  89. bool havePath = false;
  90. {
  91. Mutex::Lock _l(_paths_m);
  92. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  93. if (_paths[i]) {
  94. if (_paths[i] == path) {
  95. havePath = true;
  96. break;
  97. }
  98. } else break;
  99. }
  100. }
  101. bool attemptToContact = false;
  102. if ((!havePath)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()))) {
  103. Mutex::Lock _l(_paths_m);
  104. // Paths are redundant if they duplicate an alive path to the same IP or
  105. // with the same local socket and address family.
  106. bool redundant = false;
  107. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  108. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  109. if (_paths[i]) {
  110. if ( (_paths[i]->alive(now)) && ( ((_paths[i]->localSocket() == path->localSocket())&&(_paths[i]->address().ss_family == path->address().ss_family)) || (_paths[i]->address().ipsEqual2(path->address())) ) ) {
  111. redundant = true;
  112. break;
  113. }
  114. // If the path is the same address and port, simply assume this is a replacement
  115. if ( (_paths[i]->address().ipsEqual2(path->address()))) {
  116. replacePath = i;
  117. break;
  118. }
  119. } else break;
  120. }
  121. // If the path isn't a duplicate of the same localSocket AND we haven't already determined a replacePath,
  122. // then find the worst path and replace it.
  123. if (!redundant && replacePath == ZT_MAX_PEER_NETWORK_PATHS) {
  124. int replacePathQuality = 0;
  125. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  126. if (_paths[i]) {
  127. const int q = _paths[i]->quality(now);
  128. if (q > replacePathQuality) {
  129. replacePathQuality = q;
  130. replacePath = i;
  131. }
  132. } else {
  133. replacePath = i;
  134. break;
  135. }
  136. }
  137. }
  138. if (replacePath != ZT_MAX_PEER_NETWORK_PATHS) {
  139. if (verb == Packet::VERB_OK) {
  140. RR->t->peerLearnedNewPath(tPtr,networkId,*this,path,packetId);
  141. _paths[replacePath] = path;
  142. } else {
  143. attemptToContact = true;
  144. }
  145. }
  146. }
  147. if (attemptToContact) {
  148. sendHELLO(tPtr,path->localSocket(),path->address(),now);
  149. path->sent(now);
  150. RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
  151. }
  152. }
  153. // Periodically push direct paths to the peer, doing so more often if we do not
  154. // currently have a direct path.
  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. ScopedPtr<Packet> 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. }
  193. }
  194. }
  195. }
  196. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  197. uint16_t payloadLength, const Packet::Verb verb, int64_t now)
  198. {
  199. _freeRandomByte += (unsigned char)(packetId >> 8); // grab entropy to use in path selection logic for multipath
  200. if (_canUseMultipath) {
  201. path->recordOutgoingPacket(now, packetId, payloadLength, verb);
  202. }
  203. }
  204. void Peer::recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId,
  205. uint16_t payloadLength, const Packet::Verb verb, int64_t now)
  206. {
  207. if (_canUseMultipath) {
  208. if (path->needsToSendAck(now)) {
  209. sendACK(tPtr, path, path->localSocket(), path->address(), now);
  210. }
  211. path->recordIncomingPacket(now, packetId, payloadLength, verb);
  212. }
  213. }
  214. void Peer::computeAggregateProportionalAllocation(int64_t now)
  215. {
  216. float maxStability = 0;
  217. float totalRelativeQuality = 0;
  218. float maxThroughput = 1;
  219. float maxScope = 0;
  220. float relStability[ZT_MAX_PEER_NETWORK_PATHS];
  221. float relThroughput[ZT_MAX_PEER_NETWORK_PATHS];
  222. memset(&relStability, 0, sizeof(relStability));
  223. memset(&relThroughput, 0, sizeof(relThroughput));
  224. // Survey all paths
  225. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  226. if (_paths[i]) {
  227. relStability[i] = _paths[i]->lastComputedStability();
  228. relThroughput[i] = (float)_paths[i]->maxLifetimeThroughput();
  229. maxStability = relStability[i] > maxStability ? relStability[i] : maxStability;
  230. maxThroughput = relThroughput[i] > maxThroughput ? relThroughput[i] : maxThroughput;
  231. maxScope = _paths[i]->ipScope() > maxScope ? _paths[i]->ipScope() : maxScope;
  232. }
  233. }
  234. // Convert to relative values
  235. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  236. if (_paths[i]) {
  237. relStability[i] /= maxStability ? maxStability : 1;
  238. relThroughput[i] /= maxThroughput ? maxThroughput : 1;
  239. float normalized_ma = Utils::normalize((float)_paths[i]->ackAge(now), 0, ZT_PATH_MAX_AGE, 0, 10);
  240. float age_contrib = exp((-1)*normalized_ma);
  241. float relScope = ((float)(_paths[i]->ipScope()+1) / (maxScope + 1));
  242. float relQuality =
  243. (relStability[i] * (float)ZT_PATH_CONTRIB_STABILITY)
  244. + (fmaxf(1.0f, relThroughput[i]) * (float)ZT_PATH_CONTRIB_THROUGHPUT)
  245. + relScope * (float)ZT_PATH_CONTRIB_SCOPE;
  246. relQuality *= age_contrib;
  247. // Arbitrary cutoffs
  248. relQuality = relQuality > (1.00f / 100.0f) ? relQuality : 0.0f;
  249. relQuality = relQuality < (99.0f / 100.0f) ? relQuality : 1.0f;
  250. totalRelativeQuality += relQuality;
  251. _paths[i]->updateRelativeQuality(relQuality);
  252. }
  253. }
  254. // Convert set of relative performances into an allocation set
  255. for(uint16_t i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  256. if (_paths[i]) {
  257. _paths[i]->updateComponentAllocationOfAggregateLink((unsigned char)((_paths[i]->relativeQuality() / totalRelativeQuality) * 255));
  258. }
  259. }
  260. }
  261. int Peer::computeAggregateLinkPacketDelayVariance()
  262. {
  263. float pdv = 0.0;
  264. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  265. if (_paths[i]) {
  266. pdv += _paths[i]->relativeQuality() * _paths[i]->packetDelayVariance();
  267. }
  268. }
  269. return (int)pdv;
  270. }
  271. int Peer::computeAggregateLinkMeanLatency()
  272. {
  273. int ml = 0;
  274. int pathCount = 0;
  275. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  276. if (_paths[i]) {
  277. pathCount++;
  278. ml += (int)(_paths[i]->relativeQuality() * _paths[i]->meanLatency());
  279. }
  280. }
  281. return ml / pathCount;
  282. }
  283. int Peer::aggregateLinkPhysicalPathCount()
  284. {
  285. std::map<std::string, bool> ifnamemap;
  286. int pathCount = 0;
  287. int64_t now = RR->node->now();
  288. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  289. if (_paths[i] && _paths[i]->alive(now)) {
  290. if (!ifnamemap[_paths[i]->getName()]) {
  291. ifnamemap[_paths[i]->getName()] = true;
  292. pathCount++;
  293. }
  294. }
  295. }
  296. return pathCount;
  297. }
  298. int Peer::aggregateLinkLogicalPathCount()
  299. {
  300. int pathCount = 0;
  301. int64_t now = RR->node->now();
  302. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  303. if (_paths[i] && _paths[i]->alive(now)) {
  304. pathCount++;
  305. }
  306. }
  307. return pathCount;
  308. }
  309. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired)
  310. {
  311. Mutex::Lock _l(_paths_m);
  312. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  313. /**
  314. * Send traffic across the highest quality path only. This algorithm will still
  315. * use the old path quality metric from protocol version 9.
  316. */
  317. if (!_canUseMultipath) {
  318. long bestPathQuality = 2147483647;
  319. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  320. if (_paths[i]) {
  321. if ((includeExpired)||(_paths[i]->alive(now))) {
  322. const long q = _paths[i]->quality(now);
  323. if (q <= bestPathQuality) {
  324. bestPathQuality = q;
  325. bestPath = i;
  326. }
  327. }
  328. } else break;
  329. }
  330. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  331. return _paths[bestPath];
  332. }
  333. return SharedPtr<Path>();
  334. }
  335. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  336. if (_paths[i]) {
  337. _paths[i]->processBackgroundPathMeasurements(now);
  338. }
  339. }
  340. /**
  341. * Randomly distribute traffic across all paths
  342. */
  343. int numAlivePaths = 0;
  344. int numStalePaths = 0;
  345. if (RR->node->getMultipathMode() == ZT_MULTIPATH_RANDOM) {
  346. int alivePaths[ZT_MAX_PEER_NETWORK_PATHS];
  347. int stalePaths[ZT_MAX_PEER_NETWORK_PATHS];
  348. memset(&alivePaths, -1, sizeof(alivePaths));
  349. memset(&stalePaths, -1, sizeof(stalePaths));
  350. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  351. if (_paths[i]) {
  352. if (_paths[i]->alive(now)) {
  353. alivePaths[numAlivePaths] = i;
  354. numAlivePaths++;
  355. }
  356. else {
  357. stalePaths[numStalePaths] = i;
  358. numStalePaths++;
  359. }
  360. }
  361. }
  362. unsigned int r = _freeRandomByte;
  363. if (numAlivePaths > 0) {
  364. int rf = r % numAlivePaths;
  365. return _paths[alivePaths[rf]];
  366. }
  367. else if(numStalePaths > 0) {
  368. // Resort to trying any non-expired path
  369. int rf = r % numStalePaths;
  370. return _paths[stalePaths[rf]];
  371. }
  372. }
  373. /**
  374. * Proportionally allocate traffic according to dynamic path quality measurements
  375. */
  376. if (RR->node->getMultipathMode() == ZT_MULTIPATH_PROPORTIONALLY_BALANCED) {
  377. if ((now - _lastAggregateAllocation) >= ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
  378. _lastAggregateAllocation = now;
  379. computeAggregateProportionalAllocation(now);
  380. }
  381. // Randomly choose path according to their allocations
  382. float rf = _freeRandomByte;
  383. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  384. if (_paths[i]) {
  385. if (rf < _paths[i]->allocation()) {
  386. bestPath = i;
  387. _pathChoiceHist.push(bestPath); // Record which path we chose
  388. break;
  389. }
  390. rf -= _paths[i]->allocation();
  391. }
  392. }
  393. if (bestPath < ZT_MAX_PEER_NETWORK_PATHS) {
  394. return _paths[bestPath];
  395. }
  396. }
  397. return SharedPtr<Path>();
  398. }
  399. char *Peer::interfaceListStr()
  400. {
  401. std::map<std::string, int> ifnamemap;
  402. char tmp[32];
  403. const int64_t now = RR->node->now();
  404. char *ptr = _interfaceListStr;
  405. bool imbalanced = false;
  406. memset(_interfaceListStr, 0, sizeof(_interfaceListStr));
  407. int alivePathCount = aggregateLinkLogicalPathCount();
  408. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  409. if (_paths[i] && _paths[i]->alive(now)) {
  410. int ipv = _paths[i]->address().isV4();
  411. // If this is acting as an aggregate link, check allocations
  412. float targetAllocation = 1.0f / (float)alivePathCount;
  413. float currentAllocation = 1.0f;
  414. if (alivePathCount > 1) {
  415. currentAllocation = (float)_pathChoiceHist.countValue(i) / (float)_pathChoiceHist.count();
  416. if (fabs(targetAllocation - currentAllocation) > ZT_PATH_IMBALANCE_THRESHOLD) {
  417. imbalanced = true;
  418. }
  419. }
  420. char *ipvStr = ipv ? (char*)"ipv4" : (char*)"ipv6";
  421. sprintf(tmp, "(%s, %s, %.3f)", _paths[i]->getName(), ipvStr, currentAllocation);
  422. // Prevent duplicates
  423. if(ifnamemap[_paths[i]->getName()] != ipv) {
  424. memcpy(ptr, tmp, strlen(tmp));
  425. ptr += strlen(tmp);
  426. *ptr = ' ';
  427. ptr++;
  428. ifnamemap[_paths[i]->getName()] = ipv;
  429. }
  430. }
  431. }
  432. ptr--; // Overwrite trailing space
  433. if (imbalanced) {
  434. sprintf(tmp, ", is asymmetrical");
  435. memcpy(ptr, tmp, sizeof(tmp));
  436. } else {
  437. *ptr = '\0';
  438. }
  439. return _interfaceListStr;
  440. }
  441. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  442. {
  443. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  444. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  445. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  446. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  447. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  448. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  449. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  450. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  451. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  452. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  453. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  454. myBestV4QualityByScope[i] = 2147483647;
  455. myBestV6QualityByScope[i] = 2147483647;
  456. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  457. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  458. theirBestV4QualityByScope[i] = 2147483647;
  459. theirBestV6QualityByScope[i] = 2147483647;
  460. }
  461. Mutex::Lock _l1(_paths_m);
  462. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  463. if (_paths[i]) {
  464. const long q = _paths[i]->quality(now);
  465. const unsigned int s = (unsigned int)_paths[i]->ipScope();
  466. switch(_paths[i]->address().ss_family) {
  467. case AF_INET:
  468. if (q <= myBestV4QualityByScope[s]) {
  469. myBestV4QualityByScope[s] = q;
  470. myBestV4ByScope[s] = i;
  471. }
  472. break;
  473. case AF_INET6:
  474. if (q <= myBestV6QualityByScope[s]) {
  475. myBestV6QualityByScope[s] = q;
  476. myBestV6ByScope[s] = i;
  477. }
  478. break;
  479. }
  480. } else break;
  481. }
  482. Mutex::Lock _l2(other->_paths_m);
  483. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  484. if (other->_paths[i]) {
  485. const long q = other->_paths[i]->quality(now);
  486. const unsigned int s = (unsigned int)other->_paths[i]->ipScope();
  487. switch(other->_paths[i]->address().ss_family) {
  488. case AF_INET:
  489. if (q <= theirBestV4QualityByScope[s]) {
  490. theirBestV4QualityByScope[s] = q;
  491. theirBestV4ByScope[s] = i;
  492. }
  493. break;
  494. case AF_INET6:
  495. if (q <= theirBestV6QualityByScope[s]) {
  496. theirBestV6QualityByScope[s] = q;
  497. theirBestV6ByScope[s] = i;
  498. }
  499. break;
  500. }
  501. } else break;
  502. }
  503. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  504. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  505. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  506. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  507. mine = myBestV6ByScope[s];
  508. theirs = theirBestV6ByScope[s];
  509. break;
  510. }
  511. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  512. mine = myBestV4ByScope[s];
  513. theirs = theirBestV4ByScope[s];
  514. break;
  515. }
  516. }
  517. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  518. unsigned int alt = (unsigned int)Utils::random() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  519. const unsigned int completed = alt + 2;
  520. while (alt != completed) {
  521. if ((alt & 1) == 0) {
  522. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  523. outp.append((uint8_t)0);
  524. other->_id.address().appendTo(outp);
  525. outp.append((uint16_t)other->_paths[theirs]->address().port());
  526. if (other->_paths[theirs]->address().ss_family == AF_INET6) {
  527. outp.append((uint8_t)16);
  528. outp.append(other->_paths[theirs]->address().rawIpData(),16);
  529. } else {
  530. outp.append((uint8_t)4);
  531. outp.append(other->_paths[theirs]->address().rawIpData(),4);
  532. }
  533. outp.armor(_key,true);
  534. _paths[mine]->send(RR,tPtr,outp.data(),outp.size(),now);
  535. } else {
  536. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  537. outp.append((uint8_t)0);
  538. _id.address().appendTo(outp);
  539. outp.append((uint16_t)_paths[mine]->address().port());
  540. if (_paths[mine]->address().ss_family == AF_INET6) {
  541. outp.append((uint8_t)16);
  542. outp.append(_paths[mine]->address().rawIpData(),16);
  543. } else {
  544. outp.append((uint8_t)4);
  545. outp.append(_paths[mine]->address().rawIpData(),4);
  546. }
  547. outp.armor(other->_key,true);
  548. other->_paths[theirs]->send(RR,tPtr,outp.data(),outp.size(),now);
  549. }
  550. ++alt;
  551. }
  552. }
  553. }
  554. inline void Peer::processBackgroundPeerTasks(const int64_t now)
  555. {
  556. // Determine current multipath compatibility with other peer
  557. if ((now - _lastMultipathCompatibilityCheck) >= ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
  558. //
  559. // Cache number of available paths so that we can short-circuit multipath logic elsewhere
  560. //
  561. // We also take notice of duplicate paths (same IP only) because we may have
  562. // recently received a direct path push from a peer and our list might contain
  563. // a dead path which hasn't been fully recognized as such. In this case we
  564. // don't want the duplicate to trigger execution of multipath code prematurely.
  565. //
  566. // This is done to support the behavior of auto multipath enable/disable
  567. // without user intervention.
  568. //
  569. int currAlivePathCount = 0;
  570. int duplicatePathsFound = 0;
  571. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  572. if (_paths[i]) {
  573. currAlivePathCount++;
  574. for (unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  575. if (_paths[i] && _paths[j] && _paths[i]->address().ipsEqual2(_paths[j]->address()) && i != j) {
  576. duplicatePathsFound+=1;
  577. break;
  578. }
  579. }
  580. }
  581. }
  582. _uniqueAlivePathCount = (currAlivePathCount - (duplicatePathsFound / 2));
  583. _lastMultipathCompatibilityCheck = now;
  584. _localMultipathSupported = ((RR->node->getMultipathMode() != ZT_MULTIPATH_NONE) && (ZT_PROTO_VERSION > 9));
  585. _remoteMultipathSupported = _vProto > 9;
  586. // If both peers support multipath and more than one path exist, we can use multipath logic
  587. _canUseMultipath = _localMultipathSupported && _remoteMultipathSupported && (_uniqueAlivePathCount > 1);
  588. }
  589. }
  590. void Peer::sendACK(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  591. {
  592. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ACK);
  593. uint32_t bytesToAck = path->bytesToAck();
  594. outp.append<uint32_t>(bytesToAck);
  595. if (atAddress) {
  596. outp.armor(_key,false);
  597. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  598. } else {
  599. RR->sw->send(tPtr,outp,false);
  600. }
  601. path->sentAck(now);
  602. }
  603. void Peer::sendQOS_MEASUREMENT(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  604. {
  605. const int64_t _now = RR->node->now();
  606. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_QOS_MEASUREMENT);
  607. char qosData[ZT_PATH_MAX_QOS_PACKET_SZ];
  608. int16_t len = path->generateQoSPacket(_now,qosData);
  609. outp.append(qosData,len);
  610. if (atAddress) {
  611. outp.armor(_key,false);
  612. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  613. } else {
  614. RR->sw->send(tPtr,outp,false);
  615. }
  616. path->sentQoS(now);
  617. }
  618. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  619. {
  620. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  621. outp.append((unsigned char)ZT_PROTO_VERSION);
  622. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  623. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  624. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  625. outp.append(now);
  626. RR->identity.serialize(outp,false);
  627. atAddress.serialize(outp);
  628. RR->node->expectReplyTo(outp.packetId());
  629. if (atAddress) {
  630. outp.armor(_key,false); // false == don't encrypt full payload, but add MAC
  631. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  632. } else {
  633. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  634. }
  635. }
  636. void Peer::ping(void *tPtr,int64_t now,unsigned int &v4SendCount,unsigned int &v6SendCount)
  637. {
  638. v4SendCount = 0;
  639. v6SendCount = 0;
  640. Mutex::Lock _l(_paths_m);
  641. // Emit traces regarding aggregate link status
  642. if (_canUseMultipath) {
  643. int alivePathCount = aggregateLinkPhysicalPathCount();
  644. if ((now - _lastAggregateStatsReport) > ZT_PATH_AGGREGATE_STATS_REPORT_INTERVAL) {
  645. _lastAggregateStatsReport = now;
  646. if (alivePathCount) {
  647. RR->t->peerLinkAggregateStatistics(NULL,*this);
  648. }
  649. } if (alivePathCount < 2 && _linkIsRedundant) {
  650. _linkIsRedundant = !_linkIsRedundant;
  651. RR->t->peerLinkNoLongerRedundant(NULL,*this);
  652. } if (alivePathCount > 1 && !_linkIsRedundant) {
  653. _linkIsRedundant = !_linkIsRedundant;
  654. RR->t->peerLinkNowRedundant(NULL,*this);
  655. }
  656. }
  657. unsigned int j = 0;
  658. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  659. if ((_paths[i])&&(_paths[i]->alive(now))) {
  660. sendHELLO(tPtr,_paths[i]->localSocket(),_paths[i]->address(),now);
  661. _paths[i]->sent(now);
  662. if (_paths[i]->address().isV4())
  663. ++v4SendCount;
  664. else if (_paths[i]->address().isV6())
  665. ++v6SendCount;
  666. if (i != j)
  667. _paths[j] = _paths[i];
  668. ++j;
  669. }
  670. }
  671. while(j < ZT_MAX_PEER_NETWORK_PATHS) {
  672. _paths[j].zero();
  673. ++j;
  674. }
  675. }
  676. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  677. {
  678. Mutex::Lock _l(_paths_m);
  679. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  680. if (_paths[i]) {
  681. if ((_paths[i]->address().ss_family == inetAddressFamily)&&(_paths[i]->ipScope() == scope)) {
  682. sendHELLO(tPtr,_paths[i]->localSocket(),_paths[i]->address(),now);
  683. _paths[i]->sent(now);
  684. }
  685. } else break;
  686. }
  687. }
  688. } // namespace ZeroTier