Peer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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. 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. _lastComRequestReceived(0),
  50. _lastComRequestSent(0),
  51. _lastCredentialsReceived(0),
  52. _lastTrustEstablishedPacketReceived(0),
  53. _lastSentFullHello(0),
  54. _lastACKWindowReset(0),
  55. _lastQoSWindowReset(0),
  56. _vProto(0),
  57. _vMajor(0),
  58. _vMinor(0),
  59. _vRevision(0),
  60. _id(peerIdentity),
  61. _directPathPushCutoffCount(0),
  62. _credentialsCutoffCount(0),
  63. _linkIsBalanced(false),
  64. _linkIsRedundant(false),
  65. _remotePeerMultipathEnabled(false),
  66. _lastAggregateStatsReport(0),
  67. _lastAggregateAllocation(0)
  68. {
  69. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  70. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  71. _pathChoiceHist = new RingBuffer<int>(ZT_MULTIPATH_PROPORTION_WIN_SZ);
  72. }
  73. void Peer::received(
  74. void *tPtr,
  75. const SharedPtr<Path> &path,
  76. const unsigned int hops,
  77. const uint64_t packetId,
  78. const unsigned int payloadLength,
  79. const Packet::Verb verb,
  80. const uint64_t inRePacketId,
  81. const Packet::Verb inReVerb,
  82. const bool trustEstablished,
  83. const uint64_t networkId)
  84. {
  85. const int64_t now = RR->node->now();
  86. _lastReceive = now;
  87. switch (verb) {
  88. case Packet::VERB_FRAME:
  89. case Packet::VERB_EXT_FRAME:
  90. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  91. case Packet::VERB_NETWORK_CONFIG:
  92. case Packet::VERB_MULTICAST_FRAME:
  93. _lastNontrivialReceive = now;
  94. break;
  95. default: break;
  96. }
  97. if (trustEstablished) {
  98. _lastTrustEstablishedPacketReceived = now;
  99. path->trustedPacketReceived(now);
  100. }
  101. {
  102. Mutex::Lock _l(_paths_m);
  103. recordIncomingPacket(tPtr, path, packetId, payloadLength, verb, now);
  104. if (canUseMultipath()) {
  105. if (path->needsToSendQoS(now)) {
  106. sendQOS_MEASUREMENT(tPtr, path, path->localSocket(), path->address(), now);
  107. }
  108. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  109. if (_paths[i].p) {
  110. _paths[i].p->processBackgroundPathMeasurements(now);
  111. }
  112. }
  113. }
  114. }
  115. if (hops == 0) {
  116. // If this is a direct packet (no hops), update existing paths or learn new ones
  117. bool havePath = false;
  118. {
  119. Mutex::Lock _l(_paths_m);
  120. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  121. if (_paths[i].p) {
  122. if (_paths[i].p == path) {
  123. _paths[i].lr = now;
  124. havePath = true;
  125. break;
  126. }
  127. } else break;
  128. }
  129. }
  130. bool attemptToContact = false;
  131. if ((!havePath)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()))) {
  132. Mutex::Lock _l(_paths_m);
  133. // Paths are redundant if they duplicate an alive path to the same IP or
  134. // with the same local socket and address family.
  135. bool redundant = false;
  136. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  137. if (_paths[i].p) {
  138. 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())) ) ) {
  139. redundant = true;
  140. break;
  141. }
  142. } else break;
  143. }
  144. if (!redundant) {
  145. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  146. int replacePathQuality = 0;
  147. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  148. if (_paths[i].p) {
  149. const int q = _paths[i].p->quality(now);
  150. if (q > replacePathQuality) {
  151. replacePathQuality = q;
  152. replacePath = i;
  153. }
  154. } else {
  155. replacePath = i;
  156. break;
  157. }
  158. }
  159. // If we find a pre-existing path with the same address, just replace it.
  160. // If we don't find anything we can replace, just use the replacePath that we previously decided on.
  161. if (canUseMultipath()) {
  162. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  163. if (_paths[i].p) {
  164. if ( _paths[i].p->address().ss_family == path->address().ss_family && _paths[i].p->address().ipsEqual2(path->address())) {
  165. replacePath = i;
  166. break;
  167. }
  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. }
  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. We now do this even if we
  191. // have a current path since we'll want to use new ones too.
  192. if (this->trustEstablished(now)) {
  193. if ((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  194. _lastDirectPathPushSent = now;
  195. std::vector<InetAddress> pathsToPush;
  196. std::vector<InetAddress> dps(RR->node->directPaths());
  197. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  198. pathsToPush.push_back(*i);
  199. // Do symmetric NAT prediction if we are communicating indirectly.
  200. if (hops > 0) {
  201. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  202. for(unsigned long i=0,added=0;i<sym.size();++i) {
  203. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  204. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  205. pathsToPush.push_back(tmp);
  206. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  207. break;
  208. }
  209. }
  210. }
  211. if (pathsToPush.size() > 0) {
  212. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  213. while (p != pathsToPush.end()) {
  214. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  215. outp.addSize(2); // leave room for count
  216. unsigned int count = 0;
  217. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  218. uint8_t addressType = 4;
  219. switch(p->ss_family) {
  220. case AF_INET:
  221. break;
  222. case AF_INET6:
  223. addressType = 6;
  224. break;
  225. default: // we currently only push IP addresses
  226. ++p;
  227. continue;
  228. }
  229. outp.append((uint8_t)0); // no flags
  230. outp.append((uint16_t)0); // no extensions
  231. outp.append(addressType);
  232. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  233. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  234. outp.append((uint16_t)p->port());
  235. ++count;
  236. ++p;
  237. }
  238. if (count) {
  239. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  240. outp.armor(_key,true);
  241. path->send(RR,tPtr,outp.data(),outp.size(),now);
  242. }
  243. }
  244. }
  245. }
  246. }
  247. }
  248. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  249. uint16_t payloadLength, const Packet::Verb verb, int64_t now)
  250. {
  251. if (localMultipathSupport()) {
  252. path->recordOutgoingPacket(now, packetId, payloadLength, verb);
  253. }
  254. }
  255. void Peer::recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId,
  256. uint16_t payloadLength, const Packet::Verb verb, int64_t now)
  257. {
  258. if (localMultipathSupport()) {
  259. if (path->needsToSendAck(now)) {
  260. sendACK(tPtr, path, path->localSocket(), path->address(), now);
  261. }
  262. path->recordIncomingPacket(now, packetId, payloadLength, verb);
  263. }
  264. }
  265. void Peer::computeAggregateProportionalAllocation(int64_t now)
  266. {
  267. float maxStability = 0;
  268. float totalRelativeQuality = 0;
  269. float maxThroughput = 1;
  270. float maxScope = 0;
  271. float relStability[ZT_MAX_PEER_NETWORK_PATHS];
  272. float relThroughput[ZT_MAX_PEER_NETWORK_PATHS];
  273. memset(&relStability, 0, sizeof(relStability));
  274. memset(&relThroughput, 0, sizeof(relThroughput));
  275. // Survey all paths
  276. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  277. if (_paths[i].p) {
  278. relStability[i] = _paths[i].p->lastComputedStability();
  279. relThroughput[i] = _paths[i].p->maxLifetimeThroughput();
  280. maxStability = relStability[i] > maxStability ? relStability[i] : maxStability;
  281. maxThroughput = relThroughput[i] > maxThroughput ? relThroughput[i] : maxThroughput;
  282. maxScope = _paths[i].p->ipScope() > maxScope ? _paths[i].p->ipScope() : maxScope;
  283. }
  284. }
  285. // Convert to relative values
  286. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  287. if (_paths[i].p) {
  288. relStability[i] /= maxStability ? maxStability : 1;
  289. relThroughput[i] /= maxThroughput ? maxThroughput : 1;
  290. float normalized_ma = Utils::normalize(_paths[i].p->ackAge(now), 0, ZT_PATH_MAX_AGE, 0, 10);
  291. float age_contrib = exp((-1)*normalized_ma);
  292. float relScope = ((float)(_paths[i].p->ipScope()+1) / (maxScope + 1));
  293. float relQuality =
  294. (relStability[i] * ZT_PATH_CONTRIB_STABILITY)
  295. + (fmax(1, relThroughput[i]) * ZT_PATH_CONTRIB_THROUGHPUT)
  296. + relScope * ZT_PATH_CONTRIB_SCOPE;
  297. relQuality *= age_contrib;
  298. totalRelativeQuality += relQuality;
  299. _paths[i].p->updateRelativeQuality(relQuality);
  300. }
  301. }
  302. // Convert set of relative performances into an allocation set
  303. for(uint16_t i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  304. if (_paths[i].p) {
  305. _paths[i].p->updateComponentAllocationOfAggregateLink(_paths[i].p->relativeQuality() / totalRelativeQuality);
  306. }
  307. }
  308. }
  309. float Peer::computeAggregateLinkPacketDelayVariance()
  310. {
  311. float pdv = 0.0;
  312. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  313. if (_paths[i].p) {
  314. pdv += _paths[i].p->relativeQuality() * _paths[i].p->packetDelayVariance();
  315. }
  316. }
  317. return pdv;
  318. }
  319. float Peer::computeAggregateLinkMeanLatency()
  320. {
  321. float ml = 0.0;
  322. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  323. if (_paths[i].p) {
  324. ml += _paths[i].p->relativeQuality() * _paths[i].p->meanLatency();
  325. }
  326. }
  327. return ml;
  328. }
  329. int Peer::aggregateLinkPhysicalPathCount()
  330. {
  331. std::map<std::string, bool> ifnamemap;
  332. int pathCount = 0;
  333. int64_t now = RR->node->now();
  334. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  335. if (_paths[i].p && _paths[i].p->alive(now)) {
  336. if (!ifnamemap[_paths[i].p->getName()]) {
  337. ifnamemap[_paths[i].p->getName()] = true;
  338. pathCount++;
  339. }
  340. }
  341. }
  342. return pathCount;
  343. }
  344. int Peer::aggregateLinkLogicalPathCount()
  345. {
  346. int pathCount = 0;
  347. int64_t now = RR->node->now();
  348. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  349. if (_paths[i].p && _paths[i].p->alive(now)) {
  350. pathCount++;
  351. }
  352. }
  353. return pathCount;
  354. }
  355. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired)
  356. {
  357. Mutex::Lock _l(_paths_m);
  358. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  359. /**
  360. * Send traffic across the highest quality path only. This algorithm will still
  361. * use the old path quality metric from protocol version 9.
  362. */
  363. if (!canUseMultipath()) {
  364. long bestPathQuality = 2147483647;
  365. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  366. if (_paths[i].p) {
  367. if ((includeExpired)||((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)) {
  368. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  369. if (q <= bestPathQuality) {
  370. bestPathQuality = q;
  371. bestPath = i;
  372. }
  373. }
  374. } else break;
  375. }
  376. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  377. return _paths[bestPath].p;
  378. }
  379. return SharedPtr<Path>();
  380. }
  381. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  382. if (_paths[i].p) {
  383. _paths[i].p->processBackgroundPathMeasurements(now);
  384. }
  385. }
  386. /**
  387. * Randomly distribute traffic across all paths
  388. */
  389. int numAlivePaths = 0;
  390. int numStalePaths = 0;
  391. if (RR->node->getMultipathMode() == ZT_MULTIPATH_RANDOM) {
  392. int alivePaths[ZT_MAX_PEER_NETWORK_PATHS];
  393. int stalePaths[ZT_MAX_PEER_NETWORK_PATHS];
  394. memset(&alivePaths, -1, sizeof(alivePaths));
  395. memset(&stalePaths, -1, sizeof(stalePaths));
  396. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  397. if (_paths[i].p) {
  398. if (_paths[i].p->alive(now)) {
  399. alivePaths[numAlivePaths] = i;
  400. numAlivePaths++;
  401. }
  402. else {
  403. stalePaths[numStalePaths] = i;
  404. numStalePaths++;
  405. }
  406. }
  407. }
  408. unsigned int r;
  409. Utils::getSecureRandom(&r, 1);
  410. if (numAlivePaths > 0) {
  411. // pick a random out of the set deemed "alive"
  412. int rf = r % numAlivePaths;
  413. return _paths[alivePaths[rf]].p;
  414. }
  415. else if(numStalePaths > 0) {
  416. // resort to trying any non-expired path
  417. int rf = r % numStalePaths;
  418. return _paths[stalePaths[rf]].p;
  419. }
  420. }
  421. /**
  422. * Proportionally allocate traffic according to dynamic path quality measurements
  423. */
  424. if (RR->node->getMultipathMode() == ZT_MULTIPATH_PROPORTIONALLY_BALANCED) {
  425. int numAlivePaths = 0;
  426. int numStalePaths = 0;
  427. int alivePaths[ZT_MAX_PEER_NETWORK_PATHS];
  428. int stalePaths[ZT_MAX_PEER_NETWORK_PATHS];
  429. memset(&alivePaths, -1, sizeof(alivePaths));
  430. memset(&stalePaths, -1, sizeof(stalePaths));
  431. // Attempt to find an excuse not to use the rest of this algorithm
  432. // Alive or Stale?
  433. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  434. if (_paths[i].p) {
  435. if (_paths[i].p->alive(now)) {
  436. alivePaths[numAlivePaths] = i;
  437. numAlivePaths++;
  438. } else {
  439. stalePaths[numStalePaths] = i;
  440. numStalePaths++;
  441. }
  442. // Record a default path to use as a short-circuit for the rest of the algorithm (if needed)
  443. bestPath = i;
  444. }
  445. }
  446. if ((now - _lastAggregateAllocation) >= ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
  447. _lastAggregateAllocation = now;
  448. computeAggregateProportionalAllocation(now);
  449. }
  450. if (numAlivePaths == 0 && numStalePaths == 0) {
  451. return SharedPtr<Path>();
  452. } if (numAlivePaths == 1 || numStalePaths == 1) {
  453. return _paths[bestPath].p;
  454. }
  455. // Randomly choose path according to their allocations
  456. unsigned int r;
  457. Utils::getSecureRandom(&r, 1);
  458. float rf = (float)(r %= 100) / 100;
  459. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  460. if (_paths[i].p) {
  461. if (rf < _paths[i].p->allocation()) {
  462. bestPath = i;
  463. _pathChoiceHist->push(bestPath); // Record which path we chose
  464. break;
  465. }
  466. rf -= _paths[i].p->allocation();
  467. }
  468. }
  469. if (bestPath < ZT_MAX_PEER_NETWORK_PATHS) {
  470. return _paths[bestPath].p;
  471. }
  472. }
  473. return SharedPtr<Path>();
  474. }
  475. char *Peer::interfaceListStr()
  476. {
  477. std::map<std::string, int> ifnamemap;
  478. char tmp[32];
  479. const int64_t now = RR->node->now();
  480. char *ptr = _interfaceListStr;
  481. bool imbalanced = false;
  482. memset(_interfaceListStr, 0, sizeof(_interfaceListStr));
  483. int alivePathCount = aggregateLinkLogicalPathCount();
  484. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  485. if (_paths[i].p && _paths[i].p->alive(now)) {
  486. int ipv = _paths[i].p->address().isV4();
  487. // If this is acting as an aggregate link, check allocations
  488. float targetAllocation = 1.0 / alivePathCount;
  489. float currentAllocation = 1.0;
  490. if (alivePathCount > 1) {
  491. currentAllocation = (float)_pathChoiceHist->countValue(i) / (float)_pathChoiceHist->count();
  492. if (fabs(targetAllocation - currentAllocation) > ZT_PATH_IMBALANCE_THRESHOLD) {
  493. imbalanced = true;
  494. }
  495. }
  496. char *ipvStr = ipv ? (char*)"ipv4" : (char*)"ipv6";
  497. sprintf(tmp, "(%s, %s, %.3f)", _paths[i].p->getName(), ipvStr, currentAllocation);
  498. // Prevent duplicates
  499. if(ifnamemap[_paths[i].p->getName()] != ipv) {
  500. memcpy(ptr, tmp, strlen(tmp));
  501. ptr += strlen(tmp);
  502. *ptr = ' ';
  503. ptr++;
  504. ifnamemap[_paths[i].p->getName()] = ipv;
  505. }
  506. }
  507. }
  508. ptr--; // Overwrite trailing space
  509. if (imbalanced) {
  510. sprintf(tmp, ", is asymmetrical");
  511. memcpy(ptr, tmp, sizeof(tmp));
  512. } else {
  513. *ptr = '\0';
  514. }
  515. return _interfaceListStr;
  516. }
  517. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  518. {
  519. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  520. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  521. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  522. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  523. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  524. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  525. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  526. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  527. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  528. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  529. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  530. myBestV4QualityByScope[i] = 2147483647;
  531. myBestV6QualityByScope[i] = 2147483647;
  532. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  533. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  534. theirBestV4QualityByScope[i] = 2147483647;
  535. theirBestV6QualityByScope[i] = 2147483647;
  536. }
  537. Mutex::Lock _l1(_paths_m);
  538. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  539. if (_paths[i].p) {
  540. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  541. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  542. switch(_paths[i].p->address().ss_family) {
  543. case AF_INET:
  544. if (q <= myBestV4QualityByScope[s]) {
  545. myBestV4QualityByScope[s] = q;
  546. myBestV4ByScope[s] = i;
  547. }
  548. break;
  549. case AF_INET6:
  550. if (q <= myBestV6QualityByScope[s]) {
  551. myBestV6QualityByScope[s] = q;
  552. myBestV6ByScope[s] = i;
  553. }
  554. break;
  555. }
  556. } else break;
  557. }
  558. Mutex::Lock _l2(other->_paths_m);
  559. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  560. if (other->_paths[i].p) {
  561. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  562. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  563. switch(other->_paths[i].p->address().ss_family) {
  564. case AF_INET:
  565. if (q <= theirBestV4QualityByScope[s]) {
  566. theirBestV4QualityByScope[s] = q;
  567. theirBestV4ByScope[s] = i;
  568. }
  569. break;
  570. case AF_INET6:
  571. if (q <= theirBestV6QualityByScope[s]) {
  572. theirBestV6QualityByScope[s] = q;
  573. theirBestV6ByScope[s] = i;
  574. }
  575. break;
  576. }
  577. } else break;
  578. }
  579. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  580. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  581. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  582. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  583. mine = myBestV6ByScope[s];
  584. theirs = theirBestV6ByScope[s];
  585. break;
  586. }
  587. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  588. mine = myBestV4ByScope[s];
  589. theirs = theirBestV4ByScope[s];
  590. break;
  591. }
  592. }
  593. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  594. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  595. const unsigned int completed = alt + 2;
  596. while (alt != completed) {
  597. if ((alt & 1) == 0) {
  598. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  599. outp.append((uint8_t)0);
  600. other->_id.address().appendTo(outp);
  601. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  602. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  603. outp.append((uint8_t)16);
  604. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  605. } else {
  606. outp.append((uint8_t)4);
  607. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  608. }
  609. outp.armor(_key,true);
  610. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  611. } else {
  612. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  613. outp.append((uint8_t)0);
  614. _id.address().appendTo(outp);
  615. outp.append((uint16_t)_paths[mine].p->address().port());
  616. if (_paths[mine].p->address().ss_family == AF_INET6) {
  617. outp.append((uint8_t)16);
  618. outp.append(_paths[mine].p->address().rawIpData(),16);
  619. } else {
  620. outp.append((uint8_t)4);
  621. outp.append(_paths[mine].p->address().rawIpData(),4);
  622. }
  623. outp.armor(other->_key,true);
  624. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  625. }
  626. ++alt;
  627. }
  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. // Emit traces regarding aggregate link status
  720. if (canUseMultipath()) {
  721. int alivePathCount = aggregateLinkPhysicalPathCount();
  722. if ((now - _lastAggregateStatsReport) > ZT_PATH_AGGREGATE_STATS_REPORT_INTERVAL) {
  723. _lastAggregateStatsReport = now;
  724. if (alivePathCount) {
  725. RR->t->peerLinkAggregateStatistics(NULL,*this);
  726. }
  727. } if (alivePathCount < 2 && _linkIsRedundant) {
  728. _linkIsRedundant = !_linkIsRedundant;
  729. RR->t->peerLinkNoLongerRedundant(NULL,*this);
  730. } if (alivePathCount > 1 && !_linkIsRedundant) {
  731. _linkIsRedundant = !_linkIsRedundant;
  732. RR->t->peerLinkNowRedundant(NULL,*this);
  733. }
  734. }
  735. // Right now we only keep pinging links that have the maximum priority. The
  736. // priority is used to track cluster redirections, meaning that when a cluster
  737. // redirects us its redirect target links override all other links and we
  738. // let those old links expire.
  739. long maxPriority = 0;
  740. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  741. if (_paths[i].p)
  742. maxPriority = std::max(_paths[i].priority,maxPriority);
  743. else break;
  744. }
  745. unsigned int j = 0;
  746. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  747. if (_paths[i].p) {
  748. // Clean expired and reduced priority paths
  749. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  750. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))) {
  751. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  752. _paths[i].p->sent(now);
  753. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  754. }
  755. if (i != j)
  756. _paths[j] = _paths[i];
  757. ++j;
  758. }
  759. } else break;
  760. }
  761. if (canUseMultipath()) {
  762. while(j < ZT_MAX_PEER_NETWORK_PATHS) {
  763. _paths[j].lr = 0;
  764. _paths[j].p.zero();
  765. _paths[j].priority = 1;
  766. ++j;
  767. }
  768. }
  769. return sent;
  770. }
  771. void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
  772. {
  773. SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
  774. RR->t->peerRedirected(tPtr,0,*this,np);
  775. attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
  776. {
  777. Mutex::Lock _l(_paths_m);
  778. // New priority is higher than the priority of the originating path (if known)
  779. long newPriority = 1;
  780. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  781. if (_paths[i].p) {
  782. if (_paths[i].p == originatingPath) {
  783. newPriority = _paths[i].priority;
  784. break;
  785. }
  786. } else break;
  787. }
  788. newPriority += 2;
  789. // Erase any paths with lower priority than this one or that are duplicate
  790. // IPs and add this path.
  791. unsigned int j = 0;
  792. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  793. if (_paths[i].p) {
  794. if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
  795. if (i != j)
  796. _paths[j] = _paths[i];
  797. ++j;
  798. }
  799. }
  800. }
  801. if (j < ZT_MAX_PEER_NETWORK_PATHS) {
  802. _paths[j].lr = now;
  803. _paths[j].p = np;
  804. _paths[j].priority = newPriority;
  805. ++j;
  806. while (j < ZT_MAX_PEER_NETWORK_PATHS) {
  807. _paths[j].lr = 0;
  808. _paths[j].p.zero();
  809. _paths[j].priority = 1;
  810. ++j;
  811. }
  812. }
  813. }
  814. }
  815. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  816. {
  817. Mutex::Lock _l(_paths_m);
  818. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  819. if (_paths[i].p) {
  820. if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
  821. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
  822. _paths[i].p->sent(now);
  823. _paths[i].lr = 0; // path will not be used unless it speaks again
  824. }
  825. } else break;
  826. }
  827. }
  828. } // namespace ZeroTier