Peer.cpp 24 KB

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