Peer.cpp 29 KB

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