Peer.cpp 24 KB

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