Peer.cpp 24 KB

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