Peer.cpp 25 KB

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