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. 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 = (float)(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 = (float)(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. alivePaths[i] = currQuality;
  340. numAlivePaths++;
  341. }
  342. else {
  343. stalePaths[i] = currQuality;
  344. numStalePaths++;
  345. }
  346. if (currQuality > maxQuality) {
  347. maxQuality = currQuality;
  348. bestPath = i;
  349. }
  350. if (currQuality < minQuality) {
  351. minQuality = currQuality;
  352. }
  353. relq[i] = currQuality;
  354. }
  355. }
  356. // Attempt to find an excuse not to use the rest of this algorithm
  357. if (bestPath == ZT_MAX_PEER_NETWORK_PATHS || (numAlivePaths == 0 && numStalePaths == 0)) {
  358. return SharedPtr<Path>();
  359. } if (numAlivePaths == 1) {
  360. return _paths[bestPath].p;
  361. } if (numStalePaths == 1) {
  362. return _paths[bestPath].p;
  363. }
  364. // Relative quality
  365. //
  366. // The strongest link will have a value of 1.0 whereas every other
  367. // link will have a value which represents some fraction of the strongest link.
  368. float totalRelativeQuality = 0;
  369. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  370. if (_paths[i].p && _paths[i].p->isValidState()) {
  371. relq[i] /= maxQuality ? maxQuality : 1;
  372. totalRelativeQuality += relq[i];
  373. }
  374. }
  375. // Convert the relative quality values into flow allocations.
  376. // Additionally, determine whether each path in the flow is
  377. // contributing more or less than its target allocation. If
  378. // it is contributing more than required, don't allow it to be
  379. // randomly selected for the next packet. If however the path
  380. // needs to contribute more to the flow, we should record
  381. float imbalance = 0;
  382. float qualityScalingFactor = 1.0 / totalRelativeQuality;
  383. for(uint16_t i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  384. // Out of the last N packets to this peer, how many were sent by this path?
  385. int numPktSentWithinWin = (int)_pathChoiceHist->countValue((float)i);
  386. // Compute traffic allocation for each path in the flow
  387. if (_paths[i].p && _paths[i].p->isValidState()) {
  388. // Allocation
  389. // This is the percentage of traffic we want to send over a given path
  390. alloc[i] = relq[i] * qualityScalingFactor;
  391. float currProportion = numPktSentWithinWin / (float)ZT_MULTIPATH_PROPORTION_WIN_SZ;
  392. float targetProportion = alloc[i];
  393. float diffProportion = currProportion - targetProportion;
  394. // Imbalance
  395. //
  396. // This is the sum of the distances of each path's currently observed flow contributions
  397. // from its most recent target allocation. In other words, this is a measure of how closely we
  398. // are adhering to our desired allocations. It is worth noting that this value can be greater
  399. // than 1.0 if a significant change to allocations is made by the algorithm, this will
  400. // eventually correct itself.
  401. imbalance += fabs(diffProportion);
  402. if (diffProportion < 0) {
  403. alloc[i] = targetProportion;
  404. }
  405. else {
  406. alloc[i] = targetProportion;
  407. }
  408. }
  409. }
  410. // Compute and record current flow balance
  411. float balance = 1.0 - imbalance;
  412. if (balance >= ZT_MULTIPATH_FLOW_BALANCE_THESHOLD) {
  413. if (!_linkBalanceStatus) {
  414. _linkBalanceStatus = true;
  415. RR->t->peerLinkBalanced(NULL,0,*this);
  416. }
  417. }
  418. else {
  419. if (_linkBalanceStatus) {
  420. _linkBalanceStatus = false;
  421. RR->t->peerLinkImbalanced(NULL,0,*this);
  422. }
  423. }
  424. // Record the current flow balance. Later used for computing a mean flow balance value.
  425. _flowBalanceHist->push(balance);
  426. // Randomly choose path from allocated candidates
  427. unsigned int r;
  428. Utils::getSecureRandom(&r, 1);
  429. float rf = (float)(r %= 100) / 100;
  430. for(int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  431. if (_paths[i].p && _paths[i].p->isValidState() && _paths[i].p->address().isV4()) {
  432. if (alloc[i] > 0 && rf < alloc[i]) {
  433. bestPath = i;
  434. _pathChoiceHist->push(bestPath); // Record which path we chose
  435. break;
  436. }
  437. if (alloc[i] > 0) {
  438. rf -= alloc[i];
  439. }
  440. else {
  441. rf -= alloc[i]*-1;
  442. }
  443. }
  444. }
  445. if (bestPath < ZT_MAX_PEER_NETWORK_PATHS) {
  446. return _paths[bestPath].p;
  447. }
  448. return SharedPtr<Path>();
  449. }
  450. // Adhere to a user-defined interface/allocation scheme
  451. if (RR->node->getMultipathMode() == ZT_MULTIPATH_MANUALLY_BALANCED) {
  452. // TODO
  453. }
  454. return SharedPtr<Path>();
  455. }
  456. void Peer::introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const
  457. {
  458. unsigned int myBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  459. unsigned int myBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  460. long myBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  461. long myBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  462. unsigned int theirBestV4ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  463. unsigned int theirBestV6ByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  464. long theirBestV4QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  465. long theirBestV6QualityByScope[ZT_INETADDRESS_MAX_SCOPE+1];
  466. for(int i=0;i<=ZT_INETADDRESS_MAX_SCOPE;++i) {
  467. myBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  468. myBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  469. myBestV4QualityByScope[i] = 2147483647;
  470. myBestV6QualityByScope[i] = 2147483647;
  471. theirBestV4ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  472. theirBestV6ByScope[i] = ZT_MAX_PEER_NETWORK_PATHS;
  473. theirBestV4QualityByScope[i] = 2147483647;
  474. theirBestV6QualityByScope[i] = 2147483647;
  475. }
  476. Mutex::Lock _l1(_paths_m);
  477. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  478. if (_paths[i].p) {
  479. const long q = _paths[i].p->quality(now) / _paths[i].priority;
  480. const unsigned int s = (unsigned int)_paths[i].p->ipScope();
  481. switch(_paths[i].p->address().ss_family) {
  482. case AF_INET:
  483. if (q <= myBestV4QualityByScope[s]) {
  484. myBestV4QualityByScope[s] = q;
  485. myBestV4ByScope[s] = i;
  486. }
  487. break;
  488. case AF_INET6:
  489. if (q <= myBestV6QualityByScope[s]) {
  490. myBestV6QualityByScope[s] = q;
  491. myBestV6ByScope[s] = i;
  492. }
  493. break;
  494. }
  495. } else break;
  496. }
  497. Mutex::Lock _l2(other->_paths_m);
  498. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  499. if (other->_paths[i].p) {
  500. const long q = other->_paths[i].p->quality(now) / other->_paths[i].priority;
  501. const unsigned int s = (unsigned int)other->_paths[i].p->ipScope();
  502. switch(other->_paths[i].p->address().ss_family) {
  503. case AF_INET:
  504. if (q <= theirBestV4QualityByScope[s]) {
  505. theirBestV4QualityByScope[s] = q;
  506. theirBestV4ByScope[s] = i;
  507. }
  508. break;
  509. case AF_INET6:
  510. if (q <= theirBestV6QualityByScope[s]) {
  511. theirBestV6QualityByScope[s] = q;
  512. theirBestV6ByScope[s] = i;
  513. }
  514. break;
  515. }
  516. } else break;
  517. }
  518. unsigned int mine = ZT_MAX_PEER_NETWORK_PATHS;
  519. unsigned int theirs = ZT_MAX_PEER_NETWORK_PATHS;
  520. for(int s=ZT_INETADDRESS_MAX_SCOPE;s>=0;--s) {
  521. if ((myBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV6ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  522. mine = myBestV6ByScope[s];
  523. theirs = theirBestV6ByScope[s];
  524. break;
  525. }
  526. if ((myBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)&&(theirBestV4ByScope[s] != ZT_MAX_PEER_NETWORK_PATHS)) {
  527. mine = myBestV4ByScope[s];
  528. theirs = theirBestV4ByScope[s];
  529. break;
  530. }
  531. }
  532. if (mine != ZT_MAX_PEER_NETWORK_PATHS) {
  533. unsigned int alt = (unsigned int)RR->node->prng() & 1; // randomize which hint we send first for black magickal NAT-t reasons
  534. const unsigned int completed = alt + 2;
  535. while (alt != completed) {
  536. if ((alt & 1) == 0) {
  537. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  538. outp.append((uint8_t)0);
  539. other->_id.address().appendTo(outp);
  540. outp.append((uint16_t)other->_paths[theirs].p->address().port());
  541. if (other->_paths[theirs].p->address().ss_family == AF_INET6) {
  542. outp.append((uint8_t)16);
  543. outp.append(other->_paths[theirs].p->address().rawIpData(),16);
  544. } else {
  545. outp.append((uint8_t)4);
  546. outp.append(other->_paths[theirs].p->address().rawIpData(),4);
  547. }
  548. outp.armor(_key,true);
  549. _paths[mine].p->send(RR,tPtr,outp.data(),outp.size(),now);
  550. } else {
  551. Packet outp(other->_id.address(),RR->identity.address(),Packet::VERB_RENDEZVOUS);
  552. outp.append((uint8_t)0);
  553. _id.address().appendTo(outp);
  554. outp.append((uint16_t)_paths[mine].p->address().port());
  555. if (_paths[mine].p->address().ss_family == AF_INET6) {
  556. outp.append((uint8_t)16);
  557. outp.append(_paths[mine].p->address().rawIpData(),16);
  558. } else {
  559. outp.append((uint8_t)4);
  560. outp.append(_paths[mine].p->address().rawIpData(),4);
  561. }
  562. outp.armor(other->_key,true);
  563. other->_paths[theirs].p->send(RR,tPtr,outp.data(),outp.size(),now);
  564. }
  565. ++alt;
  566. }
  567. }
  568. }
  569. void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now)
  570. {
  571. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_HELLO);
  572. outp.append((unsigned char)ZT_PROTO_VERSION);
  573. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  574. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  575. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  576. outp.append(now);
  577. RR->identity.serialize(outp,false);
  578. atAddress.serialize(outp);
  579. outp.append((uint64_t)RR->topology->planetWorldId());
  580. outp.append((uint64_t)RR->topology->planetWorldTimestamp());
  581. const unsigned int startCryptedPortionAt = outp.size();
  582. std::vector<World> moons(RR->topology->moons());
  583. std::vector<uint64_t> moonsWanted(RR->topology->moonsWanted());
  584. outp.append((uint16_t)(moons.size() + moonsWanted.size()));
  585. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  586. outp.append((uint8_t)m->type());
  587. outp.append((uint64_t)m->id());
  588. outp.append((uint64_t)m->timestamp());
  589. }
  590. for(std::vector<uint64_t>::const_iterator m(moonsWanted.begin());m!=moonsWanted.end();++m) {
  591. outp.append((uint8_t)World::TYPE_MOON);
  592. outp.append(*m);
  593. outp.append((uint64_t)0);
  594. }
  595. outp.cryptField(_key,startCryptedPortionAt,outp.size() - startCryptedPortionAt);
  596. RR->node->expectReplyTo(outp.packetId());
  597. if (atAddress) {
  598. outp.armor(_key,false); // false == don't encrypt full payload, but add MAC
  599. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  600. } else {
  601. RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
  602. }
  603. }
  604. void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
  605. {
  606. if ( (!sendFullHello) && (_vProto >= 5) && (!((_vMajor == 1)&&(_vMinor == 1)&&(_vRevision == 0))) ) {
  607. Packet outp(_id.address(),RR->identity.address(),Packet::VERB_ECHO);
  608. RR->node->expectReplyTo(outp.packetId());
  609. outp.armor(_key,true);
  610. RR->node->putPacket(tPtr,localSocket,atAddress,outp.data(),outp.size());
  611. } else {
  612. sendHELLO(tPtr,localSocket,atAddress,now);
  613. }
  614. }
  615. void Peer::tryMemorizedPath(void *tPtr,int64_t now)
  616. {
  617. if ((now - _lastTriedMemorizedPath) >= ZT_TRY_MEMORIZED_PATH_INTERVAL) {
  618. _lastTriedMemorizedPath = now;
  619. InetAddress mp;
  620. if (RR->node->externalPathLookup(tPtr,_id.address(),-1,mp))
  621. attemptToContactAt(tPtr,-1,mp,now,true);
  622. }
  623. }
  624. unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
  625. {
  626. unsigned int sent = 0;
  627. Mutex::Lock _l(_paths_m);
  628. const bool sendFullHello = ((now - _lastSentFullHello) >= ZT_PEER_PING_PERIOD);
  629. _lastSentFullHello = now;
  630. // Right now we only keep pinging links that have the maximum priority. The
  631. // priority is used to track cluster redirections, meaning that when a cluster
  632. // redirects us its redirect target links override all other links and we
  633. // let those old links expire.
  634. long maxPriority = 0;
  635. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  636. if (_paths[i].p)
  637. maxPriority = std::max(_paths[i].priority,maxPriority);
  638. else break;
  639. }
  640. unsigned int j = 0;
  641. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  642. if (_paths[i].p) {
  643. // Clean expired and reduced priority paths
  644. if ( ((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION) && (_paths[i].priority == maxPriority) ) {
  645. if ((sendFullHello)||(_paths[i].p->needsHeartbeat(now))) {
  646. attemptToContactAt(tPtr,_paths[i].p->localSocket(),_paths[i].p->address(),now,sendFullHello);
  647. _paths[i].p->sent(now);
  648. sent |= (_paths[i].p->address().ss_family == AF_INET) ? 0x1 : 0x2;
  649. }
  650. if (i != j)
  651. _paths[j] = _paths[i];
  652. ++j;
  653. }
  654. } else break;
  655. }
  656. if (RR->node->getMultipathMode() != ZT_MULTIPATH_NONE) {
  657. while(j < ZT_MAX_PEER_NETWORK_PATHS) {
  658. _paths[j].lr = 0;
  659. _paths[j].p.zero();
  660. _paths[j].priority = 1;
  661. ++j;
  662. }
  663. }
  664. return sent;
  665. }
  666. unsigned int Peer::prunePaths()
  667. {
  668. Mutex::Lock _l(_paths_m);
  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