Peer.cpp 28 KB

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