Peer.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "Constants.hpp"
  14. #include "Peer.hpp"
  15. #include "Node.hpp"
  16. #include "Switch.hpp"
  17. #include "Network.hpp"
  18. #include "SelfAwareness.hpp"
  19. #include "Packet.hpp"
  20. #include "Trace.hpp"
  21. #include "InetAddress.hpp"
  22. #include "RingBuffer.hpp"
  23. #include "Utils.hpp"
  24. #include "ScopedPtr.hpp"
  25. namespace ZeroTier {
  26. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  27. RR(renv),
  28. _lastReceive(0),
  29. _lastDirectPathPushSent(0),
  30. _lastDirectPathPushReceive(0),
  31. _lastCredentialRequestSent(0),
  32. _lastWhoisRequestReceived(0),
  33. _lastEchoRequestReceived(0),
  34. _lastCredentialsReceived(0),
  35. _lastACKWindowReset(0),
  36. _lastQoSWindowReset(0),
  37. _lastMultipathCompatibilityCheck(0),
  38. _lastTriedStaticPath(0),
  39. _uniqueAlivePathCount(0),
  40. _localMultipathSupported(false),
  41. _remoteMultipathSupported(false),
  42. _canUseMultipath(false),
  43. _freeRandomByte((uint8_t)Utils::random()),
  44. _vProto(0),
  45. _vMajor(0),
  46. _vMinor(0),
  47. _vRevision(0),
  48. _id(peerIdentity),
  49. _directPathPushCutoffCount(0),
  50. _credentialsCutoffCount(0),
  51. _linkIsBalanced(false),
  52. _linkIsRedundant(false),
  53. _remotePeerMultipathEnabled(false),
  54. _lastAggregateStatsReport(0),
  55. _lastAggregateAllocation(0)
  56. {
  57. if (!myIdentity.agree(peerIdentity,_key))
  58. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  59. }
  60. void Peer::received(
  61. void *tPtr,
  62. const SharedPtr<Path> &path,
  63. const unsigned int hops,
  64. const uint64_t packetId,
  65. const unsigned int payloadLength,
  66. const Packet::Verb verb,
  67. const uint64_t inRePacketId,
  68. const Packet::Verb inReVerb,
  69. const uint64_t networkId)
  70. {
  71. const int64_t now = RR->node->now();
  72. _lastReceive = now;
  73. {
  74. Mutex::Lock _l(_paths_m);
  75. recordIncomingPacket(tPtr, path, packetId, payloadLength, verb, now);
  76. if (_canUseMultipath) {
  77. if (path->needsToSendQoS(now)) {
  78. sendQOS_MEASUREMENT(tPtr, path, path->localSocket(), path->address(), now);
  79. }
  80. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  81. if (_paths[i]) {
  82. _paths[i]->processBackgroundPathMeasurements(now);
  83. }
  84. }
  85. }
  86. }
  87. if (hops == 0) {
  88. // If this is a direct packet (no hops), update existing paths or learn new ones
  89. bool havePath = false;
  90. {
  91. Mutex::Lock _l(_paths_m);
  92. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  93. if (_paths[i]) {
  94. if (_paths[i] == path) {
  95. havePath = true;
  96. break;
  97. }
  98. } else break;
  99. }
  100. }
  101. bool attemptToContact = false;
  102. if ((!havePath)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()))) {
  103. Mutex::Lock _l(_paths_m);
  104. // Paths are redundant if they duplicate an alive path to the same IP or
  105. // with the same local socket and address family.
  106. bool redundant = false;
  107. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  108. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  109. if (_paths[i]) {
  110. if ( (_paths[i]->alive(now)) && ( ((_paths[i]->localSocket() == path->localSocket())&&(_paths[i]->address().ss_family == path->address().ss_family)) || (_paths[i]->address().ipsEqual2(path->address())) ) ) {
  111. redundant = true;
  112. break;
  113. }
  114. // If the path is the same address and port, simply assume this is a replacement
  115. if ( (_paths[i]->address().ipsEqual2(path->address()))) {
  116. replacePath = i;
  117. break;
  118. }
  119. } else break;
  120. }
  121. // If the path isn't a duplicate of the same localSocket AND we haven't already determined a replacePath,
  122. // then find the worst path and replace it.
  123. if (!redundant && replacePath == ZT_MAX_PEER_NETWORK_PATHS) {
  124. int replacePathQuality = 0;
  125. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  126. if (_paths[i]) {
  127. const int q = _paths[i]->quality(now);
  128. if (q > replacePathQuality) {
  129. replacePathQuality = q;
  130. replacePath = i;
  131. }
  132. } else {
  133. replacePath = i;
  134. break;
  135. }
  136. }
  137. }
  138. if (replacePath != ZT_MAX_PEER_NETWORK_PATHS) {
  139. if (verb == Packet::VERB_OK) {
  140. RR->t->peerLearnedNewPath(tPtr,networkId,*this,path,packetId);
  141. _paths[replacePath] = path;
  142. } else {
  143. attemptToContact = true;
  144. }
  145. }
  146. }
  147. if (attemptToContact) {
  148. sendHELLO(tPtr,path->localSocket(),path->address(),now);
  149. path->sent(now);
  150. RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
  151. }
  152. }
  153. // Periodically push direct paths to the peer, doing so more often if we do not
  154. // currently have a direct path.
  155. const int64_t sinceLastPush = now - _lastDirectPathPushSent;
  156. if (sinceLastPush >= ((hops == 0) ? ZT_DIRECT_PATH_PUSH_INTERVAL_HAVEPATH : ZT_DIRECT_PATH_PUSH_INTERVAL)) {
  157. _lastDirectPathPushSent = now;
  158. std::vector<ZT_InterfaceAddress> pathsToPush(RR->node->directPaths());
  159. if (pathsToPush.size() > 0) {
  160. std::vector<ZT_InterfaceAddress>::const_iterator p(pathsToPush.begin());
  161. while (p != pathsToPush.end()) {
  162. ScopedPtr<Packet> outp(new Packet(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS));
  163. outp->addSize(2); // leave room for count
  164. unsigned int count = 0;
  165. while ((p != pathsToPush.end())&&((outp->size() + 24) < 1200)) {
  166. uint8_t addressType = 4;
  167. uint8_t addressLength = 6;
  168. unsigned int ipLength = 4;
  169. const void *rawIpData;
  170. const void *rawIpPort;
  171. switch(p->address.ss_family) {
  172. case AF_INET:
  173. rawIpData = &(reinterpret_cast<const struct sockaddr_in *>(&(p->address))->sin_addr.s_addr);
  174. rawIpPort = &(reinterpret_cast<const struct sockaddr_in *>(&(p->address))->sin_port);
  175. break;
  176. case AF_INET6:
  177. rawIpData = reinterpret_cast<const struct sockaddr_in6 *>(&(p->address))->sin6_addr.s6_addr;
  178. rawIpPort = &(reinterpret_cast<const struct sockaddr_in6 *>(&(p->address))->sin6_port);
  179. addressType = 6;
  180. addressLength = 18;
  181. ipLength = 16;
  182. break;
  183. default: // we currently only push IP addresses
  184. ++p;
  185. continue;
  186. }
  187. outp->append((uint8_t)0); // no flags
  188. outp->append((uint16_t)0); // no extensions
  189. outp->append(addressType);
  190. outp->append(addressLength);
  191. outp->append(rawIpData,ipLength);
  192. outp->append(rawIpPort,2);
  193. ++count;
  194. ++p;
  195. }
  196. if (count) {
  197. outp->setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  198. outp->compress();
  199. outp->armor(_key,true);
  200. path->send(RR,tPtr,outp->data(),outp->size(),now);
  201. }
  202. }
  203. }
  204. }
  205. }
  206. void Peer::recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  207. uint16_t payloadLength, const Packet::Verb verb, int64_t now)
  208. {
  209. _freeRandomByte += (unsigned char)(packetId >> 8); // grab entropy to use in path selection logic for multipath
  210. if (_canUseMultipath) {
  211. path->recordOutgoingPacket(now, packetId, payloadLength, verb);
  212. }
  213. }
  214. void Peer::recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId,
  215. uint16_t payloadLength, const Packet::Verb verb, int64_t now)
  216. {
  217. if (_canUseMultipath) {
  218. if (path->needsToSendAck(now)) {
  219. sendACK(tPtr, path, path->localSocket(), path->address(), now);
  220. }
  221. path->recordIncomingPacket(now, packetId, payloadLength, verb);
  222. }
  223. }
  224. void Peer::computeAggregateProportionalAllocation(int64_t now)
  225. {
  226. float maxStability = 0;
  227. float totalRelativeQuality = 0;
  228. float maxThroughput = 1;
  229. float maxScope = 0;
  230. float relStability[ZT_MAX_PEER_NETWORK_PATHS];
  231. float relThroughput[ZT_MAX_PEER_NETWORK_PATHS];
  232. memset(&relStability, 0, sizeof(relStability));
  233. memset(&relThroughput, 0, sizeof(relThroughput));
  234. // Survey all paths
  235. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  236. if (_paths[i]) {
  237. relStability[i] = _paths[i]->lastComputedStability();
  238. relThroughput[i] = (float)_paths[i]->maxLifetimeThroughput();
  239. maxStability = relStability[i] > maxStability ? relStability[i] : maxStability;
  240. maxThroughput = relThroughput[i] > maxThroughput ? relThroughput[i] : maxThroughput;
  241. maxScope = _paths[i]->ipScope() > maxScope ? _paths[i]->ipScope() : maxScope;
  242. }
  243. }
  244. // Convert to relative values
  245. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  246. if (_paths[i]) {
  247. relStability[i] /= maxStability ? maxStability : 1;
  248. relThroughput[i] /= maxThroughput ? maxThroughput : 1;
  249. float normalized_ma = Utils::normalize((float)_paths[i]->ackAge(now), 0, ZT_PATH_MAX_AGE, 0, 10);
  250. float age_contrib = exp((-1)*normalized_ma);
  251. float relScope = ((float)(_paths[i]->ipScope()+1) / (maxScope + 1));
  252. float relQuality =
  253. (relStability[i] * (float)ZT_PATH_CONTRIB_STABILITY)
  254. + (fmaxf(1.0f, relThroughput[i]) * (float)ZT_PATH_CONTRIB_THROUGHPUT)
  255. + relScope * (float)ZT_PATH_CONTRIB_SCOPE;
  256. relQuality *= age_contrib;
  257. // Arbitrary cutoffs
  258. relQuality = relQuality > (1.00f / 100.0f) ? relQuality : 0.0f;
  259. relQuality = relQuality < (99.0f / 100.0f) ? relQuality : 1.0f;
  260. totalRelativeQuality += relQuality;
  261. _paths[i]->updateRelativeQuality(relQuality);
  262. }
  263. }
  264. // Convert set of relative performances into an allocation set
  265. for(uint16_t i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  266. if (_paths[i]) {
  267. _paths[i]->updateComponentAllocationOfAggregateLink((unsigned char)((_paths[i]->relativeQuality() / totalRelativeQuality) * 255));
  268. }
  269. }
  270. }
  271. int Peer::computeAggregateLinkPacketDelayVariance()
  272. {
  273. float pdv = 0.0;
  274. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  275. if (_paths[i]) {
  276. pdv += _paths[i]->relativeQuality() * _paths[i]->packetDelayVariance();
  277. }
  278. }
  279. return (int)pdv;
  280. }
  281. int Peer::computeAggregateLinkMeanLatency()
  282. {
  283. int ml = 0;
  284. int pathCount = 0;
  285. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  286. if (_paths[i]) {
  287. pathCount++;
  288. ml += (int)(_paths[i]->relativeQuality() * _paths[i]->meanLatency());
  289. }
  290. }
  291. return ml / pathCount;
  292. }
  293. int Peer::aggregateLinkPhysicalPathCount()
  294. {
  295. std::map<std::string, bool> ifnamemap;
  296. int pathCount = 0;
  297. int64_t now = RR->node->now();
  298. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  299. if (_paths[i] && _paths[i]->alive(now)) {
  300. if (!ifnamemap[_paths[i]->getName()]) {
  301. ifnamemap[_paths[i]->getName()] = true;
  302. pathCount++;
  303. }
  304. }
  305. }
  306. return pathCount;
  307. }
  308. int Peer::aggregateLinkLogicalPathCount()
  309. {
  310. int pathCount = 0;
  311. int64_t now = RR->node->now();
  312. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  313. if (_paths[i] && _paths[i]->alive(now)) {
  314. pathCount++;
  315. }
  316. }
  317. return pathCount;
  318. }
  319. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired)
  320. {
  321. Mutex::Lock _l(_paths_m);
  322. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  323. /**
  324. * Send traffic across the highest quality path only. This algorithm will still
  325. * use the old path quality metric from protocol version 9.
  326. */
  327. if (!_canUseMultipath) {
  328. long bestPathQuality = 2147483647;
  329. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  330. if (_paths[i]) {
  331. if ((includeExpired)||(_paths[i]->alive(now))) {
  332. const long q = _paths[i]->quality(now);
  333. if (q <= bestPathQuality) {
  334. bestPathQuality = q;
  335. bestPath = i;
  336. }
  337. }
  338. } else break;
  339. }
  340. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  341. return _paths[bestPath];
  342. }
  343. return SharedPtr<Path>();
  344. }
  345. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  346. if (_paths[i]) {
  347. _paths[i]->processBackgroundPathMeasurements(now);
  348. }
  349. }
  350. /**
  351. * Randomly distribute traffic across all paths
  352. */
  353. int numAlivePaths = 0;
  354. int numStalePaths = 0;
  355. if (RR->node->getMultipathMode() == ZT_MULTIPATH_RANDOM) {
  356. int alivePaths[ZT_MAX_PEER_NETWORK_PATHS];
  357. int stalePaths[ZT_MAX_PEER_NETWORK_PATHS];
  358. memset(&alivePaths, -1, sizeof(alivePaths));
  359. memset(&stalePaths, -1, sizeof(stalePaths));
  360. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  361. if (_paths[i]) {
  362. if (_paths[i]->alive(now)) {
  363. alivePaths[numAlivePaths] = i;
  364. numAlivePaths++;
  365. }
  366. else {
  367. stalePaths[numStalePaths] = i;
  368. numStalePaths++;
  369. }
  370. }
  371. }
  372. unsigned int r = _freeRandomByte;
  373. if (numAlivePaths > 0) {
  374. int rf = r % numAlivePaths;
  375. return _paths[alivePaths[rf]];
  376. }
  377. else if(numStalePaths > 0) {
  378. // Resort to trying any non-expired path
  379. int rf = r % numStalePaths;
  380. return _paths[stalePaths[rf]];
  381. }
  382. }
  383. /**
  384. * Proportionally allocate traffic according to dynamic path quality measurements
  385. */
  386. if (RR->node->getMultipathMode() == ZT_MULTIPATH_PROPORTIONALLY_BALANCED) {
  387. if ((now - _lastAggregateAllocation) >= ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
  388. _lastAggregateAllocation = now;
  389. computeAggregateProportionalAllocation(now);
  390. }
  391. // Randomly choose path according to their allocations
  392. float rf = _freeRandomByte;
  393. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  394. if (_paths[i]) {
  395. if (rf < _paths[i]->allocation()) {
  396. bestPath = i;
  397. _pathChoiceHist.push(bestPath); // Record which path we chose
  398. break;
  399. }
  400. rf -= _paths[i]->allocation();
  401. }
  402. }
  403. if (bestPath < ZT_MAX_PEER_NETWORK_PATHS) {
  404. return _paths[bestPath];
  405. }
  406. }
  407. return SharedPtr<Path>();
  408. }
  409. char *Peer::interfaceListStr()
  410. {
  411. std::map<std::string, int> ifnamemap;
  412. char tmp[32];
  413. const int64_t now = RR->node->now();
  414. char *ptr = _interfaceListStr;
  415. bool imbalanced = false;
  416. memset(_interfaceListStr, 0, sizeof(_interfaceListStr));
  417. int alivePathCount = aggregateLinkLogicalPathCount();
  418. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  419. if (_paths[i] && _paths[i]->alive(now)) {
  420. int ipv = _paths[i]->address().isV4();
  421. // If this is acting as an aggregate link, check allocations
  422. float targetAllocation = 1.0f / (float)alivePathCount;
  423. float currentAllocation = 1.0f;
  424. if (alivePathCount > 1) {
  425. currentAllocation = (float)_pathChoiceHist.countValue(i) / (float)_pathChoiceHist.count();
  426. if (fabs(targetAllocation - currentAllocation) > ZT_PATH_IMBALANCE_THRESHOLD) {
  427. imbalanced = true;
  428. }
  429. }
  430. char *ipvStr = ipv ? (char*)"ipv4" : (char*)"ipv6";
  431. sprintf(tmp, "(%s, %s, %.3f)", _paths[i]->getName(), ipvStr, currentAllocation);
  432. // Prevent duplicates
  433. if(ifnamemap[_paths[i]->getName()] != ipv) {
  434. memcpy(ptr, tmp, strlen(tmp));
  435. ptr += strlen(tmp);
  436. *ptr = ' ';
  437. ptr++;
  438. ifnamemap[_paths[i]->getName()] = ipv;
  439. }
  440. }
  441. }
  442. ptr--; // Overwrite trailing space
  443. if (imbalanced) {
  444. sprintf(tmp, ", is asymmetrical");
  445. memcpy(ptr, tmp, sizeof(tmp));
  446. } else {
  447. *ptr = '\0';
  448. }
  449. return _interfaceListStr;
  450. }
  451. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  452. {
  453. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  454. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  455. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  456. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  457. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  458. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  459. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  460. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  461. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  462. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  463. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  464. myBestV4QualityByScope[i] = 2147483647;
  465. myBestV6QualityByScope[i] = 2147483647;
  466. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  467. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  468. theirBestV4QualityByScope[i] = 2147483647;
  469. theirBestV6QualityByScope[i] = 2147483647;
  470. }
  471. Mutex::Lock _l1(_paths_m);
  472. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  473. if (_paths[i]) {
  474. const long q = _paths[i]->quality(now);
  475. const unsigned int s = (unsigned int)_paths[i]->ipScope();
  476. switch(_paths[i]->address().ss_family) {
  477. case AF_INET:
  478. if (q <= myBestV4QualityByScope[s]) {
  479. myBestV4QualityByScope[s] = q;
  480. myBestV4ByScope[s] = i;
  481. }
  482. break;
  483. case AF_INET6:
  484. if (q <= myBestV6QualityByScope[s]) {
  485. myBestV6QualityByScope[s] = q;
  486. myBestV6ByScope[s] = i;
  487. }
  488. break;
  489. }
  490. } else break;
  491. }
  492. Mutex::Lock _l2(other->_paths_m);
  493. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  494. if (other->_paths[i]) {
  495. const long q = other->_paths[i]->quality(now);
  496. const unsigned int s = (unsigned int)other->_paths[i]->ipScope();
  497. switch(other->_paths[i]->address().ss_family) {
  498. case AF_INET:
  499. if (q <= theirBestV4QualityByScope[s]) {
  500. theirBestV4QualityByScope[s] = q;
  501. theirBestV4ByScope[s] = i;
  502. }
  503. break;
  504. case AF_INET6:
  505. if (q <= theirBestV6QualityByScope[s]) {
  506. theirBestV6QualityByScope[s] = q;
  507. theirBestV6ByScope[s] = i;
  508. }
  509. break;
  510. }
  511. } else break;
  512. }
  513. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  514. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  515. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  516. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  517. mine = myBestV6ByScope[s];
  518. theirs = theirBestV6ByScope[s];
  519. break;
  520. }
  521. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  522. mine = myBestV4ByScope[s];
  523. theirs = theirBestV4ByScope[s];
  524. break;
  525. }
  526. }
  527. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  528. unsigned int alt = (unsigned int)Utils::random() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  529. const unsigned int completed = alt + 2;
  530. while (alt != completed) {
  531. if ((alt & 1) == 0) {
  532. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  533. outp.append((uint8_t)0);
  534. other->_id.address().appendTo(outp);
  535. outp.append((uint16_t)other->_paths[theirs]->address().port());
  536. if (other->_paths[theirs]->address().ss_family == AF_INET6) {
  537. outp.append((uint8_t)16);
  538. outp.append(other->_paths[theirs]->address().rawIpData(),16);
  539. } else {
  540. outp.append((uint8_t)4);
  541. outp.append(other->_paths[theirs]->address().rawIpData(),4);
  542. }
  543. outp.armor(_key,true);
  544. _paths[mine]->send(RR,tPtr,outp.data(),outp.size(),now);
  545. } else {
  546. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  547. outp.append((uint8_t)0);
  548. _id.address().appendTo(outp);
  549. outp.append((uint16_t)_paths[mine]->address().port());
  550. if (_paths[mine]->address().ss_family == AF_INET6) {
  551. outp.append((uint8_t)16);
  552. outp.append(_paths[mine]->address().rawIpData(),16);
  553. } else {
  554. outp.append((uint8_t)4);
  555. outp.append(_paths[mine]->address().rawIpData(),4);
  556. }
  557. outp.armor(other->_key,true);
  558. other->_paths[theirs]->send(RR,tPtr,outp.data(),outp.size(),now);
  559. }
  560. ++alt;
  561. }
  562. }
  563. }
  564. inline void Peer::processBackgroundPeerTasks(const int64_t now)
  565. {
  566. // Determine current multipath compatibility with other peer
  567. if ((now - _lastMultipathCompatibilityCheck) >= ZT_PATH_QUALITY_COMPUTE_INTERVAL) {
  568. //
  569. // Cache number of available paths so that we can short-circuit multipath logic elsewhere
  570. //
  571. // We also take notice of duplicate paths (same IP only) because we may have
  572. // recently received a direct path push from a peer and our list might contain
  573. // a dead path which hasn't been fully recognized as such. In this case we
  574. // don't want the duplicate to trigger execution of multipath code prematurely.
  575. //
  576. // This is done to support the behavior of auto multipath enable/disable
  577. // without user intervention.
  578. //
  579. int currAlivePathCount = 0;
  580. int duplicatePathsFound = 0;
  581. for (unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  582. if (_paths[i]) {
  583. currAlivePathCount++;
  584. for (unsigned int j=0;j<ZT_MAX_PEER_NETWORK_PATHS;++j) {
  585. if (_paths[i] && _paths[j] && _paths[i]->address().ipsEqual2(_paths[j]->address()) && i != j) {
  586. duplicatePathsFound+=1;
  587. break;
  588. }
  589. }
  590. }
  591. }
  592. _uniqueAlivePathCount = (currAlivePathCount - (duplicatePathsFound / 2));
  593. _lastMultipathCompatibilityCheck = now;
  594. _localMultipathSupported = ((RR->node->getMultipathMode() != ZT_MULTIPATH_NONE) && (ZT_PROTO_VERSION > 9));
  595. _remoteMultipathSupported = _vProto > 9;
  596. // If both peers support multipath and more than one path exist, we can use multipath logic
  597. _canUseMultipath = _localMultipathSupported && _remoteMultipathSupported && (_uniqueAlivePathCount > 1);
  598. }
  599. }
  600. void Peer::sendACK(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  601. {
  602. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ACK);
  603. uint32_t bytesToAck = path->bytesToAck();
  604. outp.append<uint32_t>(bytesToAck);
  605. if (atAddress) {
  606. outp.armor(_key,false);
  607. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  608. } else {
  609. RR->sw->send(tPtr,outp,false);
  610. }
  611. path->sentAck(now);
  612. }
  613. void Peer::sendQOS_MEASUREMENT(void *tPtr,const SharedPtr<Path> &path,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  614. {
  615. const int64_t _now = RR->node->now();
  616. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_QOS_MEASUREMENT);
  617. char qosData[ZT_PATH_MAX_QOS_PACKET_SZ];
  618. int16_t len = path->generateQoSPacket(_now,qosData);
  619. outp.append(qosData,len);
  620. if (atAddress) {
  621. outp.armor(_key,false);
  622. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  623. } else {
  624. RR->sw->send(tPtr,outp,false);
  625. }
  626. path->sentQoS(now);
  627. }
  628. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  629. {
  630. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  631. outp.append((unsigned char)ZT_PROTO_VERSION);
  632. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  633. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  634. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  635. outp.append(now);
  636. RR->identity.serialize(outp,false);
  637. atAddress.serialize(outp);
  638. RR->node->expectReplyTo(outp.packetId());
  639. if (atAddress) {
  640. outp.armor(_key,false); // false == don't encrypt full payload, but add MAC
  641. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  642. } else {
  643. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  644. }
  645. }
  646. void Peer::ping(void *tPtr,int64_t now,unsigned int &v4SendCount,unsigned int &v6SendCount)
  647. {
  648. v4SendCount = 0;
  649. v6SendCount = 0;
  650. Mutex::Lock _l(_paths_m);
  651. // Emit traces regarding aggregate link status
  652. if (_canUseMultipath) {
  653. int alivePathCount = aggregateLinkPhysicalPathCount();
  654. if ((now - _lastAggregateStatsReport) > ZT_PATH_AGGREGATE_STATS_REPORT_INTERVAL) {
  655. _lastAggregateStatsReport = now;
  656. if (alivePathCount) {
  657. RR->t->peerLinkAggregateStatistics(NULL,*this);
  658. }
  659. } if (alivePathCount < 2 && _linkIsRedundant) {
  660. _linkIsRedundant = !_linkIsRedundant;
  661. RR->t->peerLinkNoLongerRedundant(NULL,*this);
  662. } if (alivePathCount > 1 && !_linkIsRedundant) {
  663. _linkIsRedundant = !_linkIsRedundant;
  664. RR->t->peerLinkNowRedundant(NULL,*this);
  665. }
  666. }
  667. unsigned int j = 0;
  668. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  669. if ((_paths[i])&&(_paths[i]->alive(now))) {
  670. sendHELLO(tPtr,_paths[i]->localSocket(),_paths[i]->address(),now);
  671. _paths[i]->sent(now);
  672. if (_paths[i]->address().isV4())
  673. ++v4SendCount;
  674. else if (_paths[i]->address().isV6())
  675. ++v6SendCount;
  676. if (i != j)
  677. _paths[j] = _paths[i];
  678. ++j;
  679. }
  680. }
  681. while(j < ZT_MAX_PEER_NETWORK_PATHS) {
  682. _paths[j].zero();
  683. ++j;
  684. }
  685. }
  686. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  687. {
  688. Mutex::Lock _l(_paths_m);
  689. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  690. if (_paths[i]) {
  691. if ((_paths[i]->address().ss_family == inetAddressFamily)&&(_paths[i]->ipScope() == scope)) {
  692. sendHELLO(tPtr,_paths[i]->localSocket(),_paths[i]->address(),now);
  693. _paths[i]->sent(now);
  694. }
  695. } else break;
  696. }
  697. }
  698. } // namespace ZeroTier