Peer.cpp 29 KB

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