Peer.cpp 27 KB

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