Peer.cpp 29 KB

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