Peer.cpp 29 KB

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