Peer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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. namespace ZeroTier {
  38. Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity) :
  39. RR(renv),
  40. _lastReceive(0),
  41. _lastNontrivialReceive(0),
  42. _lastTriedMemorizedPath(0),
  43. _lastDirectPathPushSent(0),
  44. _lastDirectPathPushReceive(0),
  45. _lastCredentialRequestSent(0),
  46. _lastWhoisRequestReceived(0),
  47. _lastEchoRequestReceived(0),
  48. _lastComRequestReceived(0),
  49. _lastComRequestSent(0),
  50. _lastCredentialsReceived(0),
  51. _lastTrustEstablishedPacketReceived(0),
  52. _lastSentFullHello(0),
  53. _vProto(0),
  54. _vMajor(0),
  55. _vMinor(0),
  56. _vRevision(0),
  57. _id(peerIdentity),
  58. _directPathPushCutoffCount(0),
  59. _credentialsCutoffCount(0),
  60. _linkBalanceStatus(false),
  61. _linkRedundancyStatus(false)
  62. {
  63. if (!myIdentity.agree(peerIdentity,_key,ZT_PEER_SECRET_KEY_LENGTH))
  64. throw ZT_EXCEPTION_INVALID_ARGUMENT;
  65. _pathChoiceHist = new RingBuffer<int>(ZT_MULTIPATH_PROPORTION_WIN_SZ);
  66. _flowBalanceHist = new RingBuffer<float>(ZT_MULTIPATH_PROPORTION_WIN_SZ);
  67. }
  68. void Peer::received(
  69. void *tPtr,
  70. const SharedPtr<Path> &path,
  71. const unsigned int hops,
  72. const uint64_t packetId,
  73. const Packet::Verb verb,
  74. const uint64_t inRePacketId,
  75. const Packet::Verb inReVerb,
  76. const bool trustEstablished,
  77. const uint64_t networkId)
  78. {
  79. const int64_t now = RR->node->now();
  80. _lastReceive = now;
  81. switch (verb) {
  82. case Packet::VERB_FRAME:
  83. case Packet::VERB_EXT_FRAME:
  84. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  85. case Packet::VERB_NETWORK_CONFIG:
  86. case Packet::VERB_MULTICAST_FRAME:
  87. _lastNontrivialReceive = now;
  88. break;
  89. default: break;
  90. }
  91. if (trustEstablished) {
  92. _lastTrustEstablishedPacketReceived = now;
  93. path->trustedPacketReceived(now);
  94. }
  95. if (RR->node->getMultipathMode() != ZT_MULTIPATH_NONE) {
  96. if ((now - _lastPathPrune) > ZT_CLOSED_PATH_PRUNING_INTERVAL) {
  97. _lastPathPrune = now;
  98. prunePaths();
  99. }
  100. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  101. if (_paths[i].p) {
  102. _paths[i].p->measureLink(now);
  103. }
  104. }
  105. }
  106. if (hops == 0) {
  107. // If this is a direct packet (no hops), update existing paths or learn new ones
  108. bool havePath = false;
  109. {
  110. Mutex::Lock _l(_paths_m);
  111. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  112. if (_paths[i].p) {
  113. if (_paths[i].p == path) {
  114. _paths[i].lr = now;
  115. havePath = true;
  116. break;
  117. }
  118. } else break;
  119. }
  120. }
  121. bool attemptToContact = false;
  122. if ((!havePath)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr,_id.address(),path->localSocket(),path->address()))) {
  123. Mutex::Lock _l(_paths_m);
  124. // Paths are redunant if they duplicate an alive path to the same IP or
  125. // with the same local socket and address family.
  126. bool redundant = false;
  127. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  128. if (_paths[i].p) {
  129. 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())) ) ) {
  130. redundant = true;
  131. break;
  132. }
  133. } else break;
  134. }
  135. if (!redundant) {
  136. unsigned int replacePath = ZT_MAX_PEER_NETWORK_PATHS;
  137. int replacePathQuality = 0;
  138. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  139. if (_paths[i].p) {
  140. const int q = _paths[i].p->quality(now);
  141. if (q > replacePathQuality) {
  142. replacePathQuality = q;
  143. replacePath = i;
  144. }
  145. } else {
  146. replacePath = i;
  147. break;
  148. }
  149. }
  150. if (replacePath != ZT_MAX_PEER_NETWORK_PATHS) {
  151. if (verb == Packet::VERB_OK) {
  152. RR->t->peerLearnedNewPath(tPtr,networkId,*this,path,packetId);
  153. _paths[replacePath].lr = now;
  154. _paths[replacePath].p = path;
  155. _paths[replacePath].priority = 1;
  156. } else {
  157. attemptToContact = true;
  158. }
  159. }
  160. }
  161. }
  162. if (attemptToContact) {
  163. attemptToContactAt(tPtr,path->localSocket(),path->address(),now,true);
  164. path->sent(now);
  165. RR->t->peerConfirmingUnknownPath(tPtr,networkId,*this,path,packetId,verb);
  166. }
  167. }
  168. // If we have a trust relationship periodically push a message enumerating
  169. // all known external addresses for ourselves. We now do this even if we
  170. // have a current path since we'll want to use new ones too.
  171. if (this->trustEstablished(now)) {
  172. if ((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  173. _lastDirectPathPushSent = now;
  174. std::vector<InetAddress> pathsToPush;
  175. std::vector<InetAddress> dps(RR->node->directPaths());
  176. for(std::vector<InetAddress>::const_iterator i(dps.begin());i!=dps.end();++i)
  177. pathsToPush.push_back(*i);
  178. // Do symmetric NAT prediction if we are communicating indirectly.
  179. if (hops > 0) {
  180. std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
  181. for(unsigned long i=0,added=0;i<sym.size();++i) {
  182. InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
  183. if (std::find(pathsToPush.begin(),pathsToPush.end(),tmp) == pathsToPush.end()) {
  184. pathsToPush.push_back(tmp);
  185. if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  186. break;
  187. }
  188. }
  189. }
  190. if (pathsToPush.size() > 0) {
  191. std::vector<InetAddress>::const_iterator p(pathsToPush.begin());
  192. while (p != pathsToPush.end()) {
  193. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
  194. outp.addSize(2); // leave room for count
  195. unsigned int count = 0;
  196. while ((p != pathsToPush.end())&&((outp.size() + 24) < 1200)) {
  197. uint8_t addressType = 4;
  198. switch(p->ss_family) {
  199. case AF_INET:
  200. break;
  201. case AF_INET6:
  202. addressType = 6;
  203. break;
  204. default: // we currently only push IP addresses
  205. ++p;
  206. continue;
  207. }
  208. outp.append((uint8_t)0); // no flags
  209. outp.append((uint16_t)0); // no extensions
  210. outp.append(addressType);
  211. outp.append((uint8_t)((addressType == 4) ? 6 : 18));
  212. outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
  213. outp.append((uint16_t)p->port());
  214. ++count;
  215. ++p;
  216. }
  217. if (count) {
  218. outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
  219. outp.armor(_key,true);
  220. path->send(RR,tPtr,outp.data(),outp.size(),now);
  221. }
  222. }
  223. }
  224. }
  225. }
  226. }
  227. SharedPtr<Path> Peer::getAppropriatePath(int64_t now, bool includeExpired)
  228. {
  229. Mutex::Lock _l(_paths_m);
  230. unsigned int bestPath = ZT_MAX_PEER_NETWORK_PATHS;
  231. /**
  232. * Send traffic across the highest quality path only. This algorithm will still
  233. * use the old path quality metric.
  234. */
  235. if (RR->node->getMultipathMode() == ZT_MULTIPATH_NONE) {
  236. long bestPathQuality = 2147483647;
  237. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  238. if (_paths[i].p && _paths[i].p->isValidState()) {
  239. if ((includeExpired)||((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)) {
  240. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  241. if (q <= bestPathQuality) {
  242. bestPathQuality = q;
  243. bestPath = i;
  244. }
  245. }
  246. } else break;
  247. }
  248. if (bestPath != ZT_MAX_PEER_NETWORK_PATHS) {
  249. return _paths[bestPath].p;
  250. }
  251. return SharedPtr<Path>();
  252. }
  253. if ((now - _lastPathPrune) > ZT_CLOSED_PATH_PRUNING_INTERVAL) {
  254. _lastPathPrune = now;
  255. prunePaths();
  256. }
  257. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  258. if (_paths[i].p) {
  259. _paths[i].p->measureLink(now);
  260. }
  261. }
  262. /**
  263. * Randomly distribute traffic across all paths
  264. *
  265. * Behavior:
  266. * - If path DOWN: Stop randomly choosing that path
  267. * - If path UP: Start randomly choosing that path
  268. * - If all paths are unresponsive: randomly choose from all paths
  269. */
  270. int numAlivePaths = 0;
  271. int numStalePaths = 0;
  272. if (RR->node->getMultipathMode() == ZT_MULTIPATH_RANDOM) {
  273. int alivePaths[ZT_MAX_PEER_NETWORK_PATHS];
  274. int stalePaths[ZT_MAX_PEER_NETWORK_PATHS];
  275. memset(&alivePaths, -1, sizeof(alivePaths));
  276. memset(&stalePaths, -1, sizeof(stalePaths));
  277. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  278. if (_paths[i].p) {
  279. if (_paths[i].p->isValidState()) {
  280. if (_paths[i].p->alive(now)) {
  281. alivePaths[numAlivePaths] = i;
  282. numAlivePaths++;
  283. }
  284. else {
  285. stalePaths[numStalePaths] = i;
  286. numStalePaths++;
  287. }
  288. }
  289. }
  290. }
  291. unsigned int r;
  292. Utils::getSecureRandom(&r, 1);
  293. if (numAlivePaths > 0) {
  294. // pick a random out of the set deemed "alive"
  295. int rf = r % numAlivePaths;
  296. return _paths[alivePaths[rf]].p;
  297. }
  298. else if(numStalePaths > 0) {
  299. // resort to trying any non-expired path
  300. int rf = r % numStalePaths;
  301. return _paths[stalePaths[rf]].p;
  302. }
  303. }
  304. /**
  305. * Proportionally allocate traffic according to dynamic path quality measurements
  306. */
  307. if (RR->node->getMultipathMode() == ZT_MULTIPATH_PROPORTIONALLY_BALANCED) {
  308. float relq[ZT_MAX_PEER_NETWORK_PATHS];
  309. memset(&relq, 0, sizeof(relq));
  310. float alloc[ZT_MAX_PEER_NETWORK_PATHS];
  311. memset(&alloc, 0, sizeof(alloc));
  312. // Survey
  313. //
  314. // Take a survey of all available link qualities. We use this to determine if we
  315. // can skip this algorithm altogether and if not, to establish baseline for physical
  316. // link quality used in later calculations.
  317. //
  318. // We find the min/max quality of our currently-active links so
  319. // that we can form a relative scale to rank each link proportionally
  320. // to each other link.
  321. uint16_t alivePaths[ZT_MAX_PEER_NETWORK_PATHS];
  322. uint16_t stalePaths[ZT_MAX_PEER_NETWORK_PATHS];
  323. memset(&alivePaths, -1, sizeof(alivePaths));
  324. memset(&stalePaths, -1, sizeof(stalePaths));
  325. uint16_t numAlivePaths = 0;
  326. uint16_t numStalePaths = 0;
  327. float minQuality = 10000;
  328. float maxQuality = -1;
  329. float currQuality;
  330. for(uint16_t i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  331. if (_paths[i].p && _paths[i].p->isValidState()) {
  332. if (!_paths[i].p->monitorsReady()) {
  333. // TODO: This should fix itself anyway but we should test whether forcing the use of a new path will
  334. // aid in establishing flow balance more quickly.
  335. }
  336. // Compute quality here, going forward we will use lastComputedQuality()
  337. currQuality = _paths[i].p->computeQuality(now);
  338. if (!_paths[i].p->stale(now)) {
  339. numAlivePaths++;
  340. }
  341. else {
  342. numStalePaths++;
  343. }
  344. if (currQuality > maxQuality) {
  345. maxQuality = currQuality;
  346. bestPath = i;
  347. }
  348. if (currQuality < minQuality) {
  349. minQuality = currQuality;
  350. }
  351. relq[i] = currQuality;
  352. }
  353. }
  354. // Attempt to find an excuse not to use the rest of this algorithm
  355. if (bestPath == ZT_MAX_PEER_NETWORK_PATHS || (numAlivePaths == 0 && numStalePaths == 0)) {
  356. return SharedPtr<Path>();
  357. } if (numAlivePaths == 1) {
  358. return _paths[bestPath].p;
  359. } if (numStalePaths == 1) {
  360. return _paths[bestPath].p;
  361. }
  362. // Relative quality
  363. //
  364. // The strongest link will have a value of 1.0 whereas every other
  365. // link will have a value which represents some fraction of the strongest link.
  366. float totalRelativeQuality = 0;
  367. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  368. if (_paths[i].p && _paths[i].p->isValidState()) {
  369. relq[i] /= maxQuality ? maxQuality : 1;
  370. totalRelativeQuality += relq[i];
  371. }
  372. }
  373. // Convert the relative quality values into flow allocations.
  374. // Additionally, determine whether each path in the flow is
  375. // contributing more or less than its target allocation. If
  376. // it is contributing more than required, don't allow it to be
  377. // randomly selected for the next packet. If however the path
  378. // needs to contribute more to the flow, we should record
  379. float imbalance = 0;
  380. float qualityScalingFactor = (float)1.0 / totalRelativeQuality;
  381. for(uint16_t i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  382. // Out of the last N packets to this peer, how many were sent by this path?
  383. int numPktSentWithinWin = (int)_pathChoiceHist->countValue(i);
  384. // Compute traffic allocation for each path in the flow
  385. if (_paths[i].p && _paths[i].p->isValidState()) {
  386. // Allocation
  387. // This is the percentage of traffic we want to send over a given path
  388. alloc[i] = relq[i] * qualityScalingFactor;
  389. float currProportion = numPktSentWithinWin / (float)ZT_MULTIPATH_PROPORTION_WIN_SZ;
  390. float targetProportion = alloc[i];
  391. float diffProportion = currProportion - targetProportion;
  392. // Imbalance
  393. //
  394. // This is the sum of the distances of each path's currently observed flow contributions
  395. // from its most recent target allocation. In other words, this is a measure of how closely we
  396. // are adhering to our desired allocations. It is worth noting that this value can be greater
  397. // than 1.0 if a significant change to allocations is made by the algorithm, this will
  398. // eventually correct itself.
  399. imbalance += fabs(diffProportion);
  400. if (diffProportion < 0) {
  401. alloc[i] = targetProportion;
  402. }
  403. else {
  404. alloc[i] = targetProportion;
  405. }
  406. }
  407. }
  408. // Compute and record current flow balance
  409. float balance = (float)1.0 - imbalance;
  410. if (balance >= ZT_MULTIPATH_FLOW_BALANCE_THESHOLD) {
  411. if (!_linkBalanceStatus) {
  412. _linkBalanceStatus = true;
  413. RR->t->peerLinkBalanced(NULL,0,*this);
  414. }
  415. }
  416. else {
  417. if (_linkBalanceStatus) {
  418. _linkBalanceStatus = false;
  419. RR->t->peerLinkImbalanced(NULL,0,*this);
  420. }
  421. }
  422. // Record the current flow balance. Later used for computing a mean flow balance value.
  423. _flowBalanceHist->push(balance);
  424. // Randomly choose path from allocated candidates
  425. unsigned int r;
  426. Utils::getSecureRandom(&r, 1);
  427. float rf = (float)(r %= 100) / 100;
  428. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  429. if (_paths[i].p && _paths[i].p->isValidState() && _paths[i].p->address().isV4()) {
  430. if (alloc[i] > 0 && rf < alloc[i]) {
  431. bestPath = i;
  432. _pathChoiceHist->push(bestPath); // Record which path we chose
  433. break;
  434. }
  435. if (alloc[i] > 0) {
  436. rf -= alloc[i];
  437. }
  438. else {
  439. rf -= alloc[i]*-1;
  440. }
  441. }
  442. }
  443. if (bestPath < ZT_MAX_PEER_NETWORK_PATHS) {
  444. return _paths[bestPath].p;
  445. }
  446. return SharedPtr<Path>();
  447. }
  448. // Adhere to a user-defined interface/allocation scheme
  449. if (RR->node->getMultipathMode() == ZT_MULTIPATH_MANUALLY_BALANCED) {
  450. // TODO
  451. }
  452. return SharedPtr<Path>();
  453. }
  454. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  455. {
  456. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  457. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  458. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  459. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  460. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  461. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  462. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  463. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  464. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  465. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  466. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  467. myBestV4QualityByScope[i] = 2147483647;
  468. myBestV6QualityByScope[i] = 2147483647;
  469. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  470. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  471. theirBestV4QualityByScope[i] = 2147483647;
  472. theirBestV6QualityByScope[i] = 2147483647;
  473. }
  474. Mutex::Lock _l1(_paths_m);
  475. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  476. if (_paths[i].p) {
  477. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  478. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  479. switch(_paths[i].p->address().ss_family) {
  480. case AF_INET:
  481. if (q <= myBestV4QualityByScope[s]) {
  482. myBestV4QualityByScope[s] = q;
  483. myBestV4ByScope[s] = i;
  484. }
  485. break;
  486. case AF_INET6:
  487. if (q <= myBestV6QualityByScope[s]) {
  488. myBestV6QualityByScope[s] = q;
  489. myBestV6ByScope[s] = i;
  490. }
  491. break;
  492. }
  493. } else break;
  494. }
  495. Mutex::Lock _l2(other->_paths_m);
  496. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  497. if (other->_paths[i].p) {
  498. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  499. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  500. switch(other->_paths[i].p->address().ss_family) {
  501. case AF_INET:
  502. if (q <= theirBestV4QualityByScope[s]) {
  503. theirBestV4QualityByScope[s] = q;
  504. theirBestV4ByScope[s] = i;
  505. }
  506. break;
  507. case AF_INET6:
  508. if (q <= theirBestV6QualityByScope[s]) {
  509. theirBestV6QualityByScope[s] = q;
  510. theirBestV6ByScope[s] = i;
  511. }
  512. break;
  513. }
  514. } else break;
  515. }
  516. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  517. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  518. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  519. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  520. mine = myBestV6ByScope[s];
  521. theirs = theirBestV6ByScope[s];
  522. break;
  523. }
  524. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  525. mine = myBestV4ByScope[s];
  526. theirs = theirBestV4ByScope[s];
  527. break;
  528. }
  529. }
  530. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  531. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  532. const unsigned int completed = alt + 2;
  533. while (alt != completed) {
  534. if ((alt & 1) == 0) {
  535. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  536. outp.append((uint8_t)0);
  537. other->_id.address().appendTo(outp);
  538. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  539. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  540. outp.append((uint8_t)16);
  541. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  542. } else {
  543. outp.append((uint8_t)4);
  544. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  545. }
  546. outp.armor(_key,true);
  547. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  548. } else {
  549. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  550. outp.append((uint8_t)0);
  551. _id.address().appendTo(outp);
  552. outp.append((uint16_t)_paths[mine].p->address().port());
  553. if (_paths[mine].p->address().ss_family == AF_INET6) {
  554. outp.append((uint8_t)16);
  555. outp.append(_paths[mine].p->address().rawIpData(),16);
  556. } else {
  557. outp.append((uint8_t)4);
  558. outp.append(_paths[mine].p->address().rawIpData(),4);
  559. }
  560. outp.armor(other->_key,true);
  561. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  562. }
  563. ++alt;
  564. }
  565. }
  566. }
  567. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  568. {
  569. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  570. outp.append((unsigned char)ZT_PROTO_VERSION);
  571. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  572. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  573. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  574. outp.append(now);
  575. RR->identity.serialize(outp,false);
  576. atAddress.serialize(outp);
  577. outp.append((uint64_t)RR->topology->planetWorldId());
  578. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  579. const unsigned int startCryptedPortionAt = outp.size();
  580. std::vector<World> moons(RR->topology->moons());
  581. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  582. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  583. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  584. outp.append((uint8_t)m->type());
  585. outp.append((uint64_t)m->id());
  586. outp.append((uint64_t)m->timestamp());
  587. }
  588. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  589. outp.append((uint8_t)World::TYPE_MOON);
  590. outp.append(*m);
  591. outp.append((uint64_t)0);
  592. }
  593. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  594. RR->node->expectReplyTo(outp.packetId());
  595. if (atAddress) {
  596. outp.armor(_key,false); // false == don't encrypt full payload, but add MAC
  597. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  598. } else {
  599. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  600. }
  601. }
  602. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
  603. {
  604. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  605. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  606. RR->node->expectReplyTo(outp.packetId());
  607. outp.armor(_key,true);
  608. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  609. } else {
  610. sendHELLO(tPtr,localSocket,atAddress,now);
  611. }
  612. }
  613. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  614. {
  615. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  616. _lastTriedMemorizedPath = now;
  617. InetAddress mp;
  618. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  619. attemptToContactAt(tPtr,-1,mp,now,true);
  620. }
  621. }
  622. unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
  623. {
  624. unsigned int sent = 0;
  625. Mutex::Lock _l(_paths_m);
  626. const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
  627. _lastSentFullHello = now;
  628. // Right now we only keep pinging links that have the maximum priority. The
  629. // priority is used to track cluster redirections, meaning that when a cluster
  630. // redirects us its redirect target links override all other links and we
  631. // let those old links expire.
  632. long maxPriority = 0;
  633. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  634. if (_paths[i].p)
  635. maxPriority = std::max(_paths[i].priority,maxPriority);
  636. else break;
  637. }
  638. unsigned int j = 0;
  639. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  640. if (_paths[i].p) {
  641. // Clean expired and reduced priority paths
  642. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  643. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))) {
  644. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  645. _paths[i].p->sent(now);
  646. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  647. }
  648. if (i != j)
  649. _paths[j] = _paths[i];
  650. ++j;
  651. }
  652. } else break;
  653. }
  654. if (RR->node->getMultipathMode() != ZT_MULTIPATH_NONE) {
  655. while(j < ZT_MAX_PEER_NETWORK_PATHS) {
  656. _paths[j].lr = 0;
  657. _paths[j].p.zero();
  658. _paths[j].priority = 1;
  659. ++j;
  660. }
  661. }
  662. return sent;
  663. }
  664. unsigned int Peer::prunePaths()
  665. {
  666. Mutex::Lock _l(_paths_m);
  667. unsigned int pruned = 0;
  668. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  669. if (_paths[i].p) {
  670. if(_paths[i].p->isClosed() || !_paths[i].p->isValidState()) {
  671. _paths[i].lr = 0;
  672. _paths[i].p.zero();
  673. _paths[i].priority = 1;
  674. pruned++;
  675. }
  676. }
  677. }
  678. return pruned;
  679. }
  680. void Peer::clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now)
  681. {
  682. SharedPtr<Path> np(RR->topology->getPath(originatingPath->localSocket(),remoteAddress));
  683. RR->t->peerRedirected(tPtr,0,*this,np);
  684. attemptToContactAt(tPtr,originatingPath->localSocket(),remoteAddress,now,true);
  685. {
  686. Mutex::Lock _l(_paths_m);
  687. // New priority is higher than the priority of the originating path (if known)
  688. long newPriority = 1;
  689. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  690. if (_paths[i].p) {
  691. if (_paths[i].p == originatingPath) {
  692. newPriority = _paths[i].priority;
  693. break;
  694. }
  695. } else break;
  696. }
  697. newPriority += 2;
  698. // Erase any paths with lower priority than this one or that are duplicate
  699. // IPs and add this path.
  700. unsigned int j = 0;
  701. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  702. if (_paths[i].p) {
  703. if ((_paths[i].priority >= newPriority)&&(!_paths[i].p->address().ipsEqual2(remoteAddress))) {
  704. if (i != j)
  705. _paths[j] = _paths[i];
  706. ++j;
  707. }
  708. }
  709. }
  710. if (j < ZT_MAX_PEER_NETWORK_PATHS) {
  711. _paths[j].lr = now;
  712. _paths[j].p = np;
  713. _paths[j].priority = newPriority;
  714. ++j;
  715. while (j < ZT_MAX_PEER_NETWORK_PATHS) {
  716. _paths[j].lr = 0;
  717. _paths[j].p.zero();
  718. _paths[j].priority = 1;
  719. ++j;
  720. }
  721. }
  722. }
  723. }
  724. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  725. {
  726. Mutex::Lock _l(_paths_m);
  727. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  728. if (_paths[i].p) {
  729. if ((_paths[i].p->address().ss_family == inetAddressFamily)&&(_paths[i].p->ipScope() == scope)) {
  730. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,false);
  731. _paths[i].p->sent(now);
  732. _paths[i].lr = 0; // path will not be used unless it speaks again
  733. }
  734. } else break;
  735. }
  736. }
  737. } // namespace ZeroTier