Peer.cpp 28 KB

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